import sys from PyQt5.Qt import * class Window(QWidget): def __init__(self): super().__init__() self.setup_ui() def setup_ui(self): self.setWindowTitle("Qt桌面应用程序") self.button_1_flag = 1 self.resize(300, 300) self.label_1 = QLabel() self.label_1.setText("标签1") self.label_1.setStyleSheet("background-color:CornflowerBlue") self.label_2 = QLabel() self.label_2.setText("标签2") self.label_2.setStyleSheet("background-color:DarkSeaGreen") self.label_3 = QLabel() self.label_3.setText("标签3") self.label_3.setStyleSheet("background-color:HotPink") self.label_4 = QLabel() self.label_4.setText("标签4") self.label_4.setStyleSheet("background-color:CornflowerBlue") self.label_5 = QLabel() self.label_5.setText("标签5") self.label_5.setStyleSheet("background-color:DarkSeaGreen") self.label_6 = QLabel() self.label_6.setText("标签6") self.label_6.setStyleSheet("background-color:HotPink") self.grid_layout_2 = QGridLayout() self.grid_layout_2.addWidget(self.label_4, 0, 0) self.grid_layout_2.addWidget(self.label_5, 1, 0) self.grid_layout_2.addWidget(self.label_6, 2, 0) self.grid_layout_1 = QGridLayout() self.grid_layout_1.addWidget(self.label_1, 0, 0) self.grid_layout_1.addWidget(self.label_2, 0, 1) self.grid_layout_1.addWidget(self.label_3, 1, 1, 2, 2) self.grid_layout_1.addLayout(self.grid_layout_2, 3, 0, 1, 3) self.setLayout(self.grid_layout_1) self.grid_layout_1.setOriginCorner(2) print(self.grid_layout_1.getItemPosition(2)) print(self.grid_layout_1.itemAtPosition(1, 1).widget().text()) self.grid_layout_1.setRowMinimumHeight(0, 150) self.grid_layout_1.setColumnMinimumWidth(0, 150) self.grid_layout_1.setRowStretch(3, 1) self.grid_layout_1.setColumnStretch(2, 1) # self.grid_layout_1.setHorizontalSpacing(20) # self.grid_layout_1.setVerticalSpacing(20) self.grid_layout_1.setSpacing(20) print(self.grid_layout_1.count()) print(self.grid_layout_1.rowCount(), self.grid_layout_1.columnCount()) self.button_1 = QPushButton() self.button_1.setText("按钮") def button_clicked(): pass self.button_1.clicked.connect(button_clicked) self.grid_layout_1.addWidget(self.button_1) if __name__ == '__main__': app = QApplication(sys.argv) window = Window() window.show() print(window.layout().cellRect(0, 0)) sys.exit(app.exec_())