PyQt5 below Qlabel space width

Viewed 146

I am learning PyQt5. How can I remove huge space below the Qlable:

https://hizliresim.com/Lr9ujj

This is my code:

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


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

Set the vertical size policy of your label to Fixed. Your problem is that the line edit has Fixed set but the label hasn't. So the label will grow with the parent widget (tab in your case).

See https://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum for the possible options.

Another viable tool to control where a window grows if you have no widgets to fill the space are spacers, which you can also add to the layout. A vertical spacer in your case that you add below the hostEdit.

It seems to me that you are better off using 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


Update

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

Related