Search code examples
pythonwindowpyqtpyqt4qtgui

Basic help needed in PyQt4


Basically I have a main window with a menu bar and a number of options . When I click on one of the options , my code should open another window. My code looks something like this now. All required libraries are imported.

class subwindow(self):
    //Another small window

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow , self).__init__()     
        self.window()

    def window(self):
         Action = QtGui.QAction(QtGui.QIcon('action.png') , 'action' , self)          
         Action.triggered.connect(self.a)

         mb = self.menuBar()
         option = mb.addMenu('File')
         option.addAction(Action)

         self.show()

   def a(self):
         s = subwindow()



if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    mw = MainWindow()
    sys.exit(app.exec_())

How do I run the sub-window part of the code.How do I add the QtGui.QApplication part?


Solution

  • Like @Bakuriu said in the comments, there must be only one instance of QApplication. This starts the main event loop for the application.

    You can create a new window by deriving your SubWindow class from the QDialog class, and customizing it as you want. You need to call the exec_() method of the QDialog class to get the dialog to show.

    For example, in your code:

    from PyQt4 import QtGui
    import sys
    
    class SubWindow(QtGui.QDialog):
        def __init__(self):
            super(SubWindow , self).__init__()     
            label = QtGui.QLabel("Hey, subwindow here!",self);
    
    class MainWindow(QtGui.QMainWindow):
        def __init__(self):
            super(MainWindow , self).__init__()     
            self.window()
    
        def window(self):
            Action = QtGui.QAction(QtGui.QIcon('action.png') , 'action' , self)          
            Action.triggered.connect(self.a)
    
            mb = self.menuBar()
            option = mb.addMenu('File')
            option.addAction(Action)
    
            self.show()
    
        def a(self):
    
            s = SubWindow()
            s.exec_()
    
    if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)
        mw = MainWindow()
        sys.exit(app.exec_())