我是靠谱客的博主 跳跃星月,最近开发中收集的这篇文章主要介绍用pyqt5创建简单控件,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

from PyQt5.QtCore import QDateTime,Qt,QTimer
from PyQt5.QtWidgets import (QApplication,QCheckBox,QComboBox,QDateTimeEdit,
                             QDial,QDialog,QGridLayout,QGroupBox,QHBoxLayout,
                             QLabel,QLineEdit,QProgressBar,QPushButton,QRadioButton,
                             QScrollBar,QSizePolicy,QSlider,QSpinBox,QStyleFactory,
                             QTableWidget,QTabWidget,QTextEdit,QVBoxLayout,QWidget)


class WidgetGallery(QDialog):
    def __init__(self,parent=None):
        super(WidgetGallery,self).__init__(parent)

        self.originalPalette = QApplication.palette()

        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())

        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)

        self.useStylePaletteCheckBox = QCheckBox("&Use style's standard palette")
        self.useStylePaletteCheckBox.setChecked(True)

        disableWidgetsCheckBox = QCheckBox("&Disable widget")

        self.createTopLeftGroupBox()
        self.createTopRightGroupBox()
        self.createBottomLeftTabWidget()
        self.createBottomRightGroupBox()
        self.createProgressBar()

        styleComboBox.activated[str].connect(self.changeStyle)
        self.useStylePaletteCheckBox.toggled.connect(self.changePalette)
        disableWidgetsCheckBox.toggled.connect(self.topLeftGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(self.bottomLeftTabWidget.setDisabled)
        disableWidgetsCheckBox.toggled.connect(self.topRightGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(self.bottomRightGroupBox.setDisabled)

        topLayout = QHBoxLayout()
        topLayout.addWidget(styleLabel)
        topLayout.addWidget(styleComboBox)
        topLayout.addStretch(1)
        topLayout.addWidget(self.useStylePaletteCheckBox)
        topLayout.addWidget(disableWidgetsCheckBox)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout,0,0,1,2)
        mainLayout.addWidget(self.topLeftGroupBox,1,0)
        mainLayout.addWidget(self.topRightGroupBox,1,1)
        mainLayout.addWidget(self.bottomLeftTabWidget,2,0)
        mainLayout.addWidget(self.bottomRightGroupBox,2,1)
        mainLayout.addWidget(self.progressBar,3,0,1,2)
        mainLayout.setRowStretch(1,1)
        mainLayout.setRowStretch(2,1)
        mainLayout.setColumnStretch(0,1)
        mainLayout.setColumnStretch(1,1)
        self.setLayout(mainLayout)

        self.setWindowTitle("Styles")
        self.changeStyle('Windows')

    def changeStyle(self,styleName):
        QApplication.setStyle(QStyleFactory.create(styleName))
        self.changePalette()

    def changePalette(self):
        if (self.useStylePaletteCheckBox.isChecked()):
            QApplication.setPalette(QApplication.style().standardPalette())
        else:
            QApplication.setPalette(self.originalPalette)

    def advanceProgressBar(selfself):
        curVal = self.progressBar.value()
        maxVal = self.progressBar.maximum()
        self.progressBar.setValue(curVal + (maxVal-curVal)/100)

    def createTopLeftGroupBox(self):
        self.topLeftGroupBox = QGroupBox("Group 1")

        radioButton1 = QRadioButton("Radio button 1")
        radioButton2 = QRadioButton("Radio button 2")
        radioButton3 = QRadioButton("Radio button 3")
        radioButton1.setChecked(True)

        checkBox = QCheckBox("Tri-state check box")
        checkBox.setTristate(True)
        checkBox.setCheckState(Qt.PartiallyChecked)

        layout = QVBoxLayout()
        layout.addWidget(radioButton1)
        layout.addWidget(radioButton2)
        layout.addWidget(radioButton3)
        layout.addWidget(checkBox)
        layout.addStretch(1)
        self.topLeftGroupBox.setLayout(layout)

    def createTopRightGroupBox(self):
        self.topRightGroupBox = QGroupBox("Group 2")

        defaultPushButton = QPushButton("Default Push Button")
        defaultPushButton.setDefault(True)

        togglePushButton = QPushButton("Toggle Push Button")
        togglePushButton.setCheckable(True)
        togglePushButton.setChecked(True)

        flatPushButton = QPushButton("Flat Push Button")
        flatPushButton.setFlat(True)

        layout = QVBoxLayout()
        layout.addWidget(defaultPushButton)
        layout.addWidget(togglePushButton)
        layout.addWidget(flatPushButton)
        layout.addStretch(1)
        self.topRightGroupBox.setLayout(layout)

    def createBottomLeftTabWidget(self):
        self.bottomLeftTabWidget = QTabWidget()
        self.bottomLeftTabWidget.setSizePolicy(QSizePolicy.Preferred,
                                               QSizePolicy.Ignored)
        tab1 = QWidget()
        tableWidget = QTableWidget(10,10)

        tablhbox = QHBoxLayout()
        tablhbox.setContentsMargins(5,5,5,5)
        tablhbox.addWidget(tableWidget)
        tab1.setLayout(tablhbox)

        tab2 = QWidget()
        textEdit = QTextEdit()

        textEdit.setPlainText("你好呀,"
                              "抱抱!")
        tab2hbox = QHBoxLayout()
        tab2hbox.setContentsMargins(5,5,5,5)
        tab2hbox.addWidget(textEdit)
        tab2.setLayout(tab2hbox)

        self.bottomLeftTabWidget.addTab(tab1,"&Table")
        self.bottomLeftTabWidget.addTab(tab2,"Text &Edit")

    def createBottomRightGroupBox(self):
        self.bottomRightGroupBox = QGroupBox("Group 3")
        self.bottomRightGroupBox.setCheckable(True)
        self.bottomRightGroupBox.setChecked(True)

        lineEdit = QLineEdit('s3cRe7')
        lineEdit.setEchoMode(QLineEdit.Password)

        spinBox = QSpinBox(self.bottomRightGroupBox)
        spinBox.setValue(50)

        dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox)
        dateTimeEdit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider(Qt.Horizontal,self.bottomRightGroupBox)
        slider.setValue(40)

        scrollBar = QScrollBar(Qt.Horizontal,self.bottomRightGroupBox)
        scrollBar.setValue(60)

        dial = QDial(self.bottomRightGroupBox)
        dial.setValue(30)
        dial.setNotchesVisible(True)

        layout = QGridLayout()
        layout.addWidget(lineEdit,0,0,1,2)
        layout.addWidget(spinBox,1,0,1,2)
        layout.addWidget(dateTimeEdit,2,0,1,2)
        layout.addWidget(slider,3,0)
        layout.addWidget(scrollBar,4,0)
        layout.addWidget(dial,3,1,2,1)
        layout.setRowStretch(5,1)
        self.bottomRightGroupBox.setLayout(layout)

    def createProgressBar(self):
        self.progressBar = QProgressBar()
        self.progressBar.setRange(0,10000)
        self.progressBar.setValue(0)

