Pergunta

I want to open a popup window in pyqt interface using this class

class MyPopup(QWidget):
  def __init__(self):
    QWidget.__init__(self)
    self.initUI()
    self.res=0

  def initUI(self):
        self.btn = QtGui.QPushButton('Continue', self)
        self.btn.move(20, 160)
        self.btn.clicked.connect(self.showDialogcontinue)
        self.btn = QtGui.QPushButton('Quit', self)
        self.btn.move(180,160)
        self.btn.clicked.connect(self.showDialogstop)
        self.setGeometry(600, 600, 290, 150)
        self.setWindowTitle('EUT Setup')
        self.show()

  def showDialogcontinue(self):
    self.close()
    self.res=1

  def showDialogstop(self):
    self.close()
    self.res=0

So when I use it, in a push button method

    self.w = MyPopup()
    self.w.setGeometry(QRect(100, 100, 400, 200))
    self.w.show()
    if self.w.res==1:
        print "start"
        self.__thread.start()
    else:
        print "stop"

I can't get the result to launch or not mythread ___thread . Please what's wrong? Could you help?

Foi útil?

Solução

The problem is that showing a widget does not block the execution of code. So the if check is reached long before any button in the widget is clicked.

To solve this you can change the parent class to a QDialog, and show it with exec_() which will block until the dialog is closed.

And setting self.res=0 before self.initUI() since anything after self.initUI() would be called after the dialog closed. And that would reset res to 0 again.

class MyPopup(QtGui.QDialog):
  def __init__(self, parent=None):
    super(MyPopup, self).__init__(parent)
    self.res=0
    self.initUI()

  def initUI(self):
        self.btn = QtGui.QPushButton('Continue', self)
        self.btn.move(20, 160)
        self.btn.clicked.connect(self.showDialogcontinue)
        self.btn = QtGui.QPushButton('Quit', self)
        self.btn.move(180,160)
        self.btn.clicked.connect(self.showDialogstop)
        self.setGeometry(600, 600, 290, 150)
        self.setWindowTitle('EUT Setup')
        self.exec_()

  def showDialogcontinue(self):
    self.res=1
    self.close()

  def showDialogstop(self):
    self.res=0
    self.close()

if all you need is a single true\false value back from the dialog. You can do it easier using the accept\reject functions of a QDialog.

class MyPopup(QtGui.QDialog):
  def __init__(self):
    super(MyPopup, self).__init__()
    self.initUI()

  def initUI(self):
        self.btn = QtGui.QPushButton('Continue', self)
        self.btn.move(20, 160)
        self.btn.clicked.connect(self.accept)
        self.btn = QtGui.QPushButton('Quit', self)
        self.btn.move(180,160)
        self.btn.clicked.connect(self.reject)
        self.setGeometry(600, 600, 290, 150)
        self.setWindowTitle('EUT Setup')

w = MyPopup()
if w.exec_():
    print("Start thread")
else:
    print("Stop")
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top