簡體   English   中英

繪制QTableView的背景(帶有自定義QStyledItemDelegate)

[英]Painting the background of a QTableView (with a custom QStyledItemDelegate)

我一直在嘗試使用(自定義) QStyledItemDelegate在(自定義) QTableView使用“每單元”自定義背景。 一切正常,直到我真正嘗試擁有自己的自定義背景。 舉例來說,我希望所有單元格都具有紅色背景。 這是我的Delegatepaint方法。

    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);

我應該如何實現? 我認為我的操作方式非常簡單直觀,這是怎么回事?

您的代碼具有以下錯誤:

考慮到上述解決方案是:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM