[Interest] Using QSqlTableModel to populate a QComboBox -- Good? Other approaches?

K. Frank kfrank29.c at gmail.com
Wed Jun 13 19:22:00 CEST 2012


Hello List!

I have a single-column database table containing a small number of items
with which I populate a QComboBox.  (I am using this table to emulate an
enum in sql.)

Looking at various examples, I came up with a scheme using QSqlTable
model that seems to be a "Qt-approved" way of doing this:

   class EnumDialog : public QDialog, private Ui::EnumDialog {
     Q_OBJECT
     public:
       EnumDialog (QWidget *parent = 0);
       ~EnumDialog();
     private:
       QSqlTableModel *enumModel;
   };

   EnumDialog::EnumDialog (QWidget *parent) {
     setupUi (this);
     enumModel = new QSqlTableModel (0, QSqlDatabase::database());
     enumModel->setTable ("enum_table");
     enumModel->select();
     enumComboBox->setModel (enumModel);
   }

(EnumDialog is a Designer-designed dialog that contains the QComboBox
enumComboBox.)

As a practical matter, I could just hard-code the combo-box entries,
making sure by hand that they're in sync with the contents of the
database table, but I thought I'd be 'fancy" and try it this way.

This method seems to work fine.  But I'm not that familiar with the Qt
database classes so I'd like to ask whether the above approach is a
good idea, and whether there are other alternatives I might want to
look at.

My main goals are to have the code be simple and concise, and have
it be sensible from a Qt perspective.  As there are only a handful of
entries in enum_table, any method significantly more complicated
than populating the combo box by hand would seem to be overkill.
(I'm happy to leverage the power of the Qt database classes under
the hood, but I wouldn't want to do any database heavy lifting by hand.)

Thanks for any wisdom.


K. Frank



More information about the Interest mailing list