在PyQt中调整QTableWidget中标题的高度

时间:2016-05-27 06:06:20

标签: python pyqt pyqt5

我尝试在我的应用中添加QTableWidget四列,我需要根据窗口大小将标题中的列添加到stretch。目前,这些列仅占据一定的宽度,并且不会伸展到窗口。

以下是我的问题的最低可验证示例:

import sys
from PyQt5 import QtWidgets

class MyTable(QtWidgets.QTableWidget):
    def __init__(self, *args):
        QtWidgets.QTableWidget.__init__(self, *args)
        self.setheader()
        self.resizeColumnsToContents()
        self.resizeRowsToContents()

    def setheader(self):
        self.setHorizontalHeaderLabels(['Label 1', 'Label 2', 'Label 3'])    

def main(args):
    app = QtWidgets.QApplication(args)
    table = MyTable(5, 3)
    table.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main(sys.argv)

1 个答案:

答案 0 :(得分:-1)

如果您正在重新实施Dim connInfo As New Renci.SshNet.PasswordConnectionInfo("IP", "USERNAME", "PASSWORD") Dim sshClient As New Renci.SshNet.SshClient(connInfo) Dim cmd As Renci.SshNet.SshCommand Private Sub MaterialFlatButton1_Click(sender As Object, e As EventArgs) Handles MaterialFlatButton1.Click Using sshClient sshClient.Connect() cmd = sshClient.RunCommand("reboot") sshClient.Disconnect() End Using End Sub ,这是您需要提供的指示以实现拉伸效果:

QTableWidget

您从self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) 拨打QHeaderView并向其发送QTableWidget指令。以下示例是这个的有效实现:

Stretch

,结果如下:

QTableWidget with stretching header - part 2

QTableWidget with stretching header - part 3

在上面的代码示例中,还有另一种可能性,它会为您提供不同风格的相同目标。它已被评论但是你应该使用它(而不是第一条指令):

import sys
from PyQt5 import QtWidgets

class MyTable(QtWidgets.QTableWidget):
    def __init__(self, *args):
        QtWidgets.QTableWidget.__init__(self, *args)
        self.setheader()
        self.resizeColumnsToContents()
        self.resizeRowsToContents()

    def setheader(self):
        self.setHorizontalHeaderLabels(['Label 1', 'Label 2', 'Label 3'])
        self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        #self.horizontalHeader().setStretchLastSection(True) # This is another possible option


def main(args):
    app = QtWidgets.QApplication(args)
    table = MyTable(5, 3)
    table.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main(sys.argv)

,只有最后一列会拉伸:

{{3}}