第四十三課、發送自定義事件(上)------------------狄泰軟件學院

1、在程序中發送事件

一、Qt能夠在程序中自主發送事件編輯器

(1)、堵塞型事件發送函數

A、事件發送完後須要等待事件處理完成post

(2)、非堵塞型事件發送this

A、事件發送後當即返回spa

B、事件被髮送到事件隊列中等待處理指針

二、QApplication類提供了支持事件發送的靜態成員函數code

三、注意事項對象

(1)、sendEvent中事件對象生命期由Qt程序管理blog

A、同時支持棧事件對象和堆事件對象的發送生命週期

(2)、postEvent中事件對象的生命週期由Qt平臺管理

A、只能發送堆事件對象

B、事件被處理後由Qt平臺銷燬

四、事件發送過程

 兩種方式比較

#include "Widget.h"
#include <QMouseEvent>
#include <QApplication>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    m_pushButton.setParent(this);
    m_pushButton.setText("Test");

    connect(&m_pushButton, SIGNAL(clicked()), this, SLOT(onButtonClicked()));
}

void Widget::onButtonClicked()
{

    qDebug() << "void Widget::onButtonClicked()";
    testSendEvent();
    // testPostEvent();

}

void Widget::testSendEvent()
{
    //建立一個鼠標左鍵雙擊事件對象:
    //參數type:QEvent::MouseButtonPress, QEvent::MouseButtonRelease,QEvent::MouseButtonDblClick, or QEvent::MouseMove之一
    //參數position:鼠標指針相對於接收窗口的位置
    //參數button:左鍵、右鍵等發生的事件。若是是mouseMove事件,則爲Qt::NoButton
    //參數buttons和modifiers:當事件發生時鼠標和鍵盤的狀態位
    QMouseEvent dbcEvt(QEvent::MouseButtonDblClick, QPoint(0, 0),Qt::LeftButton,
                       Qt::NoButton,Qt::NoModifier);//dbcEvt:double clicked event

    qDebug() << "Before sendEvent()";

    QApplication::sendEvent(this, &dbcEvt);//至關於直接調用Widget::event();

    qDebug() << "After sendEvent";

}

void Widget::testPostEvent()
{
    //postEvent必須發送一個堆對象
    QMouseEvent*  dbcEvt = new QMouseEvent(QEvent::MouseButtonDblClick, QPoint(0, 0),Qt::LeftButton, Qt::NoButton,Qt::NoModifier);//dbcEvt:double clicked event

    qDebug() << "Before postEvent()";

    //postEvent之後,事件對象的生命期由消息隊列來自行負責管理
    QApplication::postEvent(this, dbcEvt);//當即返回

    qDebug() << "After postEvent";
}

bool Widget::event(QEvent *evt)
{
    if(evt->type() == QEvent::MouseButtonDblClick)
    {
        qDebug() << "event(): " << evt;
    }
    return QWidget::event(evt);
}

Widget::~Widget()
{
}

兩種方式比較

2、文本編輯器中的事件發送

一、菜單欄中刪除功能的實現

(1)、自定義事件對象KeyPress

(2)、自定義事件對象KeyRelease

(3)、發送事件KeyPress

(4)、發送事件KeyRelease

文本編輯器程序:

 onFileDelete()和onFileExit()的實現

void MainWindow::onFileDelete()
{
    QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Delete,Qt::NoModifier);
    QKeyEvent keyRelease(QEvent::KeyRelease, Qt::Key_Delete,Qt::NoModifier);

    QApplication::sendEvent(&mainEdit, &keyPress);//發送事件模擬鍵盤的delete鍵
    QApplication::sendEvent(&mainEdit, &keyRelease);

}
void MainWindow::onFileExit()
{
    close();
}

onFileDelete()和onFileExit()的實現

3、小結

(1)、Qt程序中可以自主地發送系統預約義的事件(系統中存在的事件)

(2)、QApplication類提供了支持事件發送的靜態成員函數

(3)、sendEvent發送事件後須要等待事件處理完成

(4)、postEvent發送事件後當即返回

相關文章
相關標籤/搜索