【问题标题】:PyQt changing specific buttonPyQt 更改特定按钮
【发布时间】:2018-09-11 21:22:54
【问题描述】:

我一直在寻找答案,但找不到解决问题的方法。我最近开始玩 PyQt 并尝试编写几个想法,其中一个是有几个按钮,上面有一些文本,当点击一个按钮时,它的文本会改变颜色。这是我的代码:

import sys
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QMainWindow,
    QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout, QMessageBox)
from PyQt5.QtCore import pyqtSlot, Qt

class App(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "Battleship"
        self.left = 50
        self.top = 50
        self.width = 750
        self.height = 500
        self.initUI()

    def initUI(self):
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setWindowTitle(self.title)
        self.setFixedSize(self.width, self.height)
        stylesheet = """QPushButton {background: #EEE; color: #11}
                    !QPushButton {background: #555; color: #EEE}"""
        self.setStyleSheet(stylesheet)
        self.grid()

        layout = QVBoxLayout()
        layout.addWidget(self.box)
        self.setLayout(layout)

        self.show()

    def grid(self):
        self.box = QGroupBox()
        self.layout = QGridLayout()
        self.box.setLayout(self.layout)

        self.button1 = QPushButton('X', self)
        self.button2 = QPushButton('X', self)
        self.button3 = QPushButton('X', self)

        self.button1.clicked.connect(self.pick)
        self.button2.clicked.connect(self.pick)
        self.button3.clicked.connect(self.pick)

        self.layout.addWidget(self.button1)
        self.layout.addWidget(self.button2)
        self.layout.addWidget(self.button3)

    def pick(self):
        # turn 'X' from black to red ONLY on the clicked button
        # while leaving the others untouched 
        pass

#---------------------------------------------------------------
if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = App()
    sys.exit(app.exec_())

为了做到这一点,'pick' 函数必须是什么样子?澄清一下:我不想制作三个单独的功能,每个按钮一个(因为对于大量按钮来说这是非常不切实际的),而是一个适用于任何按钮的单一功能。

【问题讨论】:

    标签: python pyqt pyqt5


    【解决方案1】:

    sender() 方法向我们返回发出信号的对象,在您的情况下,按钮将被按下:

    def pick(self):
        # turn 'X' from black to red ONLY on the clicked button
        # while leaving the others untouched 
        btn = self.sender()
        btn.setStyleSheet("color: red")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 2016-01-04
      • 2016-08-17
      • 2019-02-09
      • 1970-01-01
      相关资源
      最近更新 更多