PyQt5低于Qlabel空间宽度

2024-09-30 22:20:42 发布

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

我正在学习PyQt5。如何删除Qlable下的巨大空间:

https://hizliresim.com/Lr9ujj

这是我的代码:

class TftpTab(QWidget):
    def __init__(self):
        super().__init__()
        host = QLabel("Host: ")
        hostEdit = QLineEdit()


        layout = QVBoxLayout()
        layout.addWidget(host)
        layout.addWidget(hostEdit)

Tags: 代码httpscomhostinit空间pyqt5class
2条回答

将标签的垂直大小策略设置为Fixed。 您的问题是行编辑设置了Fixed,但标签没有设置。因此,标签将随着父窗口小部件(在您的示例中为tab)而增长

有关可能的选项,请参见https://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum

如果没有小部件来填充空间,控制窗口增长位置的另一个可行工具是分隔符,您也可以将其添加到布局中。在您的案例中,在hostEdit下方添加的垂直间隔符

在我看来,你最好使用QFormLayout

import sys
from PyQt5.Qt import *

class TftpTab(QWidget):
    def __init__(self):
        super().__init__()

        host = QLabel("Host: ")
        hostEdit = QLineEdit()

        layout = QFormLayout(self)
        layout.addRow(host, hostEdit)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = TftpTab()
    w.show()
    sys.exit(app.exec_())

enter image description here


更新

But if I add another Qlabel and QLineedit in same raw how can I add ?

import sys
from PyQt5.Qt import *

class TftpTab(QWidget):
    def __init__(self):
        super().__init__()

        host = QLabel("Host: ")
        hostEdit = QLineEdit()

        layout = QFormLayout(self)
        layout.addRow(host, hostEdit)

        layout.addRow(QLabel("Hello: "), QLineEdit("gogogo"))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = TftpTab()
    w.show()
    sys.exit(app.exec_())

enter image description here

相关问题 更多 >