Python PyQt QTableView 设置水平和垂直标题标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37222081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PyQt QTableView Set Horizontal & Vertical Header Labels
提问by Ruchit
using QTableWidget i can do
使用 QTableWidget 我可以做到
table = QTableWidget()
table.setHorizontalHeaderLabels(QString("Name;Age;Sex;Add").split(";"))
table.horizontalHeaderItem().setTextAlignment(Qt.AlignHCenter)
how can i do same with QTableView ??
我怎么能用 QTableView 做同样的事情??
回答by Brendan Abel
The Table/Tree/List Widgets are item-based. The Table/Tree/List Views are View/Model based (sometimes known as MVC, for Model/View/Controller). In the Model/View system, the data is set and manipulated on the model and the view just displays it. To use a View widget, you also have to create a model class. In many cases, people will create their own and subclass from QAbstractItemModel
, but you don't have to. Qt provides a non-abstract model you can use with all the view classes - QStandardItemModel
.
表/树/列表小部件是基于项目的。表/树/列表视图是基于视图/模型的(有时称为 MVC,用于模型/视图/控制器)。在模型/视图系统中,数据是在模型上设置和操作的,视图只是显示它。要使用 View 小部件,您还必须创建一个模型类。在许多情况下,人们会从 中创建他们自己的子类QAbstractItemModel
,但您不必这样做。Qt 提供了一个可以与所有视图类一起使用的非抽象模型 - QStandardItemModel
.
model = QStandardItemModel()
model.setHorizontalHeaderLabels(['Name', 'Age', 'Sex', 'Add'])
table = QTableView()
table.setModel(model)
There are a couple ways you can do alignment. Alignment data is actually supported in the model, but the header view lets you set a default (I'm guessing it uses that if the alignment data isn't set in the model)
有几种方法可以进行对齐。模型中实际上支持对齐数据,但标题视图允许您设置默认值(如果模型中未设置对齐数据,我猜它会使用默认值)
header = table.horizontalHeader()
header.setDefaultAlignment(Qt.AlignHCenter)
To get even more control, you can set the alignment data directly on the model.
为了获得更多控制,您可以直接在模型上设置对齐数据。
# Sets different alignment data just on the first column
model.setHeaderData(0, Qt.Horizontal, Qt.AlignJustify, Qt.TextAlignmentRole)
But the power of the View/Model system is that the view can choose to display that data from the model anyway it wants to. If you wanted to create your own custom view, you could have absolute control over how the text in each column is aligned and displayed.
但是视图/模型系统的强大之处在于视图可以选择以任何方式显示模型中的数据。如果您想创建自己的自定义视图,您可以完全控制每列中文本的对齐和显示方式。