0

I am making an addressbook on PyQt5 and can't make the window be shown completely because it is shown only once.

I know that the problem occurs because I am trying to initiate the class when the button is clicked, but it's the only way I've came up with to uptade the QLabel text, otherwise the window will be shown without any text on it.

Here is some code:

from PyQt5 import QtWidgets
class Window(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.resize(400,200)
        self.show()
        self.text = ''
        self.button = QtWidgets.QPushButton('Show')
        self.box = QtWidgets.QVBoxLayout()
        self.box.addWidget(self.button)
        self.setLayout(self.box)
        self.button.clicked.connect(self.init)

    def init(self):
        self.text = 'Text'
        win2 = AppearWindow()
        win2.show()

class AppearWindow(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.resize(100, 50)
        self.label = QtWidgets.QLabel()
        self.label.setText(win.text)
        self.box = QtWidgets.QVBoxLayout()
        self.box.addWidget(self.label)
        self.setLayout(self.box)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    win = Window()
    sys.exit(app.exec_())

How can I make AppearWindow be shown if I want the QLabel text on it be updated when the button on the main window is clicked?

Tymofii Koval
  • 153
  • 1
  • 8

1 Answers1

1

Try it:

from PyQt5 import QtWidgets
import random

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.text = ''
        self.button = QtWidgets.QPushButton('Show')
        self.button.clicked.connect(self.init)

        self.box = QtWidgets.QVBoxLayout()
        self.box.addWidget(self.button)
        self.setLayout(self.box)

    def init(self):
        self.text = random.choice(['Text1', 'Text2', 'Text3'])
        self.win2 = AppearWindow(self.text)                         # + self

        self.win2.show()                                            # + self

class AppearWindow(QtWidgets.QWidget):
    def __init__(self, text):
        QtWidgets.QWidget.__init__(self)

        self.resize(100, 50)
        self.label = QtWidgets.QLabel()

#        self.label.setText(win.text)
        self.label.setText(text)

        self.box = QtWidgets.QVBoxLayout()
        self.box.addWidget(self.label)
        self.setLayout(self.box)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    win = Window()
    win.resize(400,200)
    win.show()
    sys.exit(app.exec_())

enter image description here

S. Nick
  • 12,879
  • 8
  • 25
  • 33