我的项目创建了一个带有上下文菜单的系统托盘图标。在这个菜单中,我可以点击并根据需要创建尽可能多的笔记(如窗口中的便签)。但是,当我关闭我的最后一个音符时(通过点击窗口关闭按钮),会调用destruktor ~Traymenu()
。为什么?对象trayMenu
仍然有一个活动成员,系统托盘图标......
同样有趣的是,当我关闭一个音符窗口时,永远不会调用析构函数Note::~Note()
。
main.cpp中:
#include "note.h"
#include "traymenu.h"
#include <QApplication>
int main(int argc, char *argv[]){
QApplication a(argc, argv);
Traymenu trayMenu;
return a.exec();
}
traymenu.h:
#ifndef TRAYMENU_H
#define TRAYMENU_H
#include <QSystemTrayIcon>
#include <QIcon>
#include <QPixmap>
#include <QMenu>
class Note;
class Traymenu : public QSystemTrayIcon
{
public:
Traymenu();
~Traymenu();
void createMainContextMenu();
void newNote();
void exitProgram();
private:
QSystemTrayIcon mainIcon;
QMenu mainContextMenu;
std::vector<Note *> noteList;
};
#endif // TRAYMENU_H
traymenu.cpp:
#include "traymenu.h"
#include "note.h"
#include <QDebug>
Traymenu::Traymenu(){
mainIcon.setIcon(QIcon(QPixmap("C:\\program.png")));
mainIcon.setVisible(true);
mainIcon.show();
createMainContextMenu();
}
Traymenu::~Traymenu(){
qDebug() << "in ~Traymenu()" << endl;
}
void Traymenu::newNote(){
Note *nN; //new pointer to object of class Note
nN = new Note(); //Initialize pointer
noteList.push_back(nN); //add newly created object to a list
}
void Traymenu::exitProgram(){
//delete this; //deletes traymenu object (icon disappears)
}
void Traymenu::createMainContextMenu(){
QAction *actionNewNote = mainContextMenu.addAction("Neue Notiz");
mainContextMenu.addSeparator();
QAction *actionExitProgram = mainContextMenu.addAction("Programm beenden");
actionNewNote->setIcon(QIcon("C:\\new.ico"));
actionNewNote->setIconVisibleInMenu(true);
QObject::connect(actionNewNote,&QAction::triggered,this,&Traymenu::newNote);
QObject::connect(actionExitProgram,&QAction::triggered,this,&Traymenu::exitProgram);
mainIcon.setContextMenu(&mainContextMenu);
}
答案 0 :(得分:1)
默认情况下,Qt主事件循环在最后一个窗口关闭时退出,默认值为QApplication
property quitOnLastWindowClosed
因此,在创建应用程序实例后,将其设置为false,如:
QApplication a;
a.setQuitOnLastWindowClosed(false);