在PyQt中阻止按钮单击信号

时间:2016-09-15 17:04:10

标签: python user-interface pyqt signals-slots

我有一个使用pyqt的.animateClick()功能的程序,向用户显示用户必须按特定顺序复制的一系列不同按钮点击。问题是我不希望animateClick()发送信号,我只想要用户点击按钮信号。以下是我的一些代码,用于演示我的意思,以及我如何尝试解决该问题(这不起作用)。我简化了我的代码,因此更容易阅读,如果您有任何问题,请告诉我。

from PyQt4 import QtCore,QtGui
global flag
global ai_states
ai_states = []
user_states = []


class Program(object):
    # Set up the push buttons
    #Code Here.

    # Connect push buttons to function get_state()
    self.pushButton.clicked.connect(self.get_state)
    self.pushButton_2.clicked.connect(self.get_state)
    self.pushButton_3.clicked.connect(self.get_state)        
    self.pushButton_4.clicked.connect(self.get_state)

    # Code that starts the start() function

    def start(self):
        flag = 0
        ai_states[:] = []
        i = -1
        # Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.

        for k in ai_states:
            i = i + 1
            # Code here that animates button clicks determined by ai_states

            # Changes the flag to 1 once the loop ends
            if i == len(ai_states):
                flag = 1

    def get_state(self):
        if flag == 1:
            user_states.append(str(self.centralWidget.sender().text()))
        else:
            pass

        if len(user_states) == len(ai_states):
            # Checks to make sure the user inputted the same clicks as the ai_states

即使在start()函数之后标志确实为1,它仍然附加了animatedClick()信号。我究竟做错了什么?我是GUI编程的新手,所以我可能会以非常糟糕的方式解决这个问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

除非你真的需要,否则永远不要使用全局变量。如果需要对变量的共享访问,请使用实例属性:

from PyQt4 import QtCore,QtGui   

class Program(object):
    def __init__(self):
        self.ai_states = []
        self.user_states = []
        self.flag = 1

        # Set up the push buttons
        # Code Here

        # Connect push buttons to function get_state()
        self.pushButton.clicked.connect(self.get_state)
        self.pushButton_2.clicked.connect(self.get_state)
        self.pushButton_3.clicked.connect(self.get_state)        
        self.pushButton_4.clicked.connect(self.get_state)

    # Code that starts the start() function

    def start(self):
        self.flag = 0
        del self.ai_states[:]
        i = -1
        # Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.

        for k in self.ai_states:
            i = i + 1
            # Code here that animates button clicks determined by ai_states

        # Changes the flag to 1 once the loop ends
        self.flag = 1

    def get_state(self):
        if self.flag == 1:
            self.user_states.append(str(self.centralWidget.sender().text()))

        if len(self.user_states) == len(self.ai_states):
            # Checks to make sure the user inputted the same clicks as the ai_states