Read model data with custom QHeaderView

2019-09-04 17:47发布

I want to set a custom QHeaderView to rotate the horizontal header's text. I'm working with a QStandarItemModel

For the moment I've this

class QHeaderViewR : public QHeaderView
{
public:
    QHeaderViewR():QHeaderView(Qt::Horizontal)
    {}

    void paintSection(QPainter * painter, const QRect & rect, int logicalIndex) const
    {
      QPen pen(Qt::black);
      painter->setPen(pen);
      painter->translate(rect.width() * logicalIndex, (logicalIndex * -18) -18);
      painter->rotate(90);
      painter->drawText(rect,"header");
    }
};

I don't really understand what i did with the translate. I just went trial and error until it somewhat matched the columns. Still it doesn't do so perfectly and it cuts the text for no apparent reason. What should i do for the text to match the columns and not be cut off?

"pic of the mismatch and cut text"

The other thing is that i don't want to just write "header" on every column. The model that's to be viewed has HorizontalHeaderItem assigned to every column and i'd like to show those headers instead

Thanks in advance for your help

2条回答
你好瞎i
2楼-- · 2019-09-04 18:00

I solved it. Just added a QStringList as parameter of the constructor and iterated through it using the logical index. This is the final result

class QHeaderViewR : public QHeaderView
{
QStringList heads;

public:
    QHeaderViewR(QStringList _heads):QHeaderView(Qt::Horizontal)
    {

        heads = _heads;
    }

    void paintSection(QPainter * painter, const QRect & rect, int logicalIndex) const
    {


        QPen pen(Qt::black);
        painter->setPen(pen);

        painter->rotate(90);
        painter->translate(0,-rect.width()+1);

        QRect copy = rect;

        copy.setWidth(rect.height());
        copy.setHeight(rect.width());
        copy.moveTo(0,-this->sectionPosition(logicalIndex));

        if (logicalIndex == 0)
        {
            copy.setHeight(rect.width()-1);
        }

        painter->drawText(copy, " " + heads.at(logicalIndex));
        painter->drawRect(copy);
    }
};
查看更多
在下西门庆
3楼-- · 2019-09-04 18:14

Since the QHeaderView is only a view, you should get the data to display from the model.

So, similar to the base implementation in QHeaderView:

QString text = model()->headerData(logicalIndex, orientation(), Qt::DisplayRole).toString();

To set the headers on the model, use for example

QStandardItemModel::setHorizontalHeaderLabels(const QStringList &labels)
查看更多
登录 后发表回答