Qt-关于在表格中插入控件的优化方法

引入

由于软件需求,需要在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
// TestDelegate.h
class TestDelegate
: public QStyledItemDelegate
{
public:
explicit TestDelegate(QObject *parent = nullptr);

void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index);

private
QLabel *mLabel;
}
// TestDelegate.cpp
TestDelegate::TestDelegate(QObject *parent)
: QStyledItemDelegate(parent)
, mLabel(new QLabelInfoLabel)
{}

void TestDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index)
{
// 需要绘制控件所在列数
if(index.column() == 2)
{
// 通过QTableWidget设置目标位置item数据(item->setData(Qt::UserRole + 1,"Test"),此处获取
mLabel->setText(index.data(Qt::UserRole + 1).toString());
QPixmap pixmap(mLabel->size());
// 设置背景,不设置会异常
pixmap.fill(QColor(0,0,0,0));
// 将mLabel内容渲染到pixmap
mLabel->render(&pixmap);
// 绘制pixmap
QApplication::style()->drawItemPixmap(painter, option.rect, Qt::AlignCenter, pixmap);
}
}

使用时将QLabel更换为自定义控件并设置内容或状态,进行渲染即可。

总结

Qt-MVD的精髓还是在与三者之间的协作,更高阶的使用还是要在实际情况中具体情况具体设计。