-4

Look There Are My Qwidget Object And If I Am Working This Object On Main Thread No Problem Qwidget .show is Working but If I Run On Other Thread(threading.Thread) program freezes and shuts down.

WHAT CAN I DO ?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Using `QWidget`s on any thread other than the thread on which `main` is running is not supported. – G.M. Mar 19 '21 at 18:33
  • Access (including creation) of QWidgets outside the main thread is strictly forbidden and generally leads to fatal crash. Use QThreads and signals/slots to correctly interact from an external thread. Do some research, as there are literally hundreds of posts about this topic. Also, please read [how to ask](https://stackoverflow.com/help/how-to-ask) good questions and avoid unnecessary formatting (including bold text and capitalized words). – musicamante Mar 19 '21 at 18:35
  • OK I got it What Can I Do In This Situation? – Eyyüp Ensar Özcan Mar 19 '21 at 18:37
  • As said, do some research about using QThreads and signals. – musicamante Mar 19 '21 at 18:42
  • As a general comment, this is true of EVERY windowing system. Win32, X, Qt, Gtk, MacOS, wx, etc. They all require that UI interactions take place on the main thread. – Tim Roberts Mar 19 '21 at 18:46
  • Thank You So Much !!! QThread is Solved My Problem - I Called QWidget.show() On QThread Function Thats It ☻ – Eyyüp Ensar Özcan Mar 19 '21 at 18:50
  • @EyyüpEnsarÖzcan Are you saying that you're actually calling `show()` from within the QThread? If that's so, you've not understood what I said: **NO ACCESS** is allowed to **ANY** QWidget from **ANY** other thread, and that obviously includes calling `show()`. A QThread should know *nothing* about anything related to a QWidget. If your code works, it's just for *luck*, and be aware that sooner or later your program is going to crash. You *must* create signals and emit them, any other attempt is considered bad practice and is destined to fail. – musicamante Mar 19 '21 at 19:13
  • I keep the program open for 12 hours but it is not a problem – Eyyüp Ensar Özcan Mar 26 '21 at 18:51

1 Answers1

0

In a word: don’t do it. It doesn’t even have to do with threads, everything to do with separation of the UI and the “business” logic.

  1. Put the code that you had running in a thread into a QObject.

  2. Have that object emit signals and provide slots for interaction with UI. It should not be aware of any UI objects at all.

  3. Connect that object to the UI object using signal/slot connections.

  4. Move the object to another thread.

  5. Start the thread.

And you’ve totally avoided the problem now. But make sure that the business logic object never knows about any UI objects: it can’t directly interact with them, since it’ll be in the wrong thread and it won’t be appropriately decoupled from the UI.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313