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();
}

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