Qt implementa a bandeja do sistema QSystemTrayIcon

Ambiente de desenvolvimento: ubuntu16.04 + Qt5.6.3

Informações oficiais: https://doc.qt.io/qt-5/desktop-integration.html

QSystemTrayIcon

A classe QSystemTrayIcon fornece um ícone para o aplicativo na bandeja do sistema.

Os sistemas operacionais modernos geralmente oferecem uma área especial na área de trabalho chamada bandeja do sistema ou área de notificação. Os aplicativos de longa duração podem exibir ícones e mensagens curtas.

QDesktopServices

As funções fornecidas pela classe QDesktopServices são usadas para acessar serviços de desktop comuns.

Muitos ambientes de desktop fornecem uma série de serviços que podem executar tarefas comuns por meio de aplicativos. Você pode não apenas abrir um navegador local, mas também pode abrir arquivos locais (pastas), etc., e pode obter diretórios como desktop e Home.


Exemplo

A função principal:

  • Feche a última janela sem sair do programa
  • Exibição do menu da bandeja: sobre, registrar, abrir, sair de quatro menus
  • Sobre: ​​abre a caixa de diálogo sobre
  • Log: Ver log
  • Abrir: abre a interface principal
  • Sair: sai do programa
  • Página principal: Clique no botão de conexão, inicialização, login, etc., e a mensagem da bandeja exibe informações de prompt 

resultado da corrida:

Código fonte:

Estrutura do código:

Ícone ├──

│ ├── about.png

│ ├── icon.png

│ └── RR1582 * 1327.png

├── image.qrc

├── main.cpp

├── mainwindow.cpp

├── mainwindow.h

├── mainwindow.ui

├── MockMiTalk.pro

└── MockMiTalk.pro.user

Código do núcleo:

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDateTime>
#include <QDesktopWidget>
#include <QMessageBox>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("桌面集成C++版本");
    setWindowIcon(QIcon(":/icon/RR1582*1327.png"));

    logAction = new QAction(tr("日志"), this);
    logAction->setIcon(QIcon::fromTheme("document-new"));
    aboutAction = new QAction(tr("关于"), this);
    aboutAction->setIcon(QIcon::fromTheme("help-about"));
    openAction = new QAction(tr("打开"), this);
    openAction->setIcon(QIcon::fromTheme("media-record"));
    quitAction = new QAction(tr("退出"), this);
    quitAction->setIcon(QIcon::fromTheme("application-exit"));  //从系统主题获取图标

    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(aboutAction);
    trayIconMenu->addAction(logAction);

    trayIconMenu->addSeparator();
    trayIconMenu->addAction(openAction);
    trayIconMenu->addAction(quitAction);

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setIcon(QIcon(":/icon/icon.png"));
    trayIcon->setToolTip(QString::fromLocal8Bit("RRRC"));
    trayIcon->show();

    connect(openAction, &QAction::triggered, this, &QWidget::showNormal);
    connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
    connect(aboutAction, SIGNAL(triggered(bool)), this, SLOT(showAbout()));
    connect(logAction, &QAction::triggered, [=](){
          QDesktopServices::openUrl(QUrl(log_path));
    });
    //居中
    QDesktopWidget* desktop = QApplication::desktop();
    int current_screen = desktop->screenNumber(this); //获取程序所在屏幕是第几个屏幕
    QRect rect = desktop->screenGeometry(current_screen); //获取程序所在屏幕的尺寸
    this->move((rect.width() - this->width())/2,(rect.height() - this->height())/2);

    //日志
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString log = currentDateTime.toString("yyyy/MM/dd HH:mm:ss") + "\n";
    log_path = QApplication::applicationDirPath() + "/log.txt";
    QFile file(log_path);
    if (file.open(QFile::WriteOnly)) {
        file.write(log.toUtf8());
        file.close();
    }
}

MainWindow::~MainWindow()
{
    delete ui;

}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (trayIcon->isVisible()) {
        QMessageBox::information(this, tr("系统托盘"),
                                 tr("程序将继续在系统托盘中运行。要终止该程序,请在系统托盘条目的上下文菜单中选择[退出]。"));
        //不退出App
        hide();
        event->ignore();
    }
}

void MainWindow::showAbout()
{
    QMessageBox MB(this);
    MB.setWindowTitle("关于");
    MB.setText("桌面集成C++实现\n\n Copyright © 2020-2020 JUN. \nAll Rights Reserved. ");
    MB.setButtonText (QMessageBox::Ok,QString("确 定"));
    MB.setIconPixmap(QPixmap(":/icon/icon.png"));
    MB.exec();
}


void MainWindow::on_connectBtn_clicked()
{
    showMessage("连接", "已经连接机械手");
}

void MainWindow::on_powerBtn_clicked()
{
    showMessage("上电", "机械手已上电");
}

void MainWindow::on_loginBtn_clicked()
{
    showMessage("权限", "切换权限USER1");
}


void MainWindow::showMessage(QString title, QString content)
{
    //显示消息,1s后自动消失
    //第一个参数是标题
    //第二个参数是消息内容
    //第三个参数图标
    //第四个参数是超时毫秒数
    trayIcon->showMessage(title,content,QSystemTrayIcon::Information,1000);
}

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        QMessageBox::critical(0, QObject::tr("系统托盘"),
                              QObject::tr("本机系统上检测不到任何系统托盘"));
        return 1;
    }
    QApplication::setQuitOnLastWindowClosed(false);  //关闭最后一个窗口不退出程序
    MainWindow w;
    w.show();
//    MainWindow *mainWindow = new MainWindow;
//    Q_UNUSED(mainWindow);
    return a.exec();
}

 

 

 

 

 

Acho que você gosta

Origin blog.csdn.net/qq_40602000/article/details/109275933
Recomendado
Clasificación