1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import (QApplication, QMainWindow, QStackedLayout, QWidget, QToolBar, QToolButton, QStyle, QColorDialog, QFontDialog, QVBoxLayout, QGroupBox, QRadioButton)
class DemoStackedLayout(QMainWindow): def __init__(self, parent=None): super(DemoStackedLayout, self).__init__(parent) self.setWindowTitle('实战PyQt5: QStackedLayout Demo!') self.resize(480, 360) self.initUi()
def initUi(self): toolBar = QToolBar(self) self.addToolBar(Qt.LeftToolBarArea, toolBar)
btnColor = self.createButton('颜色对话框') btnColor.clicked.connect(lambda: self.onButtonClicked(0)) toolBar.addWidget(btnColor) btnFont = self.createButton('字体对话框') btnFont.clicked.connect(lambda: self.onButtonClicked(1)) toolBar.addWidget(btnFont) btnUser = self.createButton(' 分组部件') btnUser.clicked.connect(lambda: self.onButtonClicked(2)) toolBar.addWidget(btnUser)
mainWidget = QWidget(self)
self.mainLayout = QStackedLayout(mainWidget)
self.mainLayout.addWidget(QColorDialog(self)) self.mainLayout.addWidget(QFontDialog(self)) self.mainLayout.addWidget(self.createExclusiveGroup())
mainWidget.setLayout(self.mainLayout) self.setCentralWidget(mainWidget)
def createButton(self, text): icon = QApplication.style().standardIcon(QStyle.SP_DesktopIcon) btn = QToolButton(self) btn.setText(text) btn.setIcon(icon) btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) return btn
def onButtonClicked(self, index): if index < self.mainLayout.count(): self.mainLayout.setCurrentIndex(index) if index ==0: self.resize(580, 360) if index ==1: self.resize(680, 360) if index ==2: self.resize(780, 360)
def createExclusiveGroup(self): groupBox = QGroupBox('Exclusive Radio Buttons', self) radio1 = QRadioButton('&Radio Button 1', self) radio1.setChecked(True) radio2 = QRadioButton('R&adio button 2', self) radio3 = QRadioButton('Ra&dio button 3', self)
vLayout = QVBoxLayout(groupBox) vLayout.addWidget(radio1) vLayout.addWidget(radio2) vLayout.addWidget(radio3) vLayout.addStretch(1)
groupBox.setLayout(vLayout)
return groupBox
if __name__ == '__main__': app = QApplication(sys.argv) window = DemoStackedLayout() window.show() sys.exit(app.exec())
|