0

The following code runs after creating a new environment and pip install PyQt5:

from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel, QLineEdit, QPushButton

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.layout = QGridLayout()

        self.here_is_id = QLabel("Here is system id: ")
        self.layout.addWidget(self.here_is_id, 0,0)

        self.id_label = QLabel("3139668d-b0d1-4b84-9080-52474790b56c")
        self.layout.addWidget(self.id_label, 0,1)

        self.label = QLabel("Enter password: ")
        self.layout.addWidget(self.label, 1,0)
        self.edit = QLineEdit()
        self.layout.addWidget(self.edit, 1, 1)
        self.confirm_button = QPushButton('Confirm')
        self.layout.addWidget(self.confirm_button, 2, 0)
        self.cancel_button = QPushButton('Cancel')
        self.layout.addWidget(self.cancel_button, 2, 1)

        self.setLayout(self.layout)
        self.resize(450,300)

if __name__ == "__main__":
    import sys
    system_app = QApplication(sys.argv)

    main = MainWindow()
    main.show()

    system_app.exec()

It gives:

enter image description here

The two problems are:

  1. It is not evenly spaced.
  2. The cancel button is a lot longer than confirm button.

Question: how do I resolve both issue without changing the size of the widget? That is, the space between each row will be even and the two buttons have the same size. The length of QLineEdit should not be changed.

enter image description here

My attempt is to use commands like self.layout.setColumnStretch and self.layout.setSpacing. However, none of the command actually changes the widget. I am stuck on how to proceed.

温泽海
  • 216
  • 3
  • 16
  • 1
    It's a *grid* layout, widgets in the same row or column will share the same height/vertical position and width/horizontal position respectively: with just two columns you cannot have the buttons have different sizes. Either use multiple columns and proper *spans* when adding all widgets, or add a QHBoxLayout at the bottom of the grid and add the buttons to that layout. – musicamante Jun 21 '23 at 16:32

0 Answers0