Show QWidget or QWindow near QSystemTrayIcon in QT C++

641 views Asked by At

I have managed to get the QSystemTrayIcon visible similar to this:

Assume that the VMWare icon is my QSystemTrayIcon

using the following line of code (with the signal slots working):

#include "dialog.h"
#include "ui_dialog.h"
#include <QMessageBox>
#include <form.h>

Dialog::Dialog(QWidget *parent)
    : QDialog(parent), ui(new Ui::Dialog)
{
    ui->setupUi(this);

    QIcon icon("/Users/JohnnyAppleseed/IMAGE.png");
    m_ptrTrayIcon = new QSystemTrayIcon(icon );
    m_ptrTrayIcon->setToolTip( tr( "Bubble Message" ) );
   // m_ptrTrayIcon->setContextMenu(m_trayIconMenu);
    connect(m_ptrTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                 this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}

Dialog::~Dialog()
{
    delete ui;
}

However, when I try to implement code to show the QWidget/QWindow near the QSystemTrayIcon that I have created, it fails to show up near it. It also shows up and disappears quickly as well (even if I didn't want it near the QSystemTrayIcon) using this code:

void Dialog::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    form fr;
    fr.setWindowFlags(Qt::Popup);

    fr.show();
}

For the sake of being clear, I would like to show my QWidget/QWindow just like VMWare Fusion's approach (or the clock that is found on Microsoft Windows Vista or later...)

Mac OS X / Linux No description

Microsoft Windows enter image description here

Can some one please point out what am I doing wrong? Thanks!

To make things much simpler, download the project: http://zipshare.net/sv

UPDATE #1

Regarding the QWidget/QWindow flicking issue, vahancho advised me to move the form fr; from the void Dialog::iconActivated(QSystemTrayIcon::ActivationReason reason) function to the header of the working window. And it worked successfully all thanks to vahancho. The window now shows up, but its not near the QSystemTrayIcon yet :(

1

There are 1 answers

1
vahancho On BEST ANSWER

The problem is that you create you form object in the stack and it gets deleted as soon as the execution goes out of you iconActivated() slot. That is why it disappears as soon as you see it. To solve the problem you need to create your pop up in the heap.

UPDATE

In order to place you dialog near the tray icon you have to determine the tray icon position. To do that you can use QSystemTrayIcon::geometry() function. You code will look like (adjust the coordinates according to your needs):

QRect rect = m_ptrTrayIcon->geometry();
fr.move(rect.x(), rect.y());
fr.show();