Solved My Qt Window is crashing while running a C++ loop
-
Hi all, I have developed a qml interface with some buttons. For example my button is:
Button { text: "RUN" onClicked: { my_func.run() } }
And when this is clicked, this will execute a cpp function. And my cpp funtion is:
int my_func::run(){ int counter =0; while(1) { counter++; if(counter>1000000) break; } }
When I clicked the button, after a while my interface is crashing in the background. Why is this happening.
-
@yunus said in My Qt Window is crashing while running a C++ loop:
my interface is crashing in the background
What do you mean by that?
Are you aware that such a loop is blocking your UI as long as it is running? You should not do such things in event driven applications. -
@jsulm Thanks for ur reply. I mean my window's color is changing badly. But if that loop occurs some problem. Cant I run a loop in C++ part?
-
When I added to the loop: Below part simple opencv funtions. This while loop is working fine. I m really wondering why this is working without crashing?
int my_func::run(){ VideoCapture cap(0); Mat frame; while(1) { cap>>frame; imshow("asas",frame); if(waitKey(1)==27){ break; } } }
-
@yunus said in My Qt Window is crashing while running a C++ loop:
I mean my window's color is changing badly
Probably the OS is doing this because it thinks that your app is hanging (what it really does).
Long lasting operations like that should be done in another thread, not UI thread.
Or you use asynchronous (non blocking APIs) APIs like what Qt provides. -
@jsulm okey, I will try to do in another thread. Is this good solution for my problem and is there a simple example about threads since I m new in Qt
-
@yunus
take a look at the detailed description of the Thread class it has a working example in it:
https://doc.qt.io/qt-5/qthread.html#details -
@yunus Also this should be helpful: https://doc.qt.io/qt-5/thread-basics.html
-