组合框QGroupBox
样式:
注意:内部必须使用布局控件
1 import sys 2 from PyQt5.QtCore import Qt 3 from PyQt5.QtGui import QPixmap 4 from PyQt5.QtWidgets import QApplication, QWidget, QGroupBox, QRadioButton, QLabel, QHBoxLayout, QVBoxLayout 5 6 7 class Demo(QWidget): 8 def __init__(self): 9 super(Demo, self).__init__() 10 self.groupbox_1 = QGroupBox('On and Off', self) # 实例化组合框 11 self.groupbox_2 = QGroupBox('Change Color', self) 12 13 self.red = QRadioButton('Red', self) 14 self.blue = QRadioButton('Blue', self) 15 self.green = QRadioButton('Green', self) 16 self.yellow = QRadioButton('Yellow', self) 17 self.color_list = [self.red, self.blue, self.green, self.yellow] 18 19 self.on = QRadioButton('On', self) 20 self.off = QRadioButton('Off', self) 21 22 self.pic_label = QLabel(self) 23 24 self.h1_layout = QHBoxLayout() 25 self.h2_layout = QHBoxLayout() 26 self.h3_layout = QHBoxLayout() 27 self.all_v_layout = QVBoxLayout() 28 29 self.layout_init() 30 self.radiobutton_init() 31 self.label_init() 32 33 def layout_init(self): 34 self.h1_layout.addWidget(self.on) 35 self.h1_layout.addWidget(self.off) 36 self.groupbox_1.setLayout(self.h1_layout) #组合框中添加布局 37 38 self.h2_layout.addWidget(self.red) 39 self.h2_layout.addWidget(self.blue) 40 self.h2_layout.addWidget(self.green) 41 self.h2_layout.addWidget(self.yellow) 42 self.groupbox_2.setLayout(self.h2_layout) 43 44 self.h3_layout.addWidget(self.groupbox_1) 45 self.h3_layout.addWidget(self.groupbox_2) 46 47 self.all_v_layout.addWidget(self.pic_label) 48 self.all_v_layout.addLayout(self.h3_layout) 49 50 self.setLayout(self.all_v_layout) 51 52 def radiobutton_init(self): 53 self.yellow.setChecked(True) 54 for btn in self.color_list: 55 btn.clicked.connect(self.change_color_func) 56 57 self.off.setChecked(True) 58 self.off.toggled.connect(self.on_and_off_func) 59 60 def label_init(self): 61 self.pic_label.setPixmap(QPixmap('images/Off.png')) 62 self.pic_label.setAlignment(Qt.AlignCenter) 63 64 def change_color_func(self): 65 if self.on.isChecked(): 66 path = 'images/{}.png'.format([btn.text() for btn in self.color_list if btn.isChecked()][0]) 67 self.pic_label.setPixmap(QPixmap(path)) 68 69 def on_and_off_func(self): 70 if self.on.isChecked(): 71 path = 'images/{}.png'.format([btn.text() for btn in self.color_list if btn.isChecked()][0]) 72 self.pic_label.setPixmap(QPixmap(path)) 73 else: 74 self.pic_label.setPixmap(QPixmap('images/Off.png')) 75 76 77 if __name__ == '__main__': 78 app = QApplication(sys.argv) 79 demo = Demo() 80 demo.show() 81 sys.exit(app.exec_())