Search code examples
pythonpyqtqwidget

Closing a QWidget opened from a QMainWindow


I need to show a QWidget, which code is written in another module, when a certain button is pressed. To accomplish this, I wrote this code:

class Window(QMainWindow):
  def __init__(self):
    QMainWindow.__init__(self)
    #A lot of stuff in here

    #The button is connected to the method called Serial_connection
    self.connect(self.btn_selection_tool3, SIGNAL("clicked()"), self.Serial_connection)

  def Serial_connection(self):
    LiveData.LiveData(self).show()

Doing this, I open a QWidget and it works fine. But, when I want to close this QWidget, I can not do it. This is the code of the QWidget:

class LiveData(QWidget):
  def __init__(self,parent = None):
    super(QWidget, self).__init__(parent)
    #Another stuff in here

    #I create a "close" button connected to another method 
    self.connect(self.closeBtn, QtCore.SIGNAL("clicked()"), self.StopAndClose)

  def StopAndClose(self):
    print "Closing window"
    self.close()  #HERE IS WHERE I HAVE THE PROBLEM

I´ve tried several options like: self.close(), self.accept() or even sys.exit(1). The problem with the latter sys.exit(1) is that it closes the QWidget and the QMainWindow. So, how can I close this QWidget only? Hope you can help me.


Solution

  • You probably want your QWidget to be a QDialog. If it's a temporary modal widget, you should be calling the dialog like this

    dialog = LiveData.LiveData(self)
    dialog.exec_()
    

    If you just want to show the dialog at the same time as your main window, and users are meant to interact with both (though from a design perspective, this doesn't sound like a great idea), you can continue to use .show()

    Also, you should use the new-style signal/slot syntax. The old syntax hasn't been used for many years.

    self.closeButton.clicked.connect(self.StopAndClose)
    

    Though, for a QDialog you can just do

    self.closeButton.clicked.connect(self.accept)