我希望从上到下(即垂直)在QTableView显示文本中制作水平标题单元格,我该怎么做?
示例PyQt5应用程序,它显示一个QTableView,其水平标题显示正常方向的文本:
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_()
答案 0 :(得分:2)
简单use of delegate will not work here。
您需要继承QHeaderView并覆盖paintSection 在实施它时,您需要:
paintSection
的旧实现答案 1 :(得分:1)
简单的解决方案是在标题单元格的文本中的每个字符之间插入换行符(请参阅模型' headerData方法):
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
# Make text appear flowing downwards
return '\n'.join([x for x in 'Header Data']).replace(' ', '')
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_()