小编tsc*_*v11的帖子

循环创建 PyQt5 按钮:所有按钮触发相同的回调

我应该提到我已经阅读了这些但我仍然无法实现我的目标:

[在 for 循环中使用字典来创建按钮不起作用

[ QtCore.QObject.connect 在循环中只影响最后一个实例

我的目标是制作一个 linux 'launcher' 应用程序。按钮创建、放置等工作就像一个魅力,但有一个问题 - 所有按钮触发相同的回调 - 最后一个在按钮创建循环中连接。

这是脚本的基本版本,用于说明我正在尝试执行的操作:

class App(QMainWindow):

    def launch(self, filepath):
        subprocess.run(filepath)


    def __init__(self):
        super(App, self).__init__()

        for btn in matrix:

            filepath = matrix[btn]['path']
            icon = matrix[btn]['setIcon']
            posx = matrix[btn]['posx']
            posy = matrix[btn]['posy']

            matrix[btn] = QToolButton(self)
            matrix[btn].setIcon(QIcon(icon))
            matrix[btn].setIconSize(QSize(64, 64))
            matrix[btn].resize(100, 100)
            matrix[btn].move(posx, posy)
            matrix[btn].clicked.connect(lambda launch: self.launch(filepath))

        self.initUI()


    def initUI(self):

        self.setGeometry(150, 150, 1250, 650)
        self.setWindowTitle('LinuxLauncher')

        self.show()


    if __name__ == '__main__':

        app = QApplication(sys.argv)
        ex = App()
        sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

我知道有一个答案,但我已经研究了几个小时 - 我很感激有人能帮我解决这个问题 - …

python linux pyqt qpushbutton pyqt5

3
推荐指数
1
解决办法
1696
查看次数

标签 统计

linux ×1

pyqt ×1

pyqt5 ×1

python ×1

qpushbutton ×1