【问题标题】:applying dynamic solution to Pyqt5 connection将动态解决方案应用于 Pyqt5 连接
【发布时间】:2016-08-12 13:04:30
【问题描述】:

这是我正在研究的 Zetcode.com 的一个简单代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we create a skeleton
of a calculator using a QGridLayout.

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import (QWidget, QGridLayout, 
    QPushButton, QApplication)


class Example(QWidget):

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

        self.initUI()


    def initUI(self):

        grid = QGridLayout()
        self.setLayout(grid)

        names = ['Cls', 'Bck', '', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+']

        positions = [(i,j) for i in range(5) for j in range(4)]

        for position, name in zip(positions, names):

            if name == '':
                continue
            button = QPushButton(name)
            grid.addWidget(button, *position)

        self.move(300, 150)
        self.setWindowTitle('Calculator')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

现在,我正在尝试为每个单击的按钮应用 button.setDisable 选项。

一种方法是创建一个新列表并将每个按钮附加到创建的列表中。从这个列表中,我们可以做到以下几点:

button_list[0].clicked.connect(self.on_click):
button_list[1].clicked.connect(self.on_click1):

对于每个新方法,我们需要定义:

def on.click(self):
    button_list[0].setEnabled(False)

这是一个有效的解决方案。但是有没有更动态的方法来解决这个问题?

任何想法都将不胜感激。

【问题讨论】:

    标签: python user-interface dynamic pyqt5


    【解决方案1】:

    使用lambdafunctools.partial,您可以做到这一点:

    def on.click(self, numb):
        button_list[numb].setEnabled(False)
    

    使用lambda 调用:

    button_list[1].clicked.connect(lambda: self.on_click(1))
    

    或者partial:

    button_list[1].clicked.connect(partial(self.on_click, 1))
    

    【讨论】:

    • 谢谢 Flippy。我发现部分函数对于进一步的开发也非常有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多