Read model data with custom QHeaderView

回眸只為那壹抹淺笑 提交于 2019-12-12 05:39:48

问题


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


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/36366163/read-model-data-with-custom-qheaderview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!