在Qt中等待while循环中的clicked()事件

时间:2016-09-07 14:04:20

标签: python qt

如何在每次迭代中等待for循环,用户按下给定的QPushButton?

for i in range(10):


        while (the button has not been pressed):
            #do nothing
        #do something

主要问题是我无法捕获while循环中的clicked()事件。

修改

最后我最终得到了:

 for i in range(10):
        self.hasBeenProcessed = False

        # only one function can modify this boolean
        # and this function is connected to my button
        while (self.hasBeenProcessed is not True):
                QtCore.QCoreApplication.processEvents()

1 个答案:

答案 0 :(得分:2)

所以,我有点怀疑你是否应该做你所描述的事情。此外,我同意如果您显示更多代码来描述上下文会更好。

话虽如此,下面的代码是对您所描述的内容的抨击。请注意,这绝不是生产就绪代码,而是更多粗略的例子来说明原理。

我在Button1按下时调用了一个函数,并通过调用while使事件循环在QCoreApplication.processEvents()循环内旋转,这意味着GUI仍然会接受例如鼠标事件。现在,这应该是通常做的事情。然而,在某些情况下可能需要这样做,例如,如果你有一个非模态QProgressDialog并且想要在对话框计数器增加时保持GUI更新(参见例如http://doc.qt.io/qt-4.8/qprogressdialog.html#value-prop

然后第二部分只是在按下按钮2时修改第二个函数中的全局变量,while循环将退出。

如果有帮助,请告诉我

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

btn2pushed = False

def window():
   app = QApplication(sys.argv)
   win = QDialog()
   b1 = QPushButton(win)
   b1.setText("Button1")
   b1.move(50,20)
   b1.clicked.connect(b1_clicked)

   b2 = QPushButton(win)
   b2.setText("Button2")
   b2.move(50,50)
   QObject.connect(b2,SIGNAL("clicked()"),b2_clicked)

   win.setGeometry(100,100,200,100)
   win.setWindowTitle("PyQt")
   win.show()
   sys.exit(app.exec_())

def b1_clicked():
   print "Button 1 clicked"
   i = 0
   while ( btn2pushed != True ):
       # not doing anything                                                                                                                                                                                                   
       if ( i % 100000 == 0 ):
           print "Waiting for user to push button 2"
       QCoreApplication.processEvents()
       i += 1;

   print "Button 2 has been pushed"


def b2_clicked():
    global btn2pushed
    btn2pushed = True

if __name__ == '__main__':
   window()