目标效果:一个提示信息框,创建后显示提示信息,一定时间后自动消失,不阻塞原来窗口。
思路: 自定义一个控件,继承自QWidget,构造时设置定时器,时间到则自我销毁。


1593846831326.gif
### 实现代码
代码一共两个文件,.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);
        //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(){
        delete this;
    }
private:
    Ui::ReminderWidget 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();
}

君的名字
4 声望2 粉丝

Life is that.


引用和评论

0 条评论