引入
由于软件需求,需要在QTableWidget中使用自定义控件显示数据,使用CellWidget
在数据过多时会明显卡顿,遂找寻另外办法解决。
解决
使用自定义代理重写paint
函数以进行优化。
此处以QLabel
为例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class TestDelegate : public QStyledItemDelegate { public: explicit TestDelegate(QObject *parent = nullptr); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index); private: QLabel *mLabel; }
TestDelegate::TestDelegate(QObject *parent) : QStyledItemDelegate(parent) , mLabel(new QLabelInfoLabel) {}
void TestDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) { if(index.column() == 2) { mLabel->setText(index.data(Qt::UserRole + 1).toString()); QPixmap pixmap(mLabel->size()); pixmap.fill(QColor(0,0,0,0)); mLabel->render(&pixmap); QApplication::style()->drawItemPixmap(painter, option.rect, Qt::AlignCenter, pixmap); } }
|
使用时将QLabel
更换为自定义控件并设置内容或状态,进行渲染即可。
总结
Qt
-MVD
的精髓还是在与三者之间的协作,更高阶的使用还是要在实际情况中具体情况具体设计。