深入Qt–类似安卓Toast提示框
在开发安卓应用中经常点击按键的时候下方中间位置提示带文字的提示框。Qt同样也可以做到。
头文件 toastdialog.h
#ifndef TOASTDIALOG_H
#define TOASTDIALOG_H
#include <QDialog>
#include <QLabel>
#include <QTimer>
class Toast : public QDialog
{
Q_OBJECT
public:
explicit Toast(int x, int y, QString str, QWidget *parent = 0, int ms = -1);
~Toast();
protected:
bool eventFilter(QObject *obj, QEvent *e);
private slots:
void onTimeout();
private:
QLabel* m_Label; // 显示内容
QTimer* m_Timer; // count down定时器
};
#endif // TOASTDIALOG_H
源文件 toastdialog.cpp
#include <QCoreApplication>
#include <QVBoxLayout>
#include <QDesktopWidget>
#include "toastdialog.h"
Toast::Toast(int x, int y, QString str, QWidget *parent, int ms) : QDialog(parent)
{
this->setWindowFlags(Qt::FramelessWindowHint);
// this->setAttribute(Qt::WA_DeleteOnClose, true);
QDesktopWidget desktop;
int nX = x, nY = y;
if(x == -1)
{
int width = desktop.width();
nX = width / 2 - 200;
}
if(y == -1)
{
int height = desktop.height();
nY = height / 2 - 25;
}
setGeometry(nX, nY, 400, 50);
setWindowOpacity(0.1);
this->setStyleSheet("background-color:white;");
m_Label = new QLabel(this);
m_Label->setScaledContents(true);
// m_Label->setWindowOpacity(0.1);
m_Label->setStyleSheet("color:#000000;");
m_Label->setText(str);
m_Label->setAlignment(Qt::AlignCenter);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_Label, Qt::AlignCenter);
this->setLayout(layout);
m_Timer = new QTimer(this);
connect(m_Timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
if(ms <= 0)
{
m_Timer->start(3000);
}
else
{
m_Timer->start(ms);
}
// 绑定按键事件过滤器
qApp->installEventFilter(this);
}
Toast::~Toast()
{
m_Timer->stop();
delete m_Timer;
}
void Toast::onTimeout()
{
m_Timer->stop();
this->close();
}
bool Toast::eventFilter(QObject *obj, QEvent *e)
{
if (e->type() == QEvent::MouseButtonPress)
{
m_Timer->stop();
this->close();
return false;
}
return QWidget::eventFilter(obj, e);
}