How to tell if two QPushButtons have been pressed (Python)

时间:2019-04-17 02:15:21

标签: python user-interface pyqt qpushbutton

I need to call a member function when both of my QPushButtons have been pressed. I cannot find a way to keep track of if they have been pressed.

I call a function when either of the buttons are clicked using ...clicked.connect(func) and within that function I have tried to: 1) return a value, 2) update a member variable. Below I have shown how I tried to create and update member variable and use a conditional to see if both variables were true so that I could call my next function.

def __init__(self, parent=None):
    super(MorphingApp, self).__init__(parent)
    self.setupUi(self)

    self.startIm = None
    self.endIm = None

    self.initialState()


def initialState(self):

    self.btn_loadStart.clicked.connect(self.loadImageS)
    self.btn_loadEnd.clicked.connect(self.loadImageE)

    if(self.startIm is True and self.endIm is True):
        self.loadedState()


def initialState(self):
    self.startIm = True


def loadImageE(self):
    self.endIm = True

My functions of course do things, but I removed parts that were irrelevant. When I run the GUI I am able to load the images but the function that is supposed to be called after both buttons have been pushed is not called. I know this because the state of the GUI is not changing as I intend.

This is my first time posting a question so let me know how to improve :)

2 个答案:

答案 0 :(得分:0)

使用简单的True / False标志检查按钮是否已至少按下一次。这两个按钮均以标志设置为False开头,因此我们可以在init方法中进行设置。

然后将用于检查是否已按下两个按钮的代码放入与其连接的功能内。最后,如果检查通过,只需调用相应的“最终”功能即可。

这是使用两个通用按钮的示例:

def __init__(self, parent=None):
    super(MorphingApp, self).__init__(parent)
    self.btn_01_pressed = False
    self.btn_02_pressed = False
    self.set_buttons()

def set_buttons(self):
    self.btn_01.clicked.connect(self.check01)
    self.btn_02.clicked.connect(self.check02)

def check01(self):
    self.btn_01_pressed = True
    if self.btn_01_pressed is True and self.btn_02_pressed is True:
        self.call_final_function()

def check02(self):
    self.btn_02_pressed = True
    if self.btn_01_pressed is True and self.btn_02_pressed is True:
        self.call_final_function()

def call_final_function(self):
    # do something great here

就像您的文章一样,我省略了一些实际代码所必需的部分(例如创建QPushButton小部件),但希望您能理解。

答案 1 :(得分:0)

def __init__(self, parent=None):
    super(MorphingApp, self).__init__(parent)
    self.setupUi(self)

    self.startIm = False
    self.endIm = False

    self.btn_loadStart.clicked.connect(self.loadImageS)
    self.btn_loadEnd.clicked.connect(self.loadImageE)


def loadImageS(self):
    self.startIm = True

    if self.startIm and self.endIm:
        self.loadedState()


def loadImageE(self):
    self.endIm = True

    if self.startIm and self.endIm:
       self.loadedState()