PyQt - QSplitter Widget



This is another advanced layout manager which allows the size of child widgets to be changed dynamically by dragging the boundaries between them. The Splitter control provides a handle that can be dragged to resize the controls.

The widgets in a QSplitter object are laid horizontally by default although the orientation can be changed to Qt.Vertical.

Following are the methods and signals of QSplitter class −

Sr.No. Methods & Description
1

addWidget()

Adds the widget to splitter’s layout

2

indexOf()

Returns the index of the widget in the layout

3

insetWidget()

Inserts a widget at the specified index

4

setOrientation()

Sets the layout of splitter to Qt.Horizontal or Qt.Vertical

5

setSizes()

Sets the initial size of each widget

6

count()

Returns the number of widgets in splitter widget

splitterMoved() is the only signal emitted by QSplitter object whenever the splitter handle is dragged.

Example

The following example has a splitter object, splitter1, in which a frame and QTextEdit object are horizontally added.

topleft = QFrame()
textedit = QTextEdit()
splitter1.addWidget(topleft)
splitter1.addWidget(textedit)

This splitter object splitter1 and a bottom frame object are added in another splitter, splitter2, vertically. The object splitters is finally added in the top level window.

bottom = QFrame()
splitter2 = QSplitter(Qt.Vertical)
splitter2.addWidget(splitter1)
splitter2.addWidget(bottom)

hbox.addWidget(splitter2)
self.setLayout(hbox)

The complete code is as follows −

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Example(QWidget):

   def __init__(self):
      super(Example, self).__init__()
		
   self.initUI()
	
   def initUI(self):
	
      hbox = QHBoxLayout(self)
		
      topleft = QFrame()
      topleft.setFrameShape(QFrame.StyledPanel)
      bottom = QFrame()
      bottom.setFrameShape(QFrame.StyledPanel)
		
      splitter1 = QSplitter(Qt.Horizontal)
      textedit = QTextEdit()
      splitter1.addWidget(topleft)
      splitter1.addWidget(textedit)
      splitter1.setSizes([100,200])
		
      splitter2 = QSplitter(Qt.Vertical)
      splitter2.addWidget(splitter1)
      splitter2.addWidget(bottom)
		
      hbox.addWidget(splitter2)
		
      self.setLayout(hbox)
      QApplication.setStyle(QStyleFactory.create('Cleanlooks'))
		
      self.setGeometry(300, 300, 300, 200)
      self.setWindowTitle('QSplitter demo')
      self.show()
		
def main():
   app = QApplication(sys.argv)
   ex = Example()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()

The above code produces the following output −

QSplitter Widget Output
Advertisements