Button Icon Change on Click

一曲冷凌霜 提交于 2019-12-25 16:54:07

问题


I'm trying to make a GUI Application that change the icon on the right clicked button! This is my simple code:

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Ui_MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi()

    def setupUi(self):
        widget = QWidget()
        layout = QGridLayout()
        self.buttons = list()

        for x in range(3):
            row = list()
            for y in range(3):
                button = QPushButton(QIcon('Empty-Cell.png'), '{},{}'.format(x, y))
                button.clicked.connect(self.button_click)
                row.append(button)
                layout.addWidget(button, x, y)
            self.buttons.append(row)

        widget.setLayout(layout)
        self.setCentralWidget(widget)

    def button_click(self):
        # Change icon HERE!

def main():
    app = QApplication(sys.argv)
    ui = Ui_MainWindow()
    ui.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

and here the image:

Link of the GUI Application

I've been trying for hours but i'm not still able to do that, any ideas? I would like also to use an Image Widget instead of a button, label, or whatelse if it is possible..

Thank you!


回答1:


You can use QObject::sender to get the clicked button.

def button_click(self):
    test_pixmap = QPixmap(16, 16)
    test_pixmap.fill(Qt.red)
    self.sender().setIcon(QIcon(test_pixmap))


来源:https://stackoverflow.com/questions/21353065/button-icon-change-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!