Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create resizable layout UI in Pyqt?

I try to create a gui. The window should be resizable. When resized horizontally some of them widgets should expand and vertically too. I illustrated this to make it more clear:

Initial

horizontal resize

vertical resize

In Qt I use QHBoxLayout but without success unfortunately.

Thanks.

like image 698
Isra Avatar asked Oct 13 '25 01:10

Isra


1 Answers

For Example :

You need to use the setStretchFactor method on your QSplitter

An example (modified from the QSplitter example Here):

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):     
        hbox = QtGui.QHBoxLayout(self)
        left = QtGui.QFrame(self)       
        left.setFrameShape(QtGui.QFrame.StyledPanel)
        right = QtGui.QFrame(self)
        right.setFrameShape(QtGui.QFrame.StyledPanel)
        splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter.addWidget(left)
        splitter.addWidget(right)
        splitter.setStretchFactor(1, 1)
        splitter.setSizes([125, 150])
        hbox.addWidget(splitter)
        self.setLayout(hbox)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QtGui.QSplitter')
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main() 

This produces an initial UI that looks like this:

Initial UI

When the image is expanded horizontally, you can see that the left widget stays the same size:

Expanded horizontally

When expanded vertically, both widgets expand:

enter image description here

Finally, the splitter is resizeable:

Resizeable

If you adjust the window size after adjusting the splitter, the left widget will retain it's size and the right will expand/collapse to fill the remainder of the window.

like image 73
Kiran Mistry Avatar answered Oct 14 '25 16:10

Kiran Mistry