Qt World Summit: Submit your Presentation

QTimers and QThreads

  • Dear all,

    I'm writing an application which makes use of QTimers, QThreads and Socket_CAN.

    I have a main visualization, I need to send at a certain timing a CANbus message and I want to read the data traffic on the bus at all times. So what I did:

    1. My main application which runs the visualization.
    2. CANopen Object.

    Please see code below.

    #include "canopen.h"
    CANOpen::CANOpen(QObject *parent) : QObject(parent)
        NMT_timer = new QTimer(this);
        // initialize CAN socket
        int com_error;
        com_error = can_socket->open_port("can0",0);
            qDebug() << "E301: Internal Error: Unable to open CAN SOCKET. NO Communication possible" + QString::number(com_error);
        // Start to send CANbus message at certain timing (800ms)
        iStep = 0;
    void CANOpen::canopen_init(QString canbus, int filter)
    void CANOpen::DoSetup(QThread &cThread)
        // Setup thread. Function is called when a button is pushed
    void CANOpen::DoWork()
        // Read traffic on CANbus 
        qDebug() << "read port";
    void CANOpen::NMT_Send()
        // Send message on CANbus 
        qDebug() << "NMT message";
        can_frame NMT_message;
        NMT_message.can_id = 0x701;
        NMT_message.can_dlc = 1;
        NMT_message.data[0] = 0x7F;

    So what is happening now:

    The application starts up and start to send messages on the CANbus every 800ms. So so far so good.
    Then I push the button, so the DoWork function is called. The thread is started and I can read every message on the CANbus.
    The only issue at this moment is that no messages are send on the CANbus anymore. I suppose the Thread block the timer to run. (The main application continues with out any issue)
    Is this correct? Ifso, how can I solve this please?

    Thanks in advance,
    Kind regards,

  • Lifetime Qt Champion

    @TMJJ001 said in QTimers and QThreads:


    You do NOT execute DoWork() in that thread, you execute it in the GUI thread.
    Take a closer look at the example here: https://doc.qt.io/qt-5/qthread.html