user2366975
user2366975

Reputation: 4700

Why is the destructor of another object called?

My project creates a system tray icon that has a context menu. In this menu, I can click on and create as many notes (like those sticky notes from windows) as I want. However, when I closed my last note (by clicking on the window close button) the destruktor ~Traymenu() is called. Why? The object trayMenu still has an active member, the systray icon... And what is also interesting, is that the destructor Note::~Note() is never called when I close a note window.

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);
}

Upvotes: 1

Views: 107

Answers (1)

hyde
hyde

Reputation: 62777

By default, Qt main event loop exits when last window is closed, as per default value of QApplication property quitOnLastWindowClosed

So, after creating the application instance, set that to false, something like:

QApplication a;
a.setQuitOnLastWindowClosed(false);

Upvotes: 1

Related Questions