QTreeWidgetItem 颜色
QTreeWidgetItem color
我在 QTreeWidget 上使用以下样式表来更改项目样式:
QTreeWidget::item
{
padding-left:10px;
padding-top: 1px;
padding-bottom: 1px;
border-left: 10px;
}
之后,我尝试使用以下代码更改某些特定单元格的颜色:
// item is a QTreeWidgetItem
item->setBackgroundColor(1, QColor(255, 129, 123));
但是颜色没有变化。然后我发现,如果我从 QTreeWidget 中删除样式表,那么颜色更改就会起作用。
知道如何更改背景颜色以保持样式表正常工作吗?
使用自定义委托来绘制您的项目而不是样式表。
重新实现 paint()
方法来控制项目的绘制方式:
class CMyDelegate : public QStyledItemDelegate
{
public:
CMyDelegate(QObject* parent) : QStyledItemDelegate(parent) {}
void CMyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const override;
}
void CMyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyleOptionViewItemV4 itemOption(option)
initStyleOption(&itemOption, index);
itemOption.rect.adjust(-10, 0, 0, 0); // Make the item rectangle 10 pixels smaller from the left side.
// Draw your item content.
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
// And now you can draw a bottom border.
painter->setPen(Qt::black);
painter->drawLine(itemOption.rect.bottomLeft(), itemOption.rect.bottomRight());
}
这是使用委托的方法:
CMyDelegate* delegate = new CMyDelegate(tree);
tree->setItemDelegate(delegate);
此处有更多文档:http://doc.qt.io/qt-5/model-view-programming.html#delegate-classes
我在 QTreeWidget 上使用以下样式表来更改项目样式:
QTreeWidget::item
{
padding-left:10px;
padding-top: 1px;
padding-bottom: 1px;
border-left: 10px;
}
之后,我尝试使用以下代码更改某些特定单元格的颜色:
// item is a QTreeWidgetItem
item->setBackgroundColor(1, QColor(255, 129, 123));
但是颜色没有变化。然后我发现,如果我从 QTreeWidget 中删除样式表,那么颜色更改就会起作用。
知道如何更改背景颜色以保持样式表正常工作吗?
使用自定义委托来绘制您的项目而不是样式表。
重新实现 paint()
方法来控制项目的绘制方式:
class CMyDelegate : public QStyledItemDelegate
{
public:
CMyDelegate(QObject* parent) : QStyledItemDelegate(parent) {}
void CMyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const override;
}
void CMyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyleOptionViewItemV4 itemOption(option)
initStyleOption(&itemOption, index);
itemOption.rect.adjust(-10, 0, 0, 0); // Make the item rectangle 10 pixels smaller from the left side.
// Draw your item content.
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
// And now you can draw a bottom border.
painter->setPen(Qt::black);
painter->drawLine(itemOption.rect.bottomLeft(), itemOption.rect.bottomRight());
}
这是使用委托的方法:
CMyDelegate* delegate = new CMyDelegate(tree);
tree->setItemDelegate(delegate);
此处有更多文档:http://doc.qt.io/qt-5/model-view-programming.html#delegate-classes