0

I am trying to create a UI with two buttons: the first one (on the left) waits for 5 seconds and the second one prints a sentence. I want the second button to work also when the first button is clicked without having to wait for 5 seconds.

When I run the following code and click on the first button nothing happens. How can I make it work?

from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
import time

class Button1Clicked(QThread):
    def __init__(self):
        super().__init__()

    def run(self):
        print('start...')
        time.sleep(5)
        print('...finish')


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

    def initializeUI(self):
        self.setWindowTitle('Example')
        self.setGeometry(100,100,400,600)
        self.displayButtons()
        self.show()

    def displayButtons(self):
        button1 = QPushButton('Sth', self)
        thread1 = Button1Clicked()
        button1.clicked.connect(thread1.start)
        button1.move(100, 100)

        button2 = QPushButton('Sth else', self)
        button2.clicked.connect(self.button2Clicked)
        button2.move(200, 100)


    def button2Clicked(self):
        print('Hello world!')

if __name__ == '__main__':
    app = QApplication([])
    window = Window()
    app.exec()
Andrea
  • 81
  • 5
  • The `thread` is garbage collected (destroyed) when `displayButtons` returns. Change to `self.thread1 = Button1Clicked()` and `button1.clicked.connect(self.thread1.start)` – musicamante Sep 03 '21 at 10:26

0 Answers0