QDockWidget PyQt Example
QDockWidget is an essential component in PyQt, allowing for a versatile and interactive window experience by permitting it to be docked within the QMainWindow.
This widget provides a fluid user experience, as it can exist as a floating window or be seamlessly integrated into the main window at desired locations.
Book: Create Desktop Apps with Python PyQt5.
Understanding QDockWidget with an Example
The demonstration provided showcases the functionality of QDockWidget, with an illustrative list embedded in it.
The flexibility of this widget is evident as users can drag it and position it at various locations, like the left, right, and more.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class DockDemo(QMainWindow):
def __init__(self,parent=None):
super(DockDemo, self).__init__(parent)
layout=QHBoxLayout()
bar=self.menuBar()
file=bar.addMenu('File')
file.addAction('New')
file.addAction('Save')
file.addAction('quit')
self.items=QDockWidget('Dockable',self)
self.listWidget=QListWidget()
self.listWidget.addItem('Item1')
self.listWidget.addItem('Item2')
self.listWidget.addItem('Item3')
self.listWidget.addItem('Item4')
self.items.setWidget(self.listWidget)
self.items.setFloating(False)
self.setCentralWidget(QTextEdit())
self.addDockWidget(Qt.RightDockWidgetArea,self.items)
self.setLayout(layout)
self.setWindowTitle('Dock Demo with PyQt')
if __name__ == '__main__':
app=QApplication(sys.argv)
demo=DockDemo()
demo.show()
sys.exit(app.exec_())
Code Breakdown
This PyQt example integrates various elements, such as QMainWindow and QTextEdit, to exemplify how QDockWidget operates.
The main window is defined as a QMainWindow object, while the central widget is a QTextEdit component:
self.setCentralWidget(QTextEdit())
Initially, a dockable window item is established using:
self.items=QDockWidget('Dockable',self)
Subsequently, a QListWidget object is incorporated into the dockable window. This list contains four items, each added individually:
self.listWidget=QListWidget()
self.listWidget.addItem('Item1')
self.listWidget.addItem('Item2')
self.listWidget.addItem('Item3')
self.listWidget.addItem('Item4')
Finally, the QWidget is set up within the window area, and list control is added through:
self.items.setWidget(self.listWidget)