Issue
Using the answer to this question: Python: PyQt Popup Window I was able to produce a gui with a button that has a popup window.
What I would like to do now is press a button in the popup and pass a command to a function in the MyPopup class. This is easily accomplished using the lambda function, however, when you press the button in the mainwindow the popup window no longer closes and a new instance of the popup is created, resulting in two popup screens. From my understanding this is due to a signal being produced by the lambda function. Is there a way to clear this lambda function such that when the main button is pressed the old instance is closed and a new instance of the popup is loaded?
If this is not possible using lambda, is there another way to pass variables to the function to obtain the results I am looking for?
Here are some example screenshots to better illustrate my issue:
Running Script without lambda in popup
Running Script with lambda in popup
Here is the modified popup code from the previous question:
import sys
from PyQt4.Qt import *
class MyPopup(QWidget):
def __init__(self):
QWidget.__init__(self)
self.btn_popup = QPushButton("broken", self)
self.btn_popup.clicked.connect(lambda state, x='lambda prevents refresh': self.function(x))
def function(self, word):
print('Now I dont close',word)
def paintEvent(self, e):
dc = QPainter(self)
dc.drawLine(0, 0, 100, 100)
dc.drawLine(100, 0, 0, 100)
class MainWindow(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.cw = QWidget(self)
self.setCentralWidget(self.cw)
self.btn1 = QPushButton("Click me", self.cw)
self.btn1.setGeometry(QRect(0, 0, 100, 30))
self.connect(self.btn1, SIGNAL("clicked()"), self.doit)
self.w = None
def doit(self):
print ("Opening a new popup window...")
self.w = MyPopup()
self.w.setGeometry(QRect(100, 100, 400, 200))
self.w.show()
class App(QApplication):
def __init__(self, *args):
QApplication.__init__(self, *args)
self.main = MainWindow()
self.main.show()
def main(args):
global app
app = App(args)
app.exec_()
if __name__ == "__main__":
main(sys.argv)
Solution
It seems that if the lambda function does not exist the popup is destroyed, verify this by adding the following:
class MyPopup(QWidget):
def __init__(self, i):
[..]
self.destroyed.connect(lambda: print("destroyed"))
in the case where there was no lambda, the message was printed, while in the other case it was not. So the solution is to destroy it manually using the deleteLater()
method:
def doit(self):
print ("Opening a new popup window...")
if self.w:
self.w.deleteLater()
self.w = MyPopup()
self.w.setGeometry(QRect(100, 100, 400, 200))
self.w.show()
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.