PDA

View Full Version : program exit itself when create dialog with QSystemTrayIcon



jim2212001
26th July 2010, 09:40
Hi,

I'm using QT creator in WINDOWS7

My program will exit itself when my MainWindow is hidden and I closed the messagebox created by the system tray icon.

main.cpp


int main(int argc, char* argv[]){
QApplication app(argc, argv);

MainWindow *dialog = new MainWindow;

return app.exec();
}


mainwindow.h


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setupUi(this);

createActions();
createTrayIcon();

connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason )), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReas on)));

trayIcon->show();

showMessage();

}

void MainWindow::createActions(){
aboutAction = new QAction(tr("&About"), this);
connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));

quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void MainWindow::createTrayIcon(){
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(aboutAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);

trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
}

void MainWindow::showAbout(){
QMessageBox::about(this, tr("Foo"), tr("Bar"));
}

...


My program is designed not to have the mainwindow.
Every time I pressed "OK" or "X" on the about dialog, my program exited(with code 0.)

But I want my program to keep running in the background.

Thanks for help,
Jimmy

wladek
27th July 2010, 12:52
Hi Jimmy,

Try the following:


int main(int argc, char* argv[]){
QApplication app(argc, argv);
QApplication::setQuitOnLastWindowClosed(false);

MainWindow *dialog = new MainWindow;

return app.exec();
}

hakermania
27th August 2010, 11:35
Thanks for this reply, but if you only add this, then your app doesn't exits at all!
You have to add QApplication::setQuitOnLastWindowClosed(1); at the CloseEvent :)
Anyway thx for the reply, very helpful!;)