Qt QSystemTrayIcon,打开除主窗口以外的其他对话框关闭应用程序
正如标题所说,如果我制作了一个systemtray图标,其中有一个打开其他对话框(如首选项)的选项,当我关闭这个其他对话框时,当我调用时,整个应用程序都会关闭 这个>关闭();从使用该首选项对话框。 以以下代码为例: main.cpp:Qt QSystemTrayIcon,打开除主窗口以外的其他对话框关闭应用程序,qt,indicator,tray,Qt,Indicator,Tray,正如标题所说,如果我制作了一个systemtray图标,其中有一个打开其他对话框(如首选项)的选项,当我关闭这个其他对话框时,当我调用时,整个应用程序都会关闭 这个>关闭();从使用该首选项对话框。 以以下代码为例: main.cpp: #include <QtGui/QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv);
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSystemTrayIcon>
#include "preferences.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void show_me();
void quit_me();
void showpref();
private:
Ui::MainWindow *ui;
QSystemTrayIcon *trayIcon;
QAction *Show_action;
QAction *Preferences_action;
QAction *Quit_action;
Preferences *pref;
};
#endif // MAINWINDOW_H
h:
#ifndef PREFERENCES_H
#define PREFERENCES_H
#include <QDialog>
namespace Ui {
class Preferences;
}
class Preferences : public QDialog
{
Q_OBJECT
public:
explicit Preferences(QWidget *parent = 0);
~Preferences();
private slots:
void on_pushButton_clicked();
private:
Ui::Preferences *ui;
};
#endif // PREFERENCES_H
谢谢你的帮助 做一个小测试,打开主窗口,不要关闭它。打开首选项窗口并关闭它。您的应用程序不应该以这种方式退出。现在关闭主窗口,应用程序将退出。这是因为QApplication属性“quitOnLastWindowClosed”默认设置为true。你应该打电话
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(false);
MainWindow w;
w.show();
return a.exec();
}
还请注意,每次要显示首选项时,在创建首选项的新实例时,都会从主窗口泄漏内存。你可以这样做:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
pref(NULL)
{
// snap, your code goes here
}
void MainWindow::showpref(){
if( ! pref )
pref=new Preferences(this);
pref->exec();
}
它是关上了还是撞坏了?您是否通过调试器运行过它。但是用户没有关闭主窗口-它被隐藏。它没有显示,因此没有留下任何窗口(可见),因此这是最后一个关闭的窗口。如果是这样的话,是否只是最小化窗口关闭它?隐藏会使窗口不可见,并且无法从窗口管理器访问。要最小化窗口,您需要调用showmimized(注意它仍然是“show”),好了,就是这样:)(QapApplication::SetQuitOnllastWindowClosed(bool))
qmake -project
qmake *.pro
qmake
make
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(false);
MainWindow w;
w.show();
return a.exec();
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
pref(NULL)
{
// snap, your code goes here
}
void MainWindow::showpref(){
if( ! pref )
pref=new Preferences(this);
pref->exec();
}