Qt中默认的qpushbutton没有longpress事件,当需要相应btn的longpress事件的时候,就需要重载一下qpushbutton的press和release事件。
DycPushButton.h
<pre name="code" class="cpp">#ifndef DYCPUSHBUTTON_H #define DYCPUSHBUTTON_H #include "qpushbutton.h" #include <QTimer> #define TIMERSTART true; #define TIMESTOP false; class DycPushButton:QPushButton { public: DycPushButton(); private: QTimer m_pcPressTimer; int m_nPressTime; bool m_bTimerStart; public : void setLongPressTime(int PressTime); public: bool mousePressEvent(QMouseEvent *event); bool mouseReleaseEvent(QMouseEvent *event); bool mouseDoubleClickEvent(QMouseEvent *event); bool mouseMoveEvent(QMoveEvent *event); signals: onBtnLongPressed(); private slots: onTimeOut(); }; #endif // DYCPUSHBUTTON_H
<span style="font-family: Arial, Helvetica, sans-serif;">DycPushButton.cpp</span>
</pre><pre name="code" class="cpp">#include "DycPushButton.h" DycPushButton::DycPushButton() { m_pcPressTimer = new QTimer(this); m_bTimerStart = TIMESTOP; connect(m_pcPressTimer,SIGNAL(timeout()),this,(onTimeOut())); }
//设置longpress时间 void DycPushButton::setLongPressTime(int PressTime) { if(PressTime) { m_nPressTime = PressTime; } } //btn press时开始计时 bool DycPushButton::mousePressEvent(QMouseEvent *event) { if(m_nPressTime) { m_bTimerStart = TIMERSTART; m_pcPressTimer.start(m_nPressTime); } return mousePressEvent(event); }
//btn release时停止计时
bool DycPushButton::mouseReleaseEvent(QMouseEvent *event) { if(m_bTimerStart) { m_pcPressTimer.stop();
<pre style="margin-top: 0px; margin-bottom: 0px;"><pre name="code" class="cpp"> m_bTimerStart = TIMESTOP; } return mouseReleaseEvent(event); } bool DycPushButton::mouseDoubleClickEvent(QMouseEvent *event) { return mouseDoubleClickEvent(event); } bool DycPushButton::mouseMoveEvent(QMoveEvent *event) { return mouseMoveEvent(event); } //SLOT function is belown void DycPushButton::onTimeOut() { emit onBtnLongPressed(); m_bTimerStart = TIMESTOP; }