0

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

Jongware
  • 22,200
  • 8
  • 54
  • 100
Coyoteazul
  • 123
  • 1
  • 9
  • I figured out how to match the text. Damn rotate was a lot more complicated than what the documentation showed. I ended up figuring it out thanks to a video of VoidRealm. Still i haven't figured out how to get the data from the model. – Coyoteazul Apr 02 '16 at 02:51

2 Answers2

0

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);
    }
};
Coyoteazul
  • 123
  • 1
  • 9
0

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)
E4z9
  • 1,713
  • 9
  • 11