3

Is there any way to check properties and constraints for each column in a QSqlRelationalTableModel? For example, I'd like to ask my QSqlRelationalTableModel object whether a certain column can contain nulls, or what datatype is valid for that column.

2 Answers 2

3

You'll need to get a QSqlField value for each column of the model, which is given by

QSqlRecord record = model->database().record(model->tableName());
QSqlField field = record.field(columnIndex);

then you'll be able to check if a field can be null with QSqlField::requiredStatus() (if the driver supports querying that property) and to get its data type with QSqlField::type().

Sign up to request clarification or add additional context in comments.

Comments

2

From alexisdm's answer above, I wrote this simple code snippet to output the properties of each field in a table. Posting it here to save typing for anyone else who is interested.

I also discovered a gotcha: if you use table_model::record() or table_model::record(int) you get unexpected (to me) results for some properties, e.g., isAutoValue seems to always return false, even for fields designated as autoincrement fields in the database. However, you do get a real value for typeID() (though I haven't been able to determine what typeID() is), whereas typeID() always returned -1 for me using model->database().record(model->tableName()).

  QSqlRecord record = table_model->database().record(table_model->tableName());
  // the following get isAutoValue() wrong; but have a real typeID()
  //QSqlRecord record = table_model->record();  
  //QSqlRecord record = table_model->record(table_model->rowCount() - 1);
  qDebug() << "********** table" << table_model->tableName() << "*********";
  for (int i = 0; i < table_model->columnCount(); ++i) {
    QSqlField field = record.field(i);
    qDebug() << "---------- field" << i << field.name() << "--------";
    qDebug() << "default value" << field.defaultValue();
    qDebug() << "is auto value" << field.isAutoValue();
    qDebug() << "is generated" << field.isGenerated();
    qDebug() << "is null" << field.isNull();
    qDebug() << "is read only" << field.isReadOnly();
    qDebug() << "is valid" << field.isValid();
    qDebug() << "length" << field.length();
    qDebug() << "precision" << field.precision();
    qDebug() << "required status" << field.requiredStatus();
    qDebug() << "type" << field.type();
    qDebug() << "type id" << field.typeID();
    qDebug() << "value" << field.value();
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.