creating QT gui using a thread in c++?
I am trying to create this QT gui using a thread but no luck. Below is my code. Problem is gui never shows up.
/*INCLUDES HERE...
....
*/
usin开发者_如何学Gog namespace std;
struct mainStruct {
int s_argc;
char ** s_argv;
};
typedef struct mainStruct mas;
void *guifunc(void * arg);
int main(int argc, char * argv[]) {
mas m;<br>
m.s_argc = argc;
m.s_argv = argv;
pthread_t threadGUI;
//start a new thread for gui
int result = pthread_create(&threadGUI, NULL, guifunc, (void *) &m);
if (result) {
printf("Error creating gui thread");
exit(0);
}
return 0;
}
void *guifunc(void * arg)
{
mas m = *(mas *)arg;
QApplication app(m.s_argc,m.s_argv);
//object instantiation
guiClass *gui = new guiClass();
//show gui
gui->show();
app.exec();
}
There appears to be two major issues here:
- The GUI is not appearing because your
main()
function is completing after creating the thread, thus causing the process to exit straight away. - The GUI should be created on the main thread. Most frameworks require the GUI to be created, modified and executed on the main thread. You spawn threads to do work and send updates to the main thread, not the other way around.
Start with a regular application, based on the Qt sample code. If you use Qt Creator, it can provide a great deal of help and skeleton code to get you started. Then once you have a working GUI, you can start looking at adding worker threads if you need them. But you should do some research on multithreading issues, as there are many pitfalls for the unwary. Have fun!
精彩评论