深入Qt--类似安卓Toast提示框

深入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);
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值