![](/img/trans.png)
[英]QStyledItemDelegate's sizeHint method not called for a QTableView row
[英]Painting the background of a QTableView (with a custom QStyledItemDelegate)
我一直在嘗試使用(自定義) QStyledItemDelegate
在(自定義) QTableView
使用“每單元”自定義背景。 一切正常,直到我真正嘗試擁有自己的自定義背景。 舉例來說,我希望所有單元格都具有紅色背景。 這是我的Delegate
的paint
方法。
QStyleOptionViewItem newOption = option;
auto normalText = newOption.palette.brush(QPalette::ColorGroup::Normal, QPalette::ColorRole::Text);
// Works as expected
newOption.palette.setBrush(QPalette::ColorGroup::Normal, QPalette::ColorRole::Highlight, Qt::gray); // QBrush(Qt::GlobalColor::blue, Qt::BrushStyle::NoBrush));
// Expected too: selected cells are gray
newOption.palette.setBrush(QPalette::ColorGroup::Normal, QPalette::ColorRole::HighlightedText, normalText);
// All of the following do NOT work. I've tried every possible combination without success.
newOption.palette.setBrush(QPalette::ColorGroup::Normal, QPalette::ColorRole::Window, Qt::red);
newOption.palette.setBrush(QPalette::ColorGroup::Inactive, QPalette::ColorRole::Base, Qt::red);
newOption.palette.setBrush(QPalette::ColorGroup::Inactive, QPalette::ColorRole::AlternateBase, Qt::red);
newOption.palette.setBrush(QPalette::ColorGroup::Active, QPalette::ColorRole::Base, Qt::red);
newOption.palette.setBrush(QPalette::ColorGroup::Active, QPalette::ColorRole::AlternateBase, Qt::red);
QStyledItemDelegate::paint(painter, newOption, index);
我應該如何實現? 我認為我的操作方式非常簡單直觀,這是怎么回事?
您的代碼具有以下錯誤:
如果要自定義QStyleOptionViewItem
的屬性,請不要使用paint()
方法,因為在paint()
方法中,它將被內部調用的initStyleOption()
方法覆蓋。
並非繪畫的所有屬性都是從QPalette
獲得的,對於背景色,必須使用backgroundBrush
屬性。
考慮到上述解決方案是:
#include <QtWidgets>
class StyledItemDelegate: public QStyledItemDelegate
{
public:
using QStyledItemDelegate::QStyledItemDelegate;
protected:
void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override
{
QStyledItemDelegate::initStyleOption(option, index);
QBrush normalText = option->palette.brush(QPalette::ColorGroup::Normal, QPalette::ColorRole::Text);
option->palette.setBrush(QPalette::ColorGroup::Normal, QPalette::ColorRole::Highlight, Qt::gray);
option->palette.setBrush(QPalette::ColorGroup::Normal, QPalette::ColorRole::HighlightedText, normalText);
option->backgroundBrush = QColor(Qt::red);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView w;
StyledItemDelegate *delegate = new StyledItemDelegate(&w);
w.setItemDelegate(delegate);
QStandardItemModel model(10, 10);
w.setModel(&model);
w.show();
return a.exec();
}
我知道這很麻煩,但是如果您逐步瀏覽QStyledItemDelegate::paint()
的源代碼,則在內部深處會發現一些硬編碼的值(例如,所選項目的背景色)。
我結束了繪制,而不是在 QStyledItemDelegate::paint()
下繪制了一個半透明的畫家/筆刷/圖像(在基類調用之后)。
如果選擇行為對您而言並不重要,請在調用QStyledItemDelegate::paint()
之前嘗試自己執行繪畫, 然后查看是否滿足您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.