QTreeView 如何实现重绘,请用c++实现
时间: 2024-03-05 14:52:42 浏览: 17
QTreeView 可以通过重写 `paintEvent()` 函数实现重绘。在绘制每个单元格时,可以使用 `QStyle` 类提供的绘图函数来自定义单元格的外观。例如,以下是一个简单的示例,演示如何使用自定义颜色绘制 QTreeView 中每个单元格的背景:
```cpp
class CustomTreeView : public QTreeView
{
public:
CustomTreeView(QWidget *parent = nullptr) : QTreeView(parent)
{
setStyleSheet("QTreeView::item:selected { background-color: transparent; }");
}
protected:
void paintEvent(QPaintEvent *event) override
{
QPainter painter(viewport());
QStyleOptionViewItem option = viewOptions();
option.rect = rect();
for (int row = 0; row < model()->rowCount(); ++row) {
for (int column = 0; column < model()->columnCount(); ++column) {
QModelIndex index = model()->index(row, column);
option.rect = visualRect(index);
// 自定义背景颜色
painter.fillRect(option.rect, QColor(255, 255, 255));
style()->drawControl(QStyle::CE_ItemViewItem, &option, &painter, this);
}
}
painter.end();
}
};
```
在该示例中,我们首先使用 `setStyleSheet()` 方法将 QTreeView 中选定项的背景颜色设置为透明。然后,我们重写了 `paintEvent()` 函数,并使用 `QPainter` 对象在 QTreeView 的视口中绘制每个单元格。我们使用 `viewOptions()` 方法获取单元格的选项,然后使用 `visualRect()` 方法获取单元格的矩形区域。最后,我们使用 `QStyle` 类的 `drawControl()` 方法绘制单元格的外观,包括文字、图标等。在这里,我们自定义了单元格的背景颜色为白色。