PyQt5 QDockWidget - Setting Floating Property

PyQt5 QDockWidget - Setting Floating Property

In PyQt5, QDockWidget provides a widget that can be docked inside a QMainWindow or floated as a top-level window on the desktop. The floating property of a QDockWidget can be set to make it either float or dock. This is useful for creating customizable and flexible GUI applications where users can rearrange components as they see fit.

Here's how you can set the floating property of a QDockWidget:

Step 1: Import Necessary Modules

First, import the necessary PyQt5 modules:

from PyQt5.QtWidgets import QApplication, QMainWindow, QDockWidget, QTextEdit import sys 

Step 2: Create a Main Window Class

Define a main window class that inherits from QMainWindow. In this class, you will create a QDockWidget and set its floating property.

class MainWindow(QMainWindow): def __init__(self): super().__init__() # Set the title and initial size of the main window self.setWindowTitle("QDockWidget Example") self.setGeometry(100, 100, 600, 400) # Create a QTextEdit widget to put inside the dock widget self.text_edit = QTextEdit() # Create a QDockWidget self.dock_widget = QDockWidget("Dockable", self) # Set the widget for the dock widget self.dock_widget.setWidget(self.text_edit) # Add the dock widget to the main window self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_widget) # Set the floating property of the dock widget # True makes it float, False docks it self.dock_widget.setFloating(True) 

Step 3: Create and Run the Application

Finally, create a QApplication instance, an instance of your MainWindow, and start the event loop:

if __name__ == "__main__": app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) 

Additional Notes

  • The setFloating(True) method makes the QDockWidget float, while setFloating(False) docks it back into the QMainWindow.
  • You can also allow the user to control the floating state by enabling the dock widget's features, like self.dock_widget.setFeatures(QDockWidget.DockWidgetFloatable).
  • Remember that PyQt5 applications need an instance of QApplication, and every widget is run in a loop using app.exec_().

This simple example demonstrates how to set the floating property of a QDockWidget. You can extend this example by adding more features, like menus, other widgets, and different dockable areas in the QMainWindow.


More Tags

linear-equation maatwebsite-excel jquery-select2 testbed recurrent-neural-network pseudo-element namevaluecollection rhino-mocks android-button common-table-expression

More Programming Guides

Other Guides

More Programming Examples