Search code examples
pythonpyqtpyqt5qgridlayout

How can I change the size of a QGridLayout's widgets?


Take the following code:

from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        win_w, win_h = 854, 735
        self.setGeometry((1920 - win_w) // 2, (1080 - win_h) // 2, win_w, win_h)
        self.setWindowTitle('Test')
        self.setFont(QtGui.QFont('Times', 12))
        self.central_widget()

    def central_widget(self):
        widget = QtWidgets.QWidget()
        
        grid = QtWidgets.QGridLayout()
        
        text_edit1 = QtWidgets.QTextEdit()
        text_edit2 = QtWidgets.QTextEdit()
        grid.addWidget(text_edit1, 0,0)
        grid.addWidget(text_edit2, 0,1)

        widget.setLayout(grid)
        self.setCentralWidget(widget)
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Which produces this result:
result. But I would like to have the textEdit on the left to be smaller, like this:
this Even if I setGeometry before (or after) adding it to the layout, it is reset.

Is there any way to change the geometry of a widget after adding it to a layout?


Solution

  • The answer depends if you want:

    • a fixed width:

      text_edit1.setFixedWidth(100)
      
    • make it a proportion of the width of the container:

      grid.setColumnStretch(0, 2) 
      grid.setColumnStretch(1, 3)