我在QTreeWidget上使用以下样式表来更改items样式:
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中删除样式表,那么颜色更改就能工作了。
知道如何使背景色改变以保持样式表的工作吗?
发布于 2016-03-22 20:08:38
使用自定义委托来绘制项目,而不是样式表。
重新实现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
https://stackoverflow.com/questions/36158827
复制相似问题