pyqt加水平填充
时间: 2023-07-04 07:12:00 浏览: 49
要在 PyQt 中实现水平填充,可以使用 QHBoxLayout 布局管理器。以下是一个简单的例子:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self) # 创建水平布局管理器
button1 = QPushButton('Button 1', self)
hbox.addWidget(button1) # 添加第一个按钮
hbox.addStretch(1) # 添加一个可扩展的空间
button2 = QPushButton('Button 2', self)
hbox.addWidget(button2) # 添加第二个按钮
self.setLayout(hbox) # 将水平布局管理器设置为窗口的布局管理器
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle('Horizontal Box Layout')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
在上面的例子中,我们首先创建了一个 QHBoxLayout 对象,并将其设置为窗口的布局管理器。我们添加了两个 QPushButton 按钮,然后使用 addStretch() 方法添加了一个可扩展的空间,使得第一个按钮和第二个按钮之间的距离可以自动调整。这样,我们就实现了水平填充的效果。