当前位置:网站首页>Send custom events in QT

Send custom events in QT

2022-06-24 08:41:00 litanyuan

background

An event is an interaction between a user and an application , Generated by user operation or within the system , Process events through event loops , Events can also be used to exchange information between objects .

Qt The events in are inherited from QEvent class , By inheritance QEvent Class can implement custom event types .

Subclass QEvent

①..h file

#pragma once
#include <QEvent>
#include <QString>

class CustomEvent : public QEvent
{
    
public:
  CustomEvent(const QString & m_str);
  ~CustomEvent();
public:
  static int type;// Custom event types 
private:
  QString text;// Data carried by the event object 
public:
  QString getEventString() const  {
     return text; }
};

②..cpp file

#include "CustomEvent.h"

int CustomEvent::type = QEvent::registerEventType();// Register custom types 
CustomEvent::CustomEvent(const QString & m_str)
  : QEvent(QEvent::Type(type)), text(m_str)
{
    
}
CustomEvent::~CustomEvent()
{
    
}

Subclass QObject

①..h file

#pragma once

#include <QObject>
#include "QDebug"
#include "qcoreevent.h"

class QtClassDemo : public QObject
{
    
  Q_OBJECT

public:
  QtClassDemo(QObject *parent) : QObject(parent) {
    };
  ~QtClassDemo(){
    
    qDebug() << " ~QtClassDemo" ;
  };
protected:
  bool event(QEvent * event) override;// Event distributor 
private:
  void testFunc(const QString & str);

};

②..cpp file

#include "QtClassDemo.h"
#include "CustomEvent.h"

bool QtClassDemo::event(QEvent * event)
{
    
  qDebug() << event->type();

  if (event->type() == CustomEvent::type)
  {
    
    auto customEvent = static_cast<CustomEvent*>(event);
    testFunc(customEvent->getEventString());

    return true;
  }

  return QObject::event(event);
}

void QtClassDemo::testFunc(const QString & str)
{
    
  qDebug() << this->objectName() << str;
}

Publish custom events

①.sendEvent

After the event is sent, it will block , Until the event is processed ; You can send stack event objects or heap event objects .

②.postEvent

Return immediately after the event is sent without blocking , Events are sent to the event queue for processing ; Only heap event objects can be sent , After the event is handled by Qt Destroy yourself .

③. Code example

QtClassDemo * demo = new QtClassDemo(this);  
demo->setObjectName("demo");

for (int i = 0; i < 5; i++)
{
    
  qApp->postEvent(demo, new CustomEvent("hello"));
}

 Insert picture description here

 Insert picture description here

原网站

版权声明
本文为[litanyuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240610295165.html