簡體   English   中英

我想使用pyqt5為按鈕創建彩色動畫

[英]I want to create a color animation for a button with pyqt5

我使用pyqt5 QpushButton創建了一個虛擬按鈕鍵盤,並在滿足QLineEdit字符的長度時使ok按鈕處於活動狀態。 我想在激活按鈕時創建一個彩色動畫效果(漂亮地繪制)。 使用QPropertyAnimation我不知道您是否認為我制作了QT手冊。

import sys
from functools import partial
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.center_widget = QStackedWidget()
        self.setCentralWidget(self.center_widget)
        self.SearchUI()
    def SearchUI(self):
        widget = QWidget()
        mainlayout = QVBoxLayout(widget)
        button_gruop = QGroupBox()
        gridlayout = QGridLayout()

        count = 0
        self.numberSave = ''
        self.buttons = []
        self.search = QLineEdit('')
        self.search.setAlignment(Qt.AlignCenter)
        self.search.setStyleSheet('font: bold 50pt')
        self.search.setMaxLength(13)
        self.search.setEchoMode(QLineEdit.Password)
        virtualkeypad = [
            '7','8','9',
            '4','5','6',
            '1','2','3',
            'BACK','0','OK'
        ]
        positions = [(i, j) for i in range(4) for j in range(3)]
        for position, name in zip(positions, virtualkeypad):
            self.buttons.append(QPushButton(name))
            gridlayout.addWidget(self.buttons[count], *position)
            self.buttons[count].setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
            count += 1

        for i in [0,1,2,3,4,5,6,7,8,10]:
            self.buttons[i].clicked.connect(partial(self.ButtonNumberSelect, '{}'.format(virtualkeypad[i])))
            self.buttons[i].setStyleSheet('background-color: orange; font: bold 50pt;')

        self.buttons[9].clicked.connect(self.ButtonBackSpace)
        self.buttons[11].clicked.connect(self.ButtonEnter)
        self.buttons[9].setStyleSheet('background-color: orange; font: 50pt;')
        self.buttons[11].setStyleSheet('background-color: none; font: 50pt;')
        self.buttons[11].setEnabled(False)

        button_gruop.setLayout(gridlayout)
        mainlayout.addWidget(self.search)
        mainlayout.addWidget(button_gruop)
        mainlayout.setContentsMargins(150,150,150,150)
        mainlayout.contentsMargins()
        self.center_widget.addWidget(widget)

    def ButtonNumberSelect(self, button):
        self.numberSave += button
        self.search.setText(self.numberSave)
        if len(self.numberSave) == 13:
            a = QGraphicsColorizeEffect(self.buttons[11])
            self.buttons[11].setGraphicsEffect(a)
            animation_button = QPropertyAnimation(a)
            animation_button.setStartValue(QColor(Qt.cyan))
            animation_button.setKeyValueAt(0.10(Qt.darkCyan))
            animation_button.setKeyValueAt(0.10(Qt.darkBlue))
            animation_button.setKeyValueAt(0.10(Qt.darkGray))
            animation_button.setKeyValueAt(0.10(Qt.darkGreen))
            animation_button.setKeyValueAt(0.10(Qt.darkMagenta))
            animation_button.setKeyValueAt(0.10(Qt.darkYellow))
            animation_button.setEndValue(QColor(255,255,255))
            animation_button.setDuration(5000)
            animation_button.setLoopCount(5)
            animation_button.start()
            self.buttons[11].setEnabled(True)
            self.buttons[11].setStyleSheet('background-color: orange; font: 50pt;')
            self.numberSave = ''
        else:
            self.buttons[11].setEnabled(False)
            self.buttons[11].setStyleSheet('background-color: white; font: 50pt;')

    def ButtonBackSpace(self):
        self.numberSave = self.numberSave[:-1]
        self.search.setText(self.numberSave)

    def ButtonEnter(self):
        self.center_widget.setCurrentIndex(0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    fream = MainWindow()
    fream.show()
    app.exec_()

=添加編輯=運行代碼並使用數字按鈕生成13個數字時出現錯誤。

Problem Event Name: APPCRASH
  Application name: python.exe
  Application version: 3.6.6150.1013
  Application timestamp: 5b32fb86
  Error Module Name: ucrtbase.DLL
  Error Module Version: 10.0.10586.1171
  Error module timestamp: 59ae5046
  Exception code: 40000015
  Exception offset: 000846fa
  OS version: 6.1.7601.2.1.0.256.48
  Locale ID: 1042
  MORE INFORMATION 1: 5951
  Additional information 2: 59510a33f844cfe7fca7e6582e6da18f
  MORE INFORMATION 3: 99f9
  MORE INFORMATION 4: 99f926c0d0d283713191de33752f806a

def ButtonNumberSelect (self, button):該零件似乎有問題。

a = QGraphicsColorizeEffect (self.buttons [11])
self.buttons [11] .setGraphicsEffect (a)
animation_button = QPropertyAnimation (a)
animation_button.setStartValue (QColor (Qt.darkBlue))
animation_button.setEndValue (QColor (255,255,255))
animation_button.setDuration (5000)
animation_button.setLoopCount (5)
animation_button.start ()

正如我在評論中指出的那樣,我仍然不知道您試圖寫些什么:

animation_button.setKeyValueAt(0.10(Qt.XXX))

更合適的是:

animation_button.setKeyValueAt(0.10, Qt.XXX)

但是將所有百分比設置為0.1%是沒有意義的。

另一方面,假設您要更改顏色, QPropertyAnimation不會告訴您要修改的屬性,例如:

animation_button = QPropertyAnimation(a, b"color")

通過重新整理和清理代碼,您將獲得以下內容:

from PyQt5 import QtCore, QtGui, QtWidgets
from functools import partial


class BeautifulButton(QtWidgets.QPushButton):
    def __init__(self, *args, **kwargs):
        super(BeautifulButton, self).__init__(*args, **kwargs)
        effect = QtWidgets.QGraphicsColorizeEffect(self)
        self.setGraphicsEffect(effect)

        self.animation = QtCore.QPropertyAnimation(effect, b"color")

        self.animation.setStartValue(QtGui.QColor(QtCore.Qt.cyan))
        self.animation.setEndValue(QtGui.QColor(255,255,255))

        self.animation.setLoopCount(5)
        self.animation.setDuration(5000)


class Page(QtWidgets.QWidget):
    okClicked = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(Page, self).__init__(parent)
        mainlayout = QtWidgets.QVBoxLayout(self)
        self.keypad = QtWidgets.QGroupBox()
        self.search = QtWidgets.QLineEdit()
        self.search.setProperty("last_text", "")
        self.search.setAlignment(QtCore.Qt.AlignCenter)
        self.search.setStyleSheet('font: bold 50pt')
        self.search.setMaxLength(13)
        self.search.setEchoMode(QtWidgets.QLineEdit.Password)
        mainlayout.addWidget(self.search)
        mainlayout.addWidget(self.keypad)
        mainlayout.setContentsMargins(150,150,150,150)

        lay = QtWidgets.QGridLayout(self.keypad)

        virtualkeypad = [
            '7','8','9',
            '4','5','6',
            '1','2','3',
            'BACK','0','OK'
        ]
        positions = [(i, j) for i in range(4) for j in range(3)]

        self.buttons = {}

        for position, name in zip(positions, virtualkeypad):
            if name == "OK":
                btn = BeautifulButton(name)
                btn.setStyleSheet('background-color: none; font: 50pt;')
                btn.setDisabled(True)
            else:
                btn = QtWidgets.QPushButton(name)
                btn.setStyleSheet('background-color: orange; font: bold 50pt;')

            self.buttons[name] = btn
            btn.clicked.connect(partial(self.on_clicked, name))
            btn.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
            lay.addWidget(btn, *position)

    def on_clicked(self, text):
        if text in  map(str, range(0, 10)):
            if len(self.search.text()) == 13:
                self.search.clear()
            self.search.insert(text)
            btn = self.buttons["OK"]
            if len(self.search.text()) == 13:
                btn.setEnabled(True)
                btn.setStyleSheet('background-color: orange; font: bold 50pt;')
                btn.animation.start()
            else:
                btn.setEnabled(False)
                btn.setStyleSheet('background-color: white; font: 50pt;')
                btn.animation.stop()
        elif text == "BACK":
            self.search.backspace()
        elif text == "OK":
            self.okClicked.emit()


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.center_widget = QtWidgets.QStackedWidget()
        self.setCentralWidget(self.center_widget)
        self.SearchUI()

    def SearchUI(self):
        page = Page()
        page.okClicked.connect(partial(self.center_widget.setCurrentIndex, 0))
        self.center_widget.addWidget(page)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM