PyQt - QGraphicsLinearLayout



In the fast-paced world of building software, desktop applications that have graphical user interfaces (GUIs) are very important. These applications let users interact with software running on their own computers using an interface that is both interactive and visually appealing.

QGraphicsLinearLayout allows you to arrange widgets within Graphics View either horizontally or vertically.

QGraphicsLinearLayout is a layout tool within Qt Widgets that organizes widgets in the Graphics View framework. It arranges widgets horizontally (default) or vertically (set by setOrientation(Qt.Vertical)). To use QGraphicsLinearLayout, create an instance, optionally with a parent widget, and add widgets and layouts using addItem(). The layout takes ownership of added items. For items inheriting from QGraphicsItem (e.g., QGraphicsWidget), consider setOwnedByLayout() to manage ownership.

Example

In the following example, we create a simple PyQt application with a yellow background window using QGraphicsLinearLayout class and its method.

import sys
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPalette, QColor
from PyQt6.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, 
QGraphicsLinearLayout, QGraphicsWidget, QMainWindow

def create_layout():
   # Create a QGraphicsLinearLayout with vertical orientation
   layout = QGraphicsLinearLayout(Qt.Orientation.Vertical)

   # Create a QGraphicsWidget to hold the layout
   container_widget = QGraphicsWidget()

   # Add the layout to the container widget
   container_widget.setLayout(layout)

   return container_widget

if __name__ == "__main__":
   app = QApplication(sys.argv)
   window = QMainWindow()

   # Create a QGraphicsView and set the scene
   view = QGraphicsView()
   scene = QGraphicsScene()
   view.setScene(scene)

   # Add the layout to the scene
   layout_widget = create_layout()
   scene.addItem(layout_widget)

   # Set the background color of the window
   palette = window.palette()
   # Set your desired color
   palette.setColor(QPalette.ColorRole.Window, QColor(255, 255, 0))  
   window.setPalette(palette)

   # Adjust the window size
   window.setGeometry(100, 100, 400, 200)
   window.show()

   sys.exit(app.exec())

Output

The above code produces the following output −

qgraphics Linear Layout
Advertisements