gpt4 book ai didi

c++ - 为什么调用另一个对象的析构函数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:39:55 26 4
gpt4 key购买 nike

我的项目创建了一个带有上下文菜单的系统托盘图标。在此菜单中,我可以单击并创建任意数量的便签(如来自 Windows 的便签)。但是,当我关闭最后一个音符(通过单击窗口关闭按钮)时,将调用 destruktor ~Traymenu()。为什么?对象 trayMenu 仍然有一个事件成员,系统托盘图标...同样有趣的是,当我关闭笔记窗口时,析构函数 Note::~Note() 永远不会被调用。

主要.cpp:

#include "note.h"
#include "traymenu.h"
#include <QApplication>

int main(int argc, char *argv[]){
QApplication a(argc, argv);
Traymenu trayMenu;
return a.exec();
}

托盘菜单.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

托盘菜单.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);
}

最佳答案

默认情况下,Qt 主事件循环会在最后一个窗口关闭时退出,默认值为 QApplication property quitOnLastWindowClosed

因此,在创建应用程序实例后,将其设置为 false,例如:

QApplication a;
a.setQuitOnLastWindowClosed(false);

关于c++ - 为什么调用另一个对象的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21763852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com