您可以通过重写QStyledItemDelegate的paint()函数来实现更改TreeView节点三角剪头颜色。以下是示例代码:
首先,在树形视图中,我们需要使用setStyleSheet()方法设置样式表来隐藏原始三角剪头,并在每个项上绘制自己的箭头。
treeView->setStyleSheet(“QTreeView::branch {
background-color: transparent; \
image: none; \
}");
然后,我们需要创建一个自定义代理类并重写其paint()函数以绘制新的三角形。在这个例子中,我们使用Qt::DecorationRole来获取项的图标,但您可以根据您的需求更改它。
class CustomDelegate : public QStyledItemDelegate { public:
void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const override {
QStyleOptionViewItem newOption(option);
initStyleOption(&newOption, index);
// 获取项的图标
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
// 设置三角形大小和位置
QRect rect(newOption.rect.left(), newOption.rect.top(), 20, 20);
rect.moveCenter(newOption.rect.center());
// 绘制三角形
QPainterPath path;
path.moveTo(rect.bottomLeft());
path.lineTo(rect.topLeft());
path.lineTo(rect.center().x(), rect.top() + 5);
path.lineTo(rect.bottomRight());
painter->save();
if (option.state & QStyle::State_Selected) {
painter->fillRect(option.rect, option.palette.highlight());
painter->setPen(option.palette.highlightedText().color());
} else {
painter->setPen(Qt::black);
}
painter->drawPath(path);
painter->restore();
QRect textRect = newOption.rect.adjusted(20, 0, 0, 0);
QString text = index.data(Qt::DisplayRole).toString();
// 绘制文本
if (!icon.isNull()) {
icon.paint(painter, newOption.rect.left() + 2, newOption.rect.top() + 2, 16, 16);
textRect.adjust(20, 0, 0, 0);
}
painter->setFont(newOption.font);
if (option.state & QStyle::State_Selected) {
painter->setPen(option.palette.highlightedText().color());
} else {
painter->setPen(newOption.palette.text().color());
}
painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, text);
}
};
最后,我们需要在TreeView上设置自定义委托。
CustomDelegate *delegate = new CustomDelegate(); treeView->setItemDelegate(delegate);
现在您可以使用以上代码更改TreeView节点三角剪头的颜色。