PyQt4: Difference between QWidget and QMainWindow

19,716

Solution 1

QMainWindow is a class that understands GUI elements like a

  • toolbar,
  • statusbar,
  • central widget,
  • docking areas.

QWidget is just a raw widget.

When you want to have a main window for you project, use QMainWindow.

If you want to create a dialog box (modal dialog), use QWidget, or, more preferably, QDialog.

Solution 2

If you are not going to use a menu bar, tool bar or dock widgets, they are the same to you. If you will use one of those, use QMainWindow. And don't forget to call setCentralWidget to your main layout widget.

Share:
19,716

Related videos on Youtube

Nyxynyx
Author by

Nyxynyx

Hello :) I have no formal education in programming :( And I need your help! :D These days its web development: Node.js Meteor.js Python PHP Laravel Javascript / jQuery d3.js MySQL PostgreSQL MongoDB PostGIS

Updated on June 30, 2020

Comments

  • Nyxynyx
    Nyxynyx almost 4 years

    When reading through a PyQt4 tutorial, sometimes the examples uses QtGui.QMainWindow, sometimes it uses QtGui.QWidget.

    Question: How do you tell when to use which?

    import sys
    from PyQt4 import QtGui
    
    
    class Example(QtGui.QMainWindow):
    
        def __init__(self):
            super(Example, self).__init__()
    
            self.initUI()
    
        def initUI(self):               
    
            self.statusBar().showMessage('Ready')
    
            self.setGeometry(300, 300, 250, 150)
            self.setWindowTitle('Statusbar')    
            self.show()
    
    
    def main():
    
        app = QtGui.QApplication(sys.argv)
        ex = Example()
        sys.exit(app.exec_())
    
    
    if __name__ == '__main__':
        main()
    

    Another code example:

    import sys
    from PyQt4 import QtGui, QtCore
    
    class Example(QtGui.QWidget):
    
        def __init__(self):
            super(Example, self).__init__()
    
            self.initUI()
    
        def initUI(self):      
    
            cb = QtGui.QCheckBox('Show title', self)
            cb.move(20, 20)
            cb.toggle()
            cb.stateChanged.connect(self.changeTitle)
    
            self.setGeometry(300, 300, 250, 150)
            self.setWindowTitle('QtGui.QCheckBox')
            self.show()
    
        def changeTitle(self, state):
    
            if state == QtCore.Qt.Checked:
                self.setWindowTitle('QtGui.QCheckBox')
            else:
                self.setWindowTitle('')
    
    def main():
    
        app = QtGui.QApplication(sys.argv)
        ex = Example()
        sys.exit(app.exec_())
    
    
    if __name__ == '__main__':
        main()