【问题标题】:Button Icon Change on Click单击时按钮图标更改
【发布时间】:2014-02-16 15:37:19
【问题描述】:

我正在尝试制作一个 GUI 应用程序来更改右键单击按钮上的图标! 这是我的简单代码:

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()

这里是图片:

Link of the GUI Application

我已经尝试了几个小时,但我仍然无法做到这一点,有什么想法吗? 如果可能的话,我还想使用图像小部件而不是按钮、标签或其他东西..

谢谢!

【问题讨论】:

    标签: qt button user-interface pyside python-3.3


    【解决方案1】:

    你可以使用QObject::sender来获取被点击的按钮。

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

    【讨论】:

    • 嗯,它有效!有没有办法让小部件图像可点击,而不是使用按钮?
    • 小部件图像是什么意思?您可以通过在其上安装事件过滤器来获取任何小部件的点击事件(例如,可以显示像素图的 QLabel)。 IE。调用self.label.installEventFilter(self) 并实现主窗口类的eventFilter 方法。
    猜你喜欢
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2013-11-05
    • 2019-07-06
    • 1970-01-01
    • 2023-02-07
    相关资源
    最近更新 更多