實現(xiàn)思路:利用事件過濾器實現(xiàn)按鈕雙擊功能,主要是通過調(diào)用installEventFilter函數(shù)和重寫事件eventFilter函數(shù)實現(xiàn)。
?文章來源地址http://www.zghlxwxcb.cn/news/detail-659865.html
1、創(chuàng)建項目
啟動Qt Creator,在主菜單的[文件]下,打開[新建文件或項目]菜單,彈出新建文件或項目對話框,創(chuàng)建Qt Widgets Application 項目,在Class Information步驟中Base class 選擇Qwidget,其他基本默認即可。
在界面增加1個列表控件和1個按鈕控件,為按鈕添加單機事件,界面設(shè)計如上所示。
?文章來源:http://www.zghlxwxcb.cn/news/detail-659865.html
2、代碼
widget.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>565</width>
<height>424</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
<widget class="QPushButton" name="btnDoubleTest">
<property name="geometry">
<rect>
<x>430</x>
<y>20</y>
<width>101</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>測試按鈕</string>
</property>
</widget>
<widget class="QListWidget" name="listWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>401</width>
<height>401</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
bool eventFilter(QObject *watched, QEvent *event);
private slots:
void on_btnDoubleTest_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "./ui_widget.h"
#include <QMouseEvent>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->btnDoubleTest->installEventFilter(this);
}
Widget::~Widget()
{
delete ui;
}
bool Widget::eventFilter(QObject *watched, QEvent * event)
{
if(event->type()==QEvent::MouseButtonDblClick)
{
QMouseEvent * e = static_cast<QMouseEvent *>(event);
if(e->button() == Qt::LeftButton)
{
if(watched==ui->btnDoubleTest)
ui->listWidget->addItem(QString("雙擊事件"));
return true;
}
}
return QWidget::eventFilter(watched, event);
}
void Widget::on_btnDoubleTest_clicked()
{
ui->listWidget->addItem(QString("單擊事件"));
}
?
3、運行效果
運行效果如上所示,單擊按鈕時觸發(fā)單擊事件,雙擊按鈕時觸發(fā)雙擊事件。
?
?
?
?
?
?
?
?
?
?
?
?
到了這里,關(guān)于QT6實現(xiàn)按鈕雙擊事件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!