Doubts with QtableModel
-
Hello everybody,
I am doing this tutorial http://doc.qt.io/archives/qt-4.8/modelview.html#
And I come up some questions regarding to the following code:#include <QAbstractTableModel> class MyModel : public QAbstractTableModel { Q_OBJECT public: MyModel(QObject *parent); int rowCount(const QModelIndex &parent = QModelIndex()) const ; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; };
When we create the constructor MyModel(QObject *parent);
why do we pass to MyModel pointer to QObject named parent, is parent any reserved class referring to parent class from QObject?Second,
QVariant MyModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { return QString("Row%1, Column%2") .arg(index.row() + 1) .arg(index.column() +1); } return QVariant(); }
Are we returning twice 2 different objects? first we return QStringobject and then QVariant. How is possible that a Method returning 2 different objects?
Thank you very much!
-
@jss193 said in Doubts with QtableModel:
When we create the constructor MyModel(QObject *parent);
why do we pass to MyModel pointer to QObject named parentAll QObjects can form parent-child relationships. A parent object manages the memory of its children.
Read more:
- http://doc.qt.io/qt-5/objecttrees.html
- http://doc.qt.io/qt-5/qobject.html#details
- http://doc.qt.io/qt-5/qobject.html#QObject
- http://doc.qt.io/qt-5/qobject.html#children
QVariant MyModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { return QString("Row%1, Column%2") .arg(index.row() + 1) .arg(index.column() +1); } return QVariant(); }
Are we returning twice 2 different objects? first we return QStringobject and then QVariant. How is possible that a Method returning 2 different objects?
Notice the
if()
statement. It only lets you return one object:- If the role is
Qt::DisplayRole
, the function returns aQString
. - If the role is not
Qt::DisplayRole
, the function returns an emptyQVariant
.
I am doing this tutorial http://doc.qt.io/archives/qt-4.8/modelview.html#
Are you using Qt 4? If not, follow the Qt 5 documentation instead:
-
@JKSH said in Doubts with QtableModel:
If the role is Qt::DisplayRole, the function returns a QString.
Which is implicitly converted into a QVariant by the compiler :)
-
@jss193
@Christian-Ehrlicher's conversion happens without you doing anything because there is an implicit conversion defined fromQString
toQVariant
. Really you are returning aQVariant::QVariant(QString(...))
, http://doc.qt.io/qt-5/qvariant.html#QVariant-16, so you are not returning "two different types".