I have a QTableView
with some data (numbers), but each cell contains an unwanted rounded square (maybe a non-functional checkbox). They look bad, occupy space, and can obscure my data.
Why do they appear? How can I remove them?
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QTableView>
#include <QHeaderView>
class MyModel : public QAbstractTableModel
{
public:
int rowCount(const QModelIndex& index) const override {return 5;}
int columnCount(const QModelIndex& index) const override {return 2;}
QVariant data(const QModelIndex& index, int role) const override
{
if (role == Qt::DisplayRole)
return 3000 + index.row() * 100 + index.column();
else
return 0;
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow w;
QTableView widget;
MyModel model;
widget.setModel(&model);
widget.horizontalHeader()->hide();
widget.verticalHeader()->hide();
w.setCentralWidget(&widget);
w.show();
return a.exec();
}
I use Qt 6.8.0 on Windows 11.
The QAbstractItemModel::data()
documentation states:
Note: If you do not have a value to return, return an invalid (default-constructed)
QVariant
.
There are many roles defined, but you are only looking for Qt::DisplayRole
and then you are returning 0
for all the rest. Chances are, you are being queried for Qt::CheckStateRole
and thus returning a "false" checked state for it, which would explain why the check boxes appear.
Roles describing appearance and meta data (with associated types):
Constant Value Description ... ... ... Qt::CheckStateRole 10 This role is used to obtain the checked state of an item. (Qt::CheckState) ... ... ...
So, do what the documentation says - return an empty QVariant
instead:
QVariant data(const QModelIndex& index, int role) const override
{
if (role == Qt::DisplayRole)
return 3000 + index.row() * 100 + index.column();
else
// return 0;
return QVariant(); // <-- HERE
}