PyQt - QHBoxLayout



QHBoxLayout 類用於建立水平佈局容器。容器中的元素將從左到右依次排列。建立水平佈局需要使用 PyQt 的各種函式,例如 setLayout()addWidget()addLayout()。因此,QHBoxLayout 物件的命令建立了一個活動的佈局管理器。

所有這些類都可以作為構建水平方向容器的步驟:

步驟 1 - 從佈局類建立一個佈局物件。

步驟 2 - setLayout() - 將此佈局物件分配給父視窗部件的屬性。

步驟 3 - addWidget() - 可以將此方法稱為一個函式,用於將視窗部件新增到佈局中。

步驟 4 - addLayout() - 這是 QHBoxLayout 類的附加方法,允許我們將更復雜的視窗部件新增到 PyQt 視窗中。

在本教程中,我們將探討如何使用 QHBoxlayout 水平排列 PyQt 視窗部件。

qhbox Layout Example One

QHBoxLayout 的語法

QHBoxLayout 本身既是一個類,也是一個內建函式。以下是執行佈局任務的語法:

QHBoxLayout()

在 PyQt 視窗中使用 QHBoxLayout

在盒佈局系統中,開發人員提供了一種強大的方法來定位 GUI 元件及其應用程式。因此,QHBoxLayout 的三種主要用法:

  • 建立視窗部件
  • 設定 QHBoxLayout
  • 設定窗口布局

示例

下面的示例演示了使用 QHBoxLayout 類建立水平容器佈局的程式碼。

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout
class ExampleWidget(QWidget):
   def __init__(self):
      super().__init__()
      self.initUI()
   def initUI(self):
      # Create widgets
      box1 = QPushButton('A', self)
      box2 = QPushButton('B', self)
      box3 = QPushButton('C', self)

      # Create horizontal layout
      h_box = QHBoxLayout()
      h_box.addWidget(box1)
      h_box.addWidget(box2)
      h_box.addWidget(box3)

      # Set the layout for the main window
      self.setLayout(h_box)

      self.setGeometry(300, 300, 300, 150)
      self.setWindowTitle('QHBoxLayout')
      self.show()

if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = ExampleWidget()
   sys.exit(app.exec())

輸出

執行程式碼後,我們將得到一個從左到右的水平容器結果。

qhboxlayout Ex One.jpg

QHBoxLayout 中的邊距和間距屬性

邊距屬性保持 PyQt 視窗的設計,因為它會在文字和容器邊緣之間建立空間,而間距則保持兩個視窗部件之間的間隙。

在 PyQt 視窗中,我們有兩組基於邊距和間距的屬性:

  • setSpacing() - 此物件與 QHBoxLayout 類關聯,用於設定子視窗部件之間的間距。
  • setContentsMargins() - 此屬性物件也與 QHBoxLayout 類關聯,透過以下四個引數來設定邊距:左、上、右和下。

示例

在這個示例中,我們將演示使用 QHBoxLayout 類及其物件設定間距和邊距屬性。

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout
class ExampleWidget(QWidget):
   def __init__(self):
      super().__init__()
      self.initUI()
   def initUI(self):
      # Create widgets
      b1 = QPushButton('A', self)
      b2 = QPushButton('B', self)
      b3 = QPushButton('C', self)

      # Create horizontal layout
      h_box = QHBoxLayout()
      h_box.addWidget(b1)
      h_box.addWidget(b2)
      h_box.addWidget(b3)

      # Set spacing between widgets
      h_box.setSpacing(70)

      # Set content margins
      h_box.setContentsMargins(50, 50, 50, 50)

      # Set the layout for the main window
      self.setLayout(h_box)

      self.setGeometry(300, 300, 300, 150)
      self.setWindowTitle('QHBoxLayout Margin')
      self.show()

if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = ExampleWidget()
   sys.exit(app.exec())

輸出

上述程式碼將產生以下輸出:

qhboxlayout Ex Two.jpg
廣告
© . All rights reserved.