-
需求:
- 一个弹出窗口,当接收到通知的时候全局弹出;
- 点击窗口,自动跳转进日志管理;
-
分析:
- 全局静态变量,随时调用,计时器结束后自动隐藏;
-
实现:
- 主界面为
MainWindow
,子界面为Dialog - 基于主窗口确定子窗口位置;
- 计时器计时显示时间
- 主界面为
-
项目结构
-
注意:子界面应为Dialog,设置为其parent为mainwindow
-
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "msg1.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void initMsg();
void showMsg(QString title, QString text);
void testMsg();
private:
Ui::MainWindow *ui;
msg1 *my_msg1 = nullptr;
};
#endif // MAINWINDOW_H
- mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDesktopWidget>
#include <QTimer>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QDesktopWidget *desktop = QApplication::desktop();
int screenWidth = desktop->width();
int screenHeight = desktop->height();
setGeometry((screenWidth-1024)/2,(screenHeight-768)/2,1024,768);
initMsg();
showMsg("提示","软件启动");
testMsg();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initMsg()
{
my_msg1 = new msg1(this);
QDesktopWidget *desktop = QApplication::desktop();
int screenWidth = desktop->width();
int screenHeight = desktop->height();
my_msg1->setGeometry((screenWidth-1024)/2+337,(screenHeight-768)/2,350,100);
}
void MainWindow::showMsg(QString title, QString text)
{
QTimer *timer = new QTimer(this);
my_msg1->setMsg(title,text);
my_msg1->show();
timer->start(3000);
connect(timer, &QTimer::timeout, this, [=](){
timer->stop();
my_msg1->hide();
});
}
void MainWindow::testMsg()
{
QTimer *timer2 = new QTimer(this);
timer2->start(5000);
connect(timer2, &QTimer::timeout, this, [=](){
showMsg("测试","测试提示窗口。。。");
timer2->stop();
});
}
- msg1.h
#ifndef MSG1_H
#define MSG1_H
#include <QDialog>
namespace Ui {
class msg1;
}
class msg1 : public QDialog
{
Q_OBJECT
public:
explicit msg1(QWidget *parent = nullptr);
~msg1();
void setMsg(QString title, QString text);
private:
Ui::msg1 *ui;
};
#endif // MSG1_H
- msg1.cpp
#include "msg1.h"
#include "ui_msg1.h"
msg1::msg1(QWidget *parent) :
QDialog(parent),
ui(new Ui::msg1)
{
ui->setupUi(this);
this->setWindowFlags(windowFlags()|Qt::FramelessWindowHint );
}
msg1::~msg1()
{
delete ui;
}
void msg1::setMsg(QString title, QString text)
{
ui->labelTitle->setText(title);
ui->labelText->setText(text);
}
- 运行截图
- Qt练习时长两年半,欢迎讨论;
- VX:QAQ2333oooo
- QQ:1580947517