为QTableWidget的列指定不同的宽度

2024-05-28 11:16:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从QT Designerpyqt5中开发一个小界面,其中包括一个QTableWidget,但我想为列指定不同的宽度,我找到了谈论相同内容的主题,但我不知道在哪里插入它们提供的代码,我不知道是不是因为版本的原因,我在QT设计器中还是个新手

我留下我提到的问题是为了它的价值。

PyQt:How do i set different header sizes for individual headers?

PyQt Set column widths

我的文件结构如下:

app.py: Stores the functionalities of the application

SGS.py: The code that is generated after converting the .ui file to .py

SGS.ui

我留下了生成表头的SGS.py部分

item = self.TableDocs.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "IDsystem"))
item = self.TableDocs.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "IDpeople"))
item = self.TableDocs.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Work"))
item = self.TableDocs.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Hours"))

我还保留了填充表格的代码

result = Cur.execute("SELECT idsystem,IDpeople,work,hours FROM workers")
self.TableDocs.setRowCount(0)

for row_number, row_data in enumerate(result):
    self.TableDocs.insertRow(row_number)
    for column_number, data in enumerate(row_data):
        self.TableDocs.setItem(row_number, column_number, QtWidgets.QTableWidgetItem(str(data)))

Tags: thepyselfnumberfordatacolumnitem
1条回答
网友
1楼 · 发布于 2024-05-28 11:16:50

从ui生成的python文件应该永远不被编辑。将其视为用于创建接口的资源文件(如图像或JSON文件)。在Designer中做不到的所有事情都必须在应用程序代码文件中实现

无论何时将模型应用于项目视图,都可以设置大小(或调整大小模式,例如自动调整大小,或将“拉伸”设置为可用宽度)。由于您使用的是一个QTableWidget(它有其内部私有模型),您可以在接口中创建小部件后立即执行此操作,如果使用设计器文件,则该接口位于setupUi(或loadUi)之后

为了设置节的大小和行为,您需要访问表标题:列的水平标题,行的垂直标题

class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.setupUi(self)

        horizontalHeader = self.TableDocs.horizontalHeader()
        # resize the first column to 100 pixels
        horizontalHeader.resizeSection(0, 100)
        # adjust the second column to its contents
        horizontalHeader.setSectionResizeMode(
            1, QtWidgets.QHeaderView.ResizeToContents)
        # adapt the third column to fill all available space
        horizontalHeader.setSectionResizeMode(
            2, QtWidgets.QHeaderView.Stretch)

请注意,如果删除一列并在同一位置插入另一列,则需要再次设置其节大小或模式

相关问题 更多 >