凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

23. PyQt6 切换按钮

2023-10-17 python 355
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QFrame
from PyQt6.QtGui import QGuiApplication, QColor


class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.square = None
        self.color = None
        self.initUI()

    def initUI(self):
        self.setWindowTitle("PyQt6 切换按钮")

        self.color = QColor(0, 0, 0)
        redb = QPushButton("红色", self)
        redb.setCheckable(True)
        redb.move(10, 10)

        redb.clicked[bool].connect(self.setColor)

        greenb = QPushButton("绿色", self)
        greenb.setCheckable(True)
        greenb.move(10, 60)

        greenb.clicked[bool].connect(self.setColor)

        blueb = QPushButton("蓝色", self)
        blueb.setCheckable(True)
        blueb.move(10, 110)

        blueb.clicked[bool].connect(self.setColor)

        self.square = QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet("QWidget { background-color: %s}" % self.color.name())

        self.setGeometry(100, 100, 400, 300)
        self.center()

    def setColor(self, pressed):
        source = self.sender()

        if pressed:
            val = 255
        else:
            val = 0

        if source.text() == "红色":
            self.color.setRed(val)
        elif source.text() == "绿色":
            self.color.setGreen(val)
        else:
            self.color.setBlue(val)

        self.square.setStyleSheet("QWidget { background-color: %s}" % self.color.name())

    def center(self):
        qr = self.frameGeometry()
        cp = QGuiApplication.primaryScreen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    cls_app = App()
    cls_app.show()
    sys.exit(app.exec())

image.png

文章评论

0条评论