0

我想设置一个自定义 QHeaderView 来旋转水平标题的文本。我正在使用 QStdarItemModel

目前我有这个

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

我真的不明白我对翻译做了什么。我只是反复试验,直到它与列有些匹配。它仍然不能完美地做到这一点,它会无缘无故地剪切文本。我应该怎么做才能使文本与列匹配而不被截断?

“不匹配的图片和剪切文本”

另一件事是我不想在每一列上都写“标题”。要查看的模型已将 Horizo​​ntalHeaderItem 分配给每一列,我想改为显示这些标题

在此先感谢您的帮助

4

2 回答 2

0

由于 QHeaderView 只是一个视图,因此您应该从模型中获取要显示的数据。

因此,类似于QHeaderView 中的基本实现

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

要在模型上设置标题,例如使用

QStandardItemModel::setHorizontalHeaderLabels(const QStringList &labels)
于 2016-09-11T19:26:32.063 回答
0

我解决了。只需添加一个 QStringList 作为构造函数的参数并使用逻辑索引对其进行迭代。这是最终结果

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);
    }
};
于 2016-04-02T05:15:33.677 回答