Search code examples
pythonpyqtqgridlayout

How to deal with tables in QGridLayout acting weird


I'm having trouble fitting 2 tables into QGridLayout. I've read some examples and thought I got the grip of it. Apparently, I didn't. This is how I visualized it:

enter image description here

So I supposed this code should work:

layout = QGridLayout()
layout.addWidget(smalltable, 0, 1, 1, 2)
layout.addWidget(bigtable, 1, 0, 4, 4)

But instead I got something like this:

enter image description here


Solution

  • One possible solution is to set the stretch factor using setRowStretch():

    import sys
    
    from PyQt5.QtWidgets import QApplication, QGridLayout, QTableWidget, QWidget
    
    app = QApplication(sys.argv)
    
    smalltable = QTableWidget(4, 4)
    bigtable = QTableWidget(5, 5)
    
    w = QWidget()
    
    layout = QGridLayout(w)
    layout.addWidget(smalltable, 0, 1, 1, 2)
    layout.addWidget(bigtable, 1, 0, 1, 4)
    layout.setRowStretch(0, 1)
    layout.setRowStretch(1, 4)
    
    w.resize(640, 480)
    w.show()
    
    sys.exit(app.exec_())
    

    enter image description here