c++ 如何在QHeaderView的绘图器中绘制?

rjee0c15  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(125)

在下面的代码中,paintSection内部的qDebug()被调用,但是,QPixmap没有被绘制到标题列中。
可重现示例:

class HeaderView : public QHeaderView
{
    Q_OBJECT

public:

    HeaderView(Qt::Orientation orientation, QWidget *parent = nullptr)
        : QHeaderView(orientation, parent)
    {
    }

    QPixmap pixmap = QPixmap(":/files/icon.png");

    void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override
    {
        switch (logicalIndex) 
        {
            case 0:
            {
                painter->drawPixmap(rect.x(), rect.y(), rect.width(), rect.height()
                    , pixmap);

                //painter->fillRect(rect, QColor(255, 255, 255));
                qDebug() << rect;
                break;
            }
            default:
                break;
        }

        QHeaderView::paintSection(painter, rect, logicalIndex);
    }
};


class TreeView : public QTreeView
{
    Q_OBJECT

public:

    QStandardItemModel model;
    HeaderView* headerView;

    TreeView(QWidget* parent = 0) : QTreeView(parent)
    {
        setModel(&model);

        setIndentation(0);
        setUniformRowHeights(true);
        setRootIsDecorated(false);
        setSortingEnabled(true);

        headerView = new HeaderView(Qt::Horizontal);
        setHeader(headerView);

        model.setHorizontalHeaderItem(0, new QStandardItem("column0"));
        model.setHorizontalHeaderItem(1, new QStandardItem("column1"));
        model.setHorizontalHeaderItem(2, new QStandardItem("column2"));

        header()->setDefaultAlignment(Qt::AlignCenter);
        header()->setMinimumSectionSize(100);
    }
};
#include "treeview.h"

Application::Application(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);   
    TreeView* treeView = new TreeView(this);
}
d8tt03nd

d8tt03nd1#

在搜索时,我发现需要保存/恢复画家才能使其工作:

void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override
{
    painter->save();
    QHeaderView::paintSection(painter, rect, logicalIndex);
    painter->restore();

    switch (logicalIndex) 
    {
        case 0:
        {
            painter->drawPixmap(rect, pixmap);
            break;
        }
        default:
            break;
    }
}

相关问题