目录
引言
Push Button部件本身长按并没有如何效果,本文通过QTimer类和QMenu类简易实现了Push Button部件的长按效果
1.创建一个新类继承自QPushButton类
其中,新类中包含有自己的构造函数LongPressButton ,还有继承自基类QPushButton的事件过滤器函数eventFilter函数,以及一个自己撰写的显示上下文菜单的函数showContextMenu,最后,还有两个私有成员变量,计时器变量与显示菜单项变量
class LongPressButton : public QPushButton {
Q_OBJECT
public:
LongPressButton(QWidget *parent = nullptr);
protected:
//事件过滤器函数
bool eventFilter(QObject *obj, QEvent *event);
//显示上下文菜单函数
void showContextMenu();
private:
//用于检测长按事件的计时器
QTimer *longPressTimer;
//用于显示上下文菜单的菜单对象
QMenu *menu;
};
2.LongPressButton类构造函数
用于初始化LongPressButton对象
2.1 连接长按与定时器超时信号
//连接长按与定时器超时信号
connect(longPressTimer, &QTimer::timeout, this, &LongPressButton::showContextMenu);
longPressTimer->setInterval(500); // 500ms后认为是长按
2.2 安装事件过滤器
//安装事件过滤器
this->installEventFilter(this);
2.3 初始化菜单栏和选项
//初始化菜单栏和选项
menu = new QMenu(this);
QAction *action1 = new QAction(this);
QAction *action2 = new QAction(this);
action1->setText("选项1");
action2->setText("选项2");
2.4 将选项添加到菜单栏中
//将选项添加到菜单栏中去
menu->addAction(action1);
menu->addAction(action2);
connect(menu, &QMenu::triggered, this, [=](QAction *action) {
qDebug() << "选中了:" << action->text();
});
2.5 整体代码
LongPressButton::LongPressButton(QWidget *parent) : QPushButton(parent), longPressTimer(new QTimer(this)) {
//连接长按与定时器超时信号
connect(longPressTimer, &QTimer::timeout, this, &LongPressButton::showContextMenu);
longPressTimer->setInterval(500); // 500ms后认为是长按
//安装事件过滤器
this->installEventFilter(this);
//初始化菜单栏和选项
menu = new QMenu(this);
QAction *action1 = new QAction(this);
QAction *action2 = new QAction(this);
action1->setText("选项1");
action2->setText("选项2");
//将选项添加到菜单栏中去
menu->addAction(action1);
menu->addAction(action2);
connect(menu, &QMenu::triggered, this, [=](QAction *action) {
qDebug() << "选中了:" << action->text();
});
}
3.事件过滤器函数
事件过滤器中去识别鼠标的点击与长按信号,对不同的信号做出不同的操作。
bool LongPressButton::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::MouseButtonPress && obj == this) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::LeftButton) {
longPressTimer->start();//启动定时器
return true;
}
} else if (event->type() == QEvent::MouseButtonRelease && obj == this) {
longPressTimer->stop();
// 这里处理普通的点击事件
qDebug() << "点击";
}
return QPushButton::eventFilter(obj, event);
}
4.显示上下文菜单函数
void LongPressButton::showContextMenu() {
longPressTimer->stop();
menu->exec(QCursor::pos()); // 在鼠标当前位置显示菜单
}
5.运行效果
选中选项以及点击之后LongPressButton的qDebug()的输出: