简体   繁体   English

将动态解决方案应用于Pyqt5连接

[英]applying dynamic solution to Pyqt5 connection

Here is one simple code from Zetcode.com, that I am studying: 以下是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_())

Now, I am trying to apply the button.setDisable option for every button which is clicked. 现在,我正在尝试为每个单击的按钮应用button.setDisable选项。

One way is to create a new list and append each button to the created list. 一种方法是创建一个新列表并将每个按钮附加到创建的列表。 From this list, we could do following: 从这个列表中,我们可以做到以下几点:

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

And for each new method, we would then need to define: 对于每种新方法,我们需要定义:

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

This is a solution that works. 这是一个有效的解决方案。 But is there any more dynamic way to solve this issue? 但有没有更有效的方法来解决这个问题?

Would appreciate any ideas. 会欣赏任何想法。

With lambda or functools.partial , you can do just that: 使用lambdafunctools.partial ,您可以这样做:

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

Invoke with lambda : lambda调用:

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

Or with partial : partial

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM