重写QPushButton,实现长按按钮3秒触发事件

头文件:

public:
	void mousePressEvent(QMouseEvent *e); //按压
	void mouseReleaseEvent(QMouseEvent *e);
private:
    QTimer *timer;

    int m_Num = 0;

private slots:
    void onTime();

signals:
    void sig_Stop();    //发送停止信号
	

源文件:

	timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&MyStopBtn::onTime);
//重写QPushButtom按压事件
void MyStopBtn::mousePressEvent(QMouseEvent *e)
{
    Q_UNUSED(e);
    timer->start(1000);
}

void MyStopBtn::mouseReleaseEvent(QMouseEvent *e)
{
    Q_UNUSED(e);
    m_Num = 0;
    timer->stop();
}

void MyStopBtn::onTime()
{
    m_Num++;
    //按压时间达到3秒
    if( 3 == m_Num )
    {
        timer->stop();
        m_Num = 0;
        emit sig_Stop();
    }
}

你可能感兴趣的:(QT,qt)