-1

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()
Hrvoje T
  • 3,365
  • 4
  • 28
  • 41

1 Answers1

2

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 :)

tobilocker
  • 891
  • 8
  • 27
  • Ok, when I do that (self not this), widgets do show but in top left corner, one over the other. However, I switched QMainWindow with QWidget and now it is ok. Thanks! – Hrvoje T May 24 '16 at 08:38
  • 1
    Did you try the updated answer? `setCentralWidget` should fill your `QMainWindow` instance. Keep me updated if you won't get the upper example working. I can give a more detailed answer also. – tobilocker May 24 '16 at 08:45
  • I kept QMainWindow, added QLabel and QLineEdit widgets in grid and set widget as centrawidged in QMainWindow. It works, thanks! – Hrvoje T May 24 '16 at 09:16