0

i didnt understood why this code doesn't work

import sys
from threading import Thread

from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My App")
        self.setFixedSize(QSize(400, 300))

        Thread(target=self.AddButton).start()
        #self.AddButton()

    def AddButton(self):
        button = QPushButton("Press Me!",self)
        print("Ok")


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

and someone told me that i have to use signals because i cant modify the UI from external threads so i made this exemple but it still didnt work

class WorkerSignals(QObject):
    starting = pyqtSignal()


class Worker(QRunnable):
    def __init__(self):
        super(Worker, self).__init__()
        self.signals = WorkerSignals()

    @pyqtSlot()
    def run(self):
        self.signals.starting.emit()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My App")
        self.setFixedSize(QSize(400, 300))

        self.threadpool = QThreadPool()
        worker = Worker()
        worker.signals.starting.connect(self.makebutton)
        self.threadpool.start(worker)

    def makebutton(self):
        button = QPushButton("Press Me!", self)
        print("gad")

if some one can help it will be lovely

Gad
  • 154
  • 8
  • You cannot modify the UI from external threads, as UI elements are *not* thread safe. If you want to communicate between other threads and the main UI thread (which is the *only one* that can access the UI), you must use signals. – musicamante Dec 21 '21 at 13:06
  • Do you have any simple code of that? I will be really happy :) Thanks – Gad Dec 21 '21 at 13:14
  • 1
    Do some research on the topic, as there are literally hundreds of questions about it. – musicamante Dec 21 '21 at 13:22

0 Answers0