Search code examples
pythonqtpyqtsignalssignals-slots

creating widgets in user defined slots


I am building a simple application in which I have a button, which when clicked prints hello.

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

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QMainWindow):
    def __init__(self):
        super(Example, self).__init__();
        self.initUI()


    def initUI(self):
        self.button = QtGui.QPushButton("print hello",self)
        self.button.clicked.connect(self.print_hello)

    def print_hello(self):
        self.button.deleteLater()
        self.label = QtGui.QLabel("hello",self)



def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

if __name__=='__main__':
    main()

Now, the slot print_hello() doesn't output the label "hello"
Why is this happening?


Solution

  • The label isn't shown because, although you have created it, you haven't told the GUI to show it yet. You could, for example, want to do some other operations on the label in the background before you decide to show it.

    Adding self.label.show() to print_hello() will make it visible.