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.box_layout_1 = QBoxLayout(QBoxLayout.TopToBottom) self.box_layout_1.addWidget(self.label_1) # self.box_layout_1.addLayout(self.box_layout_2) # self.box_layout_1.addWidget(self.label_2) # self.box_layout_1.addWidget(self.label_3) self.setLayout(self.box_layout_1) self.box_layout_2 = QBoxLayout(QBoxLayout.LeftToRight) self.box_layout_2.addWidget(self.label_4) self.box_layout_2.addSpacing(50) self.box_layout_2.addWidget(self.label_5) self.box_layout_2.addStretch() self.box_layout_2.addWidget(self.label_6) self.box_layout_1.insertLayout(1,self.box_layout_2,1) self.box_layout_1.insertWidget(2,self.label_3,1) self.box_layout_1.insertSpacing(2,50) self.box_layout_1.insertStretch(1,2) self.box_layout_1.setStretchFactor(self.label_1,1) self.box_layout_2.setDirection(QBoxLayout.RightToLeft) # self.box_layout_1.replaceWidget(self.label_1,self.label_2) # self.label_1.hide() # self.box_layout_1.removeWidget(self.label_1) # self.label_1.hide() # self.box_layout_2.setParent(None) # self.box_layout_2.deleteLater() self.box_layout_1.removeItem(self.box_layout_2) print(self.box_layout_2.count()) for i in range(self.box_layout_2.count()): print(type(self.box_layout_2.itemAt(i))) if type(self.box_layout_2.itemAt(i)) == QWidgetItem: self.box_layout_2.itemAt(i).widget().hide() # self.box_layout_1.setEnabled(False) self.button_1 = QPushButton() self.button_1.setText("隐藏2/6") def button_clicked(): if self.button_1_flag == 1: self.label_2.hide() self.label_6.hide() self.button_1_flag = 2 self.button_1.setText("显示2/6") else: self.label_2.show() self.label_6.show() self.button_1_flag = 1 self.button_1.setText("隐藏2/6") self.button_1.clicked.connect(button_clicked) self.box_layout_1.addWidget(self.button_1) if __name__ == '__main__': app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())