I work with QSqlTableModel, I make 3 delegates QDoubleSpinBox, QLineEdit, QDateTime I override the standard methods. The problem is that these delegates can only be set 1) for the entire table 2) for specific columns 3) for specific rows. But my data from the table is loaded from Postgres DB and there are dozens of tables. I need to click on a cell, automatically determine its type, for example, if it contains the string QString, it uses the QLineEdit delegag, and if there are real numbers QDoubleSpinBox, if the time is May 30, 2016, it is a QDateTime delegate. How will this implementation look like in code? Any examples?

Or how to do so, there is a QDoubleSpinBox delegate, it is necessary that it be applied not to the entire table but only to cells where the type is double.

    1 answer 1

    If we take the implementation of a regular delegate, then its modification to support several data types should not be complicated. The model always returns data in the form of QVariant , which in turn has the QVariant::type() method. Then, based on the resulting data type, all that remains is to create and return the corresponding widget:

     QWidget *Delegate::createEditor(QWidget *parent , const QStyleOptionViewItem &option , const QModelIndex &index) const { Q_UNUSED(option); QWidget *wdg = Q_NULLPTR; if(index.data().type() == QVariant::Double) wdg = new QDoubleSpinBox(parent); else if(index.data().type() == QVariant::String) wdg = new QLineEdit(parent); else if(index.data().type() == QVariant::Int) wdg = new QSpinBox(parent); // и т.д. else if ... return wdg; } 

    Accordingly, you will need to override the delegate's setEditorData() and setModelData() .

    • alexis, thank you, you helped - Disastricks
    • @DavidRise, no problem. - alexis031182