Data type comparison problem
-
Hi,
I'm trying to align data in QTableView columns based on their data type. Data are retrieved from MySQL database through QSqlTableModel. I tried to compare the type of data at the data function subclassed from QSqlTableModel, with the following code:
@
QVariant TableModel::data(const QModelIndex &index, int role) const
{
QVariant dtype = QSqlTableModel::data(index, role).type();
qDebug() << "Data Type:" << dtype;if (role == Qt::TextAlignmentRole) { if (dtype == QVariant::String) return Qt::AlignLeft + Qt::AlignVCenter; else return Qt::AlignRight + Qt::AlignVCenter; } return QSqlTableModel::data(index, role);
}
@The comparison doesn't seem to work as expected, making all columns appear as right aligned.
Where did I go wrong? Can anyone help, please? -
maybe
@QVariant dtype = QSqlTableModel::data(index, role).type();@
should be
@QVariant::Type dtype = QSqlTableModel::data(index, role).type();@
QVariant::type() returns enum not another QVairant.
PS: QVariant::QVariant ( Type type ) Constructs a null variant of type type. From docs.
-
The QVariant::Type might be any kind of variable able to hold the enumarator value. An int might be enough ;-)
Maybe remove the local variable at all? KISS is always a good advice. so maybe more like:
@
data()
{
qDebug() << QSqlTableModel::data(index.role).type();
if (role == Qt::TextAlignmentRole)
{
if (QSqlTableModel::data(index, role).type() == Qt::TextAlignmentRole)
{
// do your return stuff
}
}
}
@ -
Thank you all for the replies. Changed the code with:
@
QVariant::Type dtype = QSqlTableModel::data(index, role).type();
@
as it should, then added more qDebug between the lines, and found out that Qt spits out empty data while role == Qt::TextAlignmentRole. So I went back to the Docs and decided to reimplement views rendering using delegates. More in line to MVC pattern, I think.