androbin
androbin

Reputation: 1759

QThread custom event

I'd like to create an RFID reader thread using Qt and MercuryAPI (native-c). It has a native-c thread, but it has problems. I decided to write one of my own.

So far I have the thread written with a custom event (TagReadEvent) that sends data. It drops the following qDebug error:

QCoreApplication::removePostedEvent: Internal error: 0xbfdfed8 1001 is posted

I can't find whatever called QCoreApplication::removePostedEvent, but drops this error when postEventList.size() == 0.

TagReadEvent:

class TagReadEvent : public QEvent
{
public:
    TagReadEvent();
    ~TagReadEvent();
    QList<TMR_TagData> tagData;
};

Custom event handler:

void MainWindow::customEvent(QEvent *event)
{
    if (event->type() == (QEvent::User + 1)) {
        TagReadEvent *tagEvent = static_cast<TagReadEvent *>(event);
        for (int i = 0; i < tagEvent->tagData.length(); ++i) {
            TMR_TagData tagData = tagEvent->tagData.at(i);
            char epcStr[128];
            TMR_bytesToHex(tagData.epc, tagData.epcByteCount, epcStr);
            qDebug() << epcStr;
        }
    }
    return QMainWindow::customEvent(event);
}

Filling and sending event:

    TagReadEvent event;
    while (TMR_SUCCESS == TMR_hasMoreTags(&(mainWindow->reader))) {
        TMR_TagReadData trd;
        lastStatus = TMR_getNextTag(&(mainWindow->reader), &trd);
        if (checkerr(tr("fetching tag")))
            return;
        event.tagData.append(trd.tag);
    }
    if (event.tagData.length() > 0)
        QCoreApplication::postEvent(mainWindow,&event);

Upvotes: 0

Views: 405

Answers (1)

androbin
androbin

Reputation: 1759

You should allocate the event on the heap, not as a local variable:

TagReadEvent * event = new TagReadEvent;

It will be destroyed and deallocated by the event loop running in the destination thread.

From the docs: QCoreApplication::postEvent:

Adds the event event, with the object receiver as the receiver of the event, to an event queue and returns immediately.

The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is not safe to access the event after it has been posted. (emphasis mine)

Upvotes: 1

Related Questions