在 QTableView 中,如何使水平标题单元格显示垂直文本? [英] In a QTableView, how can I make horizontal header cells display vertical text?

查看:54
本文介绍了在 QTableView 中,如何使水平标题单元格显示垂直文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让 QTableView 中的水平标题单元格从上到下(即垂直)显示文本,我该怎么做?

I wish to make horizontal header cells in a QTableView display text from top to bottom (i.e., vertically), how can I do this?

示例 PyQt5 应用程序,它显示一个 QTableView,其中水平标题显示法线方向的文本:

Example PyQt5 app which displays a QTableView with a horizontal header showing text in the normal direction:

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys

class TableModel(QAbstractTableModel):
    def __init__(self, parent):
        super(TableModel, self).__init__(parent)

    def headerData(self, section, orientation, role):
        if orientation != Qt.Horizontal:
            return
        if role != Qt.DisplayRole:
            return

        return 'Header Data'

    def data(self, index, role):
        if role != Qt.DisplayRole:
            return

        return 'Row Data'

    def rowCount(self, parent):
        return 1

    def columnCount(self, parent):
        return 1


class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()

        main_widget = QWidget(self)
        self.setCentralWidget(main_widget)
        layout = QVBoxLayout(main_widget)

        view = QTableView(main_widget)
        view.horizontalHeader().setVisible(True)
        view.verticalHeader().setVisible(False)
        layout.addWidget(view)
        model = TableModel(view)
        view.setModel(model)
        view.resizeColumnsToContents()

app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()

推荐答案

简单的在这里无法使用委托.

您需要子类化 QHeaderView 并覆盖 paintSection.
在实现它时,您需要:

You need to subclass QHeaderView and override paintSection.
In implementation of it you need:

  • 旋转和翻译画家
  • 计算将考虑上述转换的新矩形
  • 使用新值调用 paintSection 的旧实现
  • 恢复画家状态(逆向变换).

这篇关于在 QTableView 中,如何使水平标题单元格显示垂直文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