if __name__ =='__main__':
    import sys

    app = QApplication(sys.argv)
    gallery = WidgetGallery()
    gallery.show()
    sys.exit(app.exec_())import sys

from PyQt5.QtCore import QDir, Qt
from PyQt5.QtGui import QFont, QPalette
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
        QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
        QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton)


class Dialog(QDialog):
    MESSAGE = "

Message boxes have a caption, a text, and up to three " "buttons, each with standard or custom texts.

" "

Click a button to close the message box. Pressing the Esc " "button will activate the detected escape button (if any).

" def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.openFilesPath = '' self.errorMessageDialog = QErrorMessage(self) frameStyle = QFrame.Sunken | QFrame.Panel self.integerLabel = QLabel() self.integerLabel.setFrameStyle(frameStyle) self.integerButton = QPushButton("QInputDialog.get&Int()") self.doubleLabel = QLabel() self.doubleLabel.setFrameStyle(frameStyle) self.doubleButton = QPushButton("QInputDialog.get&Double()") self.itemLabel = QLabel() self.itemLabel.setFrameStyle(frameStyle) self.itemButton = QPushButton("QInputDialog.getIte&m()") self.textLabel = QLabel() self.textLabel.setFrameStyle(frameStyle) self.textButton = QPushButton("QInputDialog.get&Text()") self.colorLabel = QLabel() self.colorLabel.setFrameStyle(frameStyle) self.colorButton = QPushButton("QColorDialog.get&Color()") self.fontLabel = QLabel() self.fontLabel.setFrameStyle(frameStyle) self.fontButton = QPushButton("QFontDialog.get&Font()") self.directoryLabel = QLabel() self.directoryLabel.setFrameStyle(frameStyle) self.directoryButton = QPushButton("QFileDialog.getE&xistingDirectory()") self.openFileNameLabel = QLabel() self.openFileNameLabel.setFrameStyle(frameStyle) self.openFileNameButton = QPushButton("QFileDialog.get&OpenFileName()") self.openFileNamesLabel = QLabel() self.openFileNamesLabel.setFrameStyle(frameStyle) self.openFileNamesButton = QPushButton("QFileDialog.&getOpenFileNames()") self.saveFileNameLabel = QLabel() self.saveFileNameLabel.setFrameStyle(frameStyle) self.saveFileNameButton = QPushButton("QFileDialog.get&SaveFileName()") self.criticalLabel = QLabel() self.criticalLabel.setFrameStyle(frameStyle) self.criticalButton = QPushButton("QMessageBox.critica&l()") self.informationLabel = QLabel() self.informationLabel.setFrameStyle(frameStyle) self.informationButton = QPushButton("QMessageBox.i&nformation()") self.questionLabel = QLabel() self.questionLabel.setFrameStyle(frameStyle) self.questionButton = QPushButton("QMessageBox.&question()") self.warningLabel = QLabel() self.warningLabel.setFrameStyle(frameStyle) self.warningButton = QPushButton("QMessageBox.&warning()") self.errorLabel = QLabel() self.errorLabel.setFrameStyle(frameStyle) self.errorButton = QPushButton("QErrorMessage.show&M&essage()") self.integerButton.clicked.connect(self.setInteger) self.doubleButton.clicked.connect(self.setDouble) self.itemButton.clicked.connect(self.setItem) self.textButton.clicked.connect(self.setText) self.colorButton.clicked.connect(self.setColor) self.fontButton.clicked.connect(self.setFont) self.directoryButton.clicked.connect(self.setExistingDirectory) self.openFileNameButton.clicked.connect(self.setOpenFileName) self.openFileNamesButton.clicked.connect(self.setOpenFileNames) self.saveFileNameButton.clicked.connect(self.setSaveFileName) self.criticalButton.clicked.connect(self.criticalMessage) self.informationButton.clicked.connect(self.informationMessage) self.questionButton.clicked.connect(self.questionMessage) self.warningButton.clicked.connect(self.warningMessage) self.errorButton.clicked.connect(self.errorMessage) self.native = QCheckBox() self.native.setText("Use native file dialog.") self.native.setChecked(True) if sys.platform not in ("win32", "darwin"): self.native.hide() layout = QGridLayout() layout.setColumnStretch(1, 1) layout.setColumnMinimumWidth(1, 250) layout.addWidget(self.integerButton, 0, 0) layout.addWidget(self.integerLabel, 0, 1) layout.addWidget(self.doubleButton, 1, 0) layout.addWidget(self.doubleLabel, 1, 1) layout.addWidget(self.itemButton, 2, 0) layout.addWidget(self.itemLabel, 2, 1) layout.addWidget(self.textButton, 3, 0) layout.addWidget(self.textLabel, 3, 1) layout.addWidget(self.colorButton, 4, 0) layout.addWidget(self.colorLabel, 4, 1) layout.addWidget(self.fontButton, 5, 0) layout.addWidget(self.fontLabel, 5, 1) layout.addWidget(self.directoryButton, 6, 0) layout.addWidget(self.directoryLabel, 6, 1) layout.addWidget(self.openFileNameButton, 7, 0) layout.addWidget(self.openFileNameLabel, 7, 1) layout.addWidget(self.openFileNamesButton, 8, 0) layout.addWidget(self.openFileNamesLabel, 8, 1) layout.addWidget(self.saveFileNameButton, 9, 0) layout.addWidget(self.saveFileNameLabel, 9, 1) layout.addWidget(self.criticalButton, 10, 0) layout.addWidget(self.criticalLabel, 10, 1) layout.addWidget(self.informationButton, 11, 0) layout.addWidget(self.informationLabel, 11, 1) layout.addWidget(self.questionButton, 12, 0) layout.addWidget(self.questionLabel, 12, 1) layout.addWidget(self.warningButton, 13, 0) layout.addWidget(self.warningLabel, 13, 1) layout.addWidget(self.errorButton, 14, 0) layout.addWidget(self.errorLabel, 14, 1) layout.addWidget(self.native, 15, 0) self.setLayout(layout) self.setWindowTitle("Standard Dialogs") def setInteger(self): i, ok = QInputDialog.getInt(self, "QInputDialog.getInt()", "Percentage:", 25, 0, 100, 1) if ok: self.integerLabel.setText("%d%%" % i) def setDouble(self): d, ok = QInputDialog.getDouble(self, "QInputDialog.getDouble()", "Amount:", 37.56, -10000, 10000, 2) if ok: self.doubleLabel.setText("$%g" % d) def setItem(self): items = ("Spring", "Summer", "Fall", "Winter") item, ok = QInputDialog.getItem(self, "QInputDialog.getItem()", "Season:", items, 0, False) if ok and item: self.itemLabel.setText(item) def setText(self): text, ok = QInputDialog.getText(self, "QInputDialog.getText()", "User name:", QLineEdit.Normal, QDir.home().dirName()) if ok and text != '': self.textLabel.setText(text) def setColor(self): color = QColorDialog.getColor(Qt.green, self) if color.isValid(): self.colorLabel.setText(color.name()) self.colorLabel.setPalette(QPalette(color)) self.colorLabel.setAutoFillBackground(True) def setFont(self): font, ok = QFontDialog.getFont(QFont(self.fontLabel.text()), self) if ok: self.fontLabel.setText(font.key()) self.fontLabel.setFont(font) def setExistingDirectory(self): options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly directory = QFileDialog.getExistingDirectory(self, "QFileDialog.getExistingDirectory()", self.directoryLabel.text(), options=options) if directory: self.directoryLabel.setText(directory) def setOpenFileName(self): options = QFileDialog.Options() if not self.native.isChecked(): options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", self.openFileNameLabel.text(), "All Files (*);;Text Files (*.txt)", options=options) if fileName: self.openFileNameLabel.setText(fileName) def setOpenFileNames(self): options = QFileDialog.Options() if not self.native.isChecked(): options |= QFileDialog.DontUseNativeDialog files, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", self.openFilesPath, "All Files (*);;Text Files (*.txt)", options=options) if files: self.openFilesPath = files[0] self.openFileNamesLabel.setText("[%s]" % ', '.join(files)) def setSaveFileName(self): options = QFileDialog.Options() if not self.native.isChecked(): options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getSaveFileName(self, "QFileDialog.getSaveFileName()", self.saveFileNameLabel.text(), "All Files (*);;Text Files (*.txt)", options=options) if fileName: self.saveFileNameLabel.setText(fileName) def criticalMessage(self): reply = QMessageBox.critical(self, "QMessageBox.critical()", Dialog.MESSAGE, QMessageBox.Abort | QMessageBox.Retry | QMessageBox.Ignore) if reply == QMessageBox.Abort: self.criticalLabel.setText("Abort") elif reply == QMessageBox.Retry: self.criticalLabel.setText("Retry") else: self.criticalLabel.setText("Ignore") def informationMessage(self): reply = QMessageBox.information(self, "QMessageBox.information()", Dialog.MESSAGE) if reply == QMessageBox.Ok: self.informationLabel.setText("OK") else: self.informationLabel.setText("Escape") def questionMessage(self): reply = QMessageBox.question(self, "QMessageBox.question()", Dialog.MESSAGE, QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if reply == QMessageBox.Yes: self.questionLabel.setText("Yes") elif reply == QMessageBox.No: self.questionLabel.setText("No") else: self.questionLabel.setText("Cancel") def warningMessage(self): msgBox = QMessageBox(QMessageBox.Warning, "QMessageBox.warning()", Dialog.MESSAGE, QMessageBox.NoButton, self) msgBox.addButton("Save &Again", QMessageBox.AcceptRole) msgBox.addButton("&Continue", QMessageBox.RejectRole) if msgBox.exec_() == QMessageBox.AcceptRole: self.warningLabel.setText("Save Again") else: self.warningLabel.setText("Continue") def errorMessage(self): self.errorMessageDialog.showMessage("This dialog shows and remembers " "error messages. If the checkbox is checked (as it is by " "default), the shown message will be shown again, but if the " "user unchecks the box the message will not appear again if " "QErrorMessage.showMessage() is called with the same message.") self.errorLabel.setText("If the box is unchecked, the message won't " "appear again.") if __name__ == '__main__': app = QApplication(sys.argv) dialog = Dialog() dialog.show() sys.exit(app.exec_())

最后

以上就是跳跃星月为你收集整理的用pyqt5创建简单控件的全部内容,希望文章能够帮你解决用pyqt5创建简单控件所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部