QMainWindow不显示QHBoxLayout
时间: 2024-05-12 10:14:32 浏览: 9
QMainWindow是一个顶层窗口,它通常包含一个菜单栏、工具栏、状态栏和中心部件(central widget)。如果你想在QMainWindow中显示QHBoxLayout,你需要将QHBoxLayout作为一个子部件添加到中心部件中。
以下是一个简单的例子:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建一个QWidget作为中心部件
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
# 创建一个 QHBoxLayout
layout = QHBoxLayout(central_widget)
layout.addWidget(QPushButton("Button 1"))
layout.addWidget(QPushButton("Button 2"))
layout.addWidget(QPushButton("Button 3"))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在这个例子中,我们首先创建一个QWidget并将其设置为QMainWindow的中心部件。然后我们创建一个QHBoxLayout并将其添加到QWidget上。最后,我们在QHBoxLayout中添加了三个QPushButton。运行这个代码,你应该可以在窗口中看到三个按钮。