PyQt - QGraphicsGridLayout



在 PyQt 中,QGraphicsGridLayout 是一個用於圖形檢視中的佈局類。它以網格模式排列控制元件和其他佈局項。我們可以用它來為基於 GUI 的應用程式中的圖形元素建立結構化佈局。

讓我們探討一下在 PyQt 中使用 QGraphicsGridLayout 的優勢 -

QGraphicsGridLayout 類提供了一個網格佈局,用於在 QgraphicsWidget 內排列布局和控制元件。

以下是 QGraphicsGridLayout 的一個重要要點 -

  • 在為圖形元素建立結構化佈局時,始終需要以網格模式組織控制元件。
  • 透過呼叫 addItem() 方法新增控制元件和佈局。
  • 使用 setLayout() 方法在控制元件中分配佈局。
  • 我們可以在堆上構造一個沒有父物件的物件。
  • QGraphicsGrid 允許每個專案的尺寸以整數表示。
  • 如果網格中的某個單元格有其專案無法填滿的額外空間,則每個專案將根據該專案在佈局中的對齊方式進行定位。要為每個專案指定對齊方式,可以使用 setAlignment() 方法。類似地,可以使用 alignment() 方法檢查任何專案的對齊方式。

現在讓我們瞭解一下在 GUI 開發中使用 QGraphicsGridLayout 的優勢 -

  • **基於網格的佈局** - 開發人員可以使用 QGraphicsGridLayout 建立順序佈局,尤其是在圖形檢視中定位控制元件時。
  • **自動調整大小** - 佈局會自動計算專案尺寸,簡化控制元件放置。
  • **所有權管理** - 佈局旨在承擔管理新增專案的責任,這使得記憶體管理和清理變得輕而易舉。
  • **尺寸控制** - 尊重網格中每個專案的尺寸首選項和收縮策略。
  • **靈活的對齊方式** - 使用 setAlignment() 自定義每個專案的對齊方式,以獲得所需的顯示效果。

請注意,掌握佈局可以增強專業外觀的介面。

示例

以下示例說明了使用 QGraphicsGridLayout 類及其方法的四個容器控制元件。

import sys
from PyQt6.QtWidgets import QApplication, QGraphicsScene, QGraphicsView, QGraphicsGridLayout, QGraphicsProxyWidget, QPushButton, QGraphicsWidget
def main():
   app = QApplication(sys.argv)

   # Create a QGraphicsScene
   scene = QGraphicsScene()

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

   # Create a QGraphicsGridLayout
   layout = QGraphicsGridLayout()

   # Create buttons and add them to the layout
   b1 = QPushButton("Box 1")
   b2 = QPushButton("Box 2")
   b3 = QPushButton("Box 3")
   b4 = QPushButton("Box 4")

   proxy_button1 = QGraphicsProxyWidget()
   proxy_button1.setWidget(b1)
   layout.addItem(proxy_button1, 0, 0)

   proxy_button2 = QGraphicsProxyWidget()
   proxy_button2.setWidget(b2)
   layout.addItem(proxy_button2, 0, 1)

   proxy_button3 = QGraphicsProxyWidget()
   proxy_button3.setWidget(b3)
   layout.addItem(proxy_button3, 1, 0)

   proxy_button4 = QGraphicsProxyWidget()
   proxy_button4.setWidget(b4)
   layout.addItem(proxy_button4, 1, 1)

   # Create a QGraphicsWidget to hold the layout
   widget = QGraphicsWidget()
   widget.setLayout(layout)

   # Add the widget to the scene
   scene.addItem(widget)

   # Show the view
   view.show()

   # Execute the application
   sys.exit(app.exec())

if __name__ == "__main__":
   main()

輸出

以上程式碼產生以下輸出 -

qgraphics Grid Layout
廣告

© . All rights reserved.