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


目标效果:一个提示信息框,创建后显示提示信息,一定时间后自动消失,不阻塞原来窗口。
思路: 自定义一个控件,继承自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();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章