头文件
class MyAutoCloseFrameBase : public QFrame
{
Q_OBJECT
public:
MyAutoCloseFrameBase(QWidget *parent,int keeptime = 2000);//msec
~MyAutoCloseFrameBase();
void resetAutoClock(bool isable = true);
void SetLabelText(QString text);
protected:
bool event(QEvent *e);
void paintEvent(QPaintEvent *ev);
private:
QTimer* m_pTimer;
int m_keeptime;
QVBoxLayout* m_QVBoxLayout;
QLabel* m_label;
};
cpp文件
#include "MyAutoCloseFrameBase.h"
MyAutoCloseFrameBase::MyAutoCloseFrameBase(QWidget *parent,int keeptime)
: QFrame(parent)
, m_keeptime(keeptime)
{
setWindowFlags( Qt::FramelessWindowHint|Qt::Tool);
setAttribute(Qt::WA_TranslucentBackground);
//设置为Qt::Tool属性才可以让透明窗口浮动在上方,并且不阻塞信号
//设置为Qt::Dialog属性会阻塞事件,导致快捷键不可用
m_pTimer = new QTimer(this);
m_pTimer->setSingleShot(true);//start once timeout once
m_pTimer->setInterval(m_keeptime);
connect(m_pTimer, SIGNAL(timeout()),this,SLOT(hide()));
//设置定时器自动隐藏
m_label = new QLabel(this);
m_label->setAlignment(Qt::AlignCenter);
m_QVBoxLayout = new QVBoxLayout(this);
m_QVBoxLayout->setContentsMargins(12, 9, 12, 9);
m_QVBoxLayout->setSpacing(0);
m_QVBoxLayout->addWidget(m_label);
setLayout(m_QVBoxLayout);
}
MyAutoCloseFrameBase::~MyAutoCloseFrameBase()
{
}
void MyAutoCloseFrameBase::resetAutoClock(bool isable)
{
m_pTimer->start(m_keeptime);
}
bool MyAutoCloseFrameBase::event(QEvent* e)
{
if (e->type() == QEvent::HoverMove)
{
resetAutoClock(false);
}
if (e->type() == QEvent::Show)
{
m_pTimer->start();
return false;
}
return QFrame::event(e);
}
void MyAutoCloseFrameBase::SetLabelText(QString text)
{
m_label->setText(text);
}
void MyAutoCloseFrameBase::paintEvent(QPaintEvent*ev)
{
QPainter p(this);
p.setPen(Qt::NoPen);
/*透明背景*/
p.setBrush(QBrush(QColor(0, 0, 0, 0)));
p.drawRect(rect());
p.setRenderHint(QPainter::Antialiasing);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
/*圆角矩形背景*/
p.setBrush(QBrush(QColor(75,88,94,255)));
p.drawRoundedRect(0, 0, width() - 1, height() - 1, 6 * g_dscale, 6 * g_dscale);
/*边框*/
p.setPen(QColor(38, 49, 55, 255));
p.drawRoundedRect(0, 0, width() - 1, height() - 1, 6 * g_dscale, 6 * g_dscale);
}