Qt最小化到托盘、恢复并置顶

Qt最小化到托盘、恢复并置顶

在window.h文件中添加如下内容:
//window.h
    QSystemTrayIcon *trayicon;
    QMenu *trayiconMenu;

//托盘点击处理槽函数

private slots:
    void onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason reason);

在window.cpp文件中添加如下内容,在构造函数中对添加的两个变量进行初始化添加托盘图标,链接槽函数,其中槽函数用于响应在托盘图标及托盘菜单上的鼠标点击操作:
//window.cpp
    trayicon = new QSystemTrayIcon(this);
    connect(trayicon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason)));
    QIcon icon("MyICO.ico");
    trayicon->setIcon(icon);
    trayicon->show();

//最小化处理
void Window::changeEvent(QEvent *e)
{
    if((e->type()==QEvent::WindowStateChange)&&this->isMinimized())
    {
        this->hide();
//        QTimer::singleShot(100, this, SLOT(close()));
    }
}

//实现槽函数
void BluetoothSMS::onSystemTrayIconClicked(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    //单击
    case QSystemTrayIcon::Trigger:
        //双击
    case QSystemTrayIcon::DoubleClick:
        if(this->isHidden())
        {
            //恢复窗口显示
            this->show();
            //一下两句缺一均不能有效将窗口置顶
            this->setWindowState(Qt::WindowActive);
            this->activateWindow();
 
  
            ui->MsgText->setFocus();
        }
        else
        {
            this->hide();
        }
        break;
    default:
        break;
    }
}

你可能感兴趣的:(置顶,托盘,顶层,活动窗口.)