简体   繁体   中英

Programatically executing mouse events in QT

I want to transfer a mouse event from one widget and execute it on another, I'm sending the mouse event through a signal.

void Eventhost::mousePressEvent(QMouseEvent* event)
{
    emit SignalControl(event);
}

This event gets sent to the widget where it is processed here;

void EventReceiver::mousePressEvent(QMouseEvent * event)
{
    event->accept();
    QWidget::mousePressEvent(event);
}

However even though the event makes it to the eventreceiver the mouse event doesn't seem to execute. What am I missing? I'd appreciate any input

Try it without using event->accept(); in your EventReceiver. As explained in Qt Docs:

Events that can be propagated have an accept() and an ignore() function that you can call to tell Qt that you "accept" or "ignore" the event. If an event handler calls accept() on an event, the event won't be propagated further; if an event handler calls ignore(), Qt tries to find another receiver.

This is the reason QWidget::mousePressEvent(event); is not being called inside void EventReceiver::mousePressEvent(QMouseEvent * event) .

You need to connect a signal emitter to a slot receiver. The SignalControl method must be declared under signals: in the header for the Eventhost class, mousePressEvent must be declared under slots: in the header for the EventReceiver class.

Eventhost* hostObj = new Eventhost(...
EventReceiver* recvObj = new EventReceiver(...
QObject::connect(hostObj, &Eventhost::SignalControl,
                 recvObj, &EventReceiver::mousePressEvent);

See the docs here: https://doc.qt.io/qt-5/signalsandslots.html

Also see: Qt: How to handle custom events with connect?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM