setCentralWidget
时间: 2023-09-01 16:11:20 浏览: 33
setCentralWidget() is a method in PyQt that sets the specified widget as the central widget of the main window. This means that the widget will take up the majority of the window's space and will be the main focus of the user interface.
Here's an example of how to use setCentralWidget():
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QWidget
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My Main Window")
central_widget = QWidget(self)
label = QLabel("Hello World!", central_widget)
self.setCentralWidget(central_widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyMainWindow()
window.show()
sys.exit(app.exec())
```
In this example, we create a new QMainWindow subclass called MyMainWindow. In the constructor, we set the window title and create a new QWidget object called central_widget. We then create a QLabel object called label and add it to the central_widget. Finally, we call setCentralWidget() to set central_widget as the central widget of the main window.
When we run the application, we should see a window with the title "My Main Window" and a label that says "Hello World!" in the center of the window.