pythonpyqtbuttonclickqmessagebox

buttonClicked signal of QMessageBox isn't working


I would like use a Qmessagebox in order to display some info about a running computation and as a stop function when I click on the OK button. However when I use the signal buttonClicked nothing is happenning and hte function connect with it is never called

Here a code to illustrate my issue:

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys

class SenderObject(QObject):
    something_happened = pyqtSignal( )

class myfunc():
    updateTime = SenderObject()
    def __init__(self):
        self.i = 0
        self.stop = True
    def run(self):
        while self.stop :
            self.i+=1
            if self.i%100 == 0:
                self.updateTime.something_happened.emit()
                print('infinit loop',self.i)


class SurfViewer(QMainWindow):
    def __init__(self, parent=None):
        super(SurfViewer, self).__init__()
        self.parent = parent
        self.setFixedWidth(200)
        self.setFixedHeight(200)
        self.wid = QWidget()
        self.setCentralWidget(self.wid)
        self.groups = QHBoxLayout() ####
        self.Run = QPushButton('Run')
        self.groups.addWidget(self.Run)
        self.wid.setLayout(self.groups)

        self.Run.clicked.connect(self.run)

        self.myfunc = myfunc()
        self.myfunc.updateTime.something_happened.connect(self.updateTime)

    def run(self):
        self.msg = QMessageBox()
        self.msg.setText('Click Ok to stop the loop')
        self.msg.setWindowTitle(" ")
        self.msg.setModal(False)
        self.msg.show()

        self.myfunc.run()
        self.msg.buttonClicked.connect(self.Okpressed)

    def Okpressed(self):
        self.myfunc.stop = False

    @pyqtSlot( )
    def updateTime(self ):
        self.msg.setText('Click Ok to stop the loop\ni = '+str(self.myfunc.i))
        self.parent.processEvents()



if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SurfViewer(app)
    ex.setWindowTitle('window')
    ex.show()
    sys.exit(app.exec_( ))  

So theself.msg.buttonClicked.connect(self.Okpressed) line never call the function Okpressed. Therefore, myfunc.run is never stopped. Somebody could help on this?


Solution

  • write

    self.msg.buttonClicked.connect(self.Okpressed)
    

    before

    self.myfunc.run()
    

    If you call run function before subscribing click event, curse will stuck into infinite while loop. so your click event never subscribed.

    First subscribe click event and then call "run" function of "myfunc"

    And yes never do this -

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

    Its vbad programming practice. You can write like

    from PyQt4 import QtGui
    

    And use into code like

    QtGui.QMessagebox