天天看点

QT【简单自定义弹出提示框】:非模态,数秒后自动消失

目标效果:一个提示信息框,创建后显示提示信息,一定时间后自动消失,不阻塞原来窗口。

要点整理:

  1. 一定时间后自动销毁。(定时器)
  2. 任务栏上无显示。(Tool属性)
  3. 无边框。(FramelessWindowHint属性)
  4. 处于顶层。(WindowStaysOnTopHint属性)

思路: 自定义一个控件,继承自QWidget,构造时设置定时器,时间到则自我销毁。

QT【简单自定义弹出提示框】:非模态,数秒后自动消失

实现代码

代码一共两个文件,.h/.ui

ReminderWidget.h

#pragma once

#include <QWidget>
#include <QTimer>
#include "ui_ReminderWidget.h"

class ReminderWidget : public QWidget
{
  Q_OBJECT

public:
  ReminderWidget(QString text="",QWidget *parent = Q_NULLPTR): QWidget(parent)
  {
    ui.setupUi(this);
    //设置去掉窗口边框、任务栏无标志、置于顶层
    this->setWindowFlags(Qt::FramelessWindowHint 
      | Qt::Tool 
      | Qt::WindowStaysOnTopHint);
    //设置属性:关闭即销毁
    this->setAttribute(Qt::WA_DeleteOnClose); 
    //text为要显示的信息
    ui.label->setText(text);
    //设置定时器,到时关闭弹框
    QTimer* timer = new QTimer(this);
    timer->start(1500);//时间1.5秒
    timer->setSingleShot(true);//仅触发一次
    connect(timer, SIGNAL(timeout()), this, SLOT(onTimeupDestroy()));
  }
  
  ~ReminderWidget(){}
private slots:
  void onTimeupDestroy(){
    this->close();
  }
private:
  Ui::ReminderWidget ui;
};      
只有一个名为label的QLabel。      
void Reminder::onPushBtn() {
    ReminderWidget* p_widget = new ReminderWidget("提示信息");
    //简单计算一下其显示的坐标
    int x, y;
    x = this->pos().x() + this->width() / 2 - p_widget->width() / 2;
    y = this->pos().y() + 40;
    //设置控件显示的位置
    p_widget->setGeometry(x,y, p_widget->width(),p_widget->height());
    p_widget->show();
}