Search code examples
qtpython-2.7pysideqlineeditqlabel

I can't see QLabel and QLineEdit widgets in my QMainWindow in Python2


I wrote this code and I don't understand why widgets QLabel and QLineEdit don't show up? Do I have to put them in another class? It's Python2.7 and PySide.

This is how a window looks like when I run the code:

enter image description here

#!/usr/bin/env python
# coding: utf-8

import sys
import crypt
from PySide import QtGui

class MyApp(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyApp, self).__init__(parent)
        self.initui()

    def initui(self):
        # main window size, title and icon
        self.setMinimumSize(500, 350)
        self.setWindowTitle("Calculate a password hash in Linux")

        # lines for entering data
        self.saltLabel = QtGui.QLabel("Salt:")
        self.saltLine = QtGui.QLineEdit()
        self.saltLine.setPlaceholderText("e.g. $6$xxxxxxxx")

        # set layout
        grid = QtGui.QGridLayout()
        grid.addWidget(self.saltLabel, 0, 0)
        grid.addWidget(self.saltLine, 1, 0)

        self.setLayout(grid)

        # show a widget
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    instance = MyApp()
    instance.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

Solution

  • How about using a QWidget as centralWidget

    widget = QWidget()
    widget.setLayout(grid)
    #add your widgets and...
    self.setCentralWidget(widget)
    

    and you don't need to call show() since you do in your __main__

    It's up to the owner but i would recommend sublassing a QWidget and leave your QMainWindow instance as concise as possible. An implementation could be:

    class MyWidget(QtGui.QWidget):
    
        def __init__(self, *args):
            QtGui.QWidget.__init__(self, *args)
            grid = QtGui.QGridLayout()
            #and so on...
    

    and use this as widget in your QMainWindow instance. This increases readability and maintainability and reusability a lot :)