我需要将一个自定义小部件放入子类 QAbstractTableModel
的 QTableView
单元格中。
我搜索了已经给出的解决方案,但没有人满足我的需求。
自定义小部件必须始终保留在此处,而不仅仅是像 QItemDelegate::createEditor
那样处于编辑模式。
自定义小部件可能是一切,我正在寻找所有小部件的通用解决方案,而不仅仅是 QPushButtons
或 QCheckBox
。
抱歉我的英语不好。
最佳答案
您可以使用QAbstractItemView::setIndexWidget
并压倒一切QAbstractItemView::dataChanged
实现您想要的目标如下:
class MyTableView : public QTableView
{
protected:
void dataChanged(const QModelIndex &topLeft, const QModelIndex & bottomRight, const QVector<int> & roles)
{
QPushButton *pPushButton = qobject_cast<QPushButton*>(indexWidget(topLeft));
if (pPushButton)
pPushButton->setText(model()->data(topLeft, Qt::DisplayRole).toString());
else
QTableView::dataChanged(topLeft, bottomRight, roles);
}
};
void main ()
{
MyTableView table;
table.setIndexWidget(table.model()->index(0, 0, QModelIndex()),new QPushButton());
}
请注意,这是一个不完整的实现,但它应该向您展示如何解决您的问题。真正的实现应该更新topLeft和bottomRight之间的所有QPushButton。
关于c++ - Qt 在 QTableView 中设置自定义小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43277569/