0

So I have written this PyQt5 code and could not fathom why is home not being executed when I click on the download button. On the other hand if I move the contents of the home to __init__ it is working fine. What exactly is going wrong here and how to rectify it?

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import Qt

class GUI(QMainWindow):

    def __init__(self):
        super(GUI, self).__init__()
        self.setGeometry(50, 50, 800, 500)
        self.setWindowTitle('App')
        self.setWindowIcon(QIcon('icon.ico'))

        backgroundImage =  QImage('back.jpg')
        backgroundScaledImage = backgroundImage.scaled(QSize(800,500))
        palette = QPalette()
        palette.setBrush(10, QBrush(backgroundScaledImage))                     
        self.setPalette(palette)

        self.progress = QProgressBar(self)
        self.progress.setGeometry(20, 30, 300, 20)

        self.btn = QPushButton('Download', self)
        self.btn.move(200,120)
        self.btn.clicked.connect(self.home)
        #self.home()

        QApplication.setStyle(QStyleFactory.create('plastique'))



        self.show()


    def home(self):

        print('whoa')
        # Create textbox
        self.textbox = QLineEdit(self)
        self.textbox.move(200, 200)
        self.textbox.resize(280,40)

        # Create a button in the window
        self.button = QPushButton('Show text', self)
        self.button.move(20,80)
        self.show()

When I uncomment the line #self.home() or directly put the code at that place the code is working as expected. But when I click the Downloadbutton nothing is happening.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
DuttaA
  • 903
  • 4
  • 10
  • 24
  • 1
    add `self.textbox.show()` and `self.button.show()` in the final part of the `home()` function – eyllanesc Feb 27 '19 at 05:24
  • @eyllanesc but why does it work when I put in the __init__? – DuttaA Feb 27 '19 at 05:30
  • In my answer to the duplicate question, I clearly explained the reason why it works in one case and not in another: *Widgets when they are visible for the first time call to be visible to their children, but since you are creating it afterwards they probably are not calling that method*, – eyllanesc Feb 27 '19 at 05:35
  • [cont.] So in the case that home is called in the `__init__` the window has not yet been shown so in an instant the show method of the children in the window will be called between them button and textbox, instead in the slot and the window is visible so the window will not call the show method of your children. The idea is not to waste resources unnecessarily – eyllanesc Feb 27 '19 at 05:35
  • In conclusion: if a widget is the child of a window before it is displayed then when the window will show how much it is displayed, but if you add a child to the window after showing it, it will not. – eyllanesc Feb 27 '19 at 05:37

0 Answers0