Evans Belloeil
Evans Belloeil

Reputation: 2503

Emit a signal in a static function

I've got a a static function : static void lancerServeur(std::atomic<bool>& boolServer) , this function is force to be static because I launch it in a thread, but due to this, I can't emit a signal in this function. Here's what I try to do :

void MainWindow::lancerServeur(std::atomic<bool>& boolServer){
    serveur s;
    StructureSupervision::T_StructureSupervision* bufferStructureRecu;
    while(boolServer){
        bufferStructureRecu = s.receiveDataUDP();
        if(bufferStructureRecu->SystemData._statutGroundFlight != 0){
            emit this->signal_TrameRecu(bufferStructureRecu);//IMPOSSIBLE TO DO
        }
    }
}

Is there a way to emit my signal ?

Thanks.

Upvotes: 4

Views: 2951

Answers (2)

TheDarkKnight
TheDarkKnight

Reputation: 27611

You can keep a static pointer to the instance of MainWindow in the MainWindow class and initialise it in the constructor. Then you can use that pointer to call the emit from the static function.

class MainWindow : public QMainWindow
{
    ...
    private:
        static MainWindow* m_psMainWindow;

        void emit_signal_TrameRecu(StructureSupervision::T_StructureSupervision* ptr)
        {
            emit signal_TrameRecup(ptr);
        }
};

// Implementation

// init static ptr
MainWindow* MainWindow::m_psMainWindow = nullptr; // C++ 11 nullptr

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    m_psMainWindow = this;
}


void MainWindow::lancerServeur(std::atomic<bool>& boolServer)
{
    StructureSupervision::T_StructureSupervision* bufferStructureRecu;

    ...

    if(m_psMainWindow)
        m_psMainWindow->emit_signal_TrameRecu( bufferStructureRecu );
}

Upvotes: 4

Paolo Brandoli
Paolo Brandoli

Reputation: 4750

Pass the pointer to the class as a parameter to lancerServeur, or you can use a slot on a worker class and move it to a thread.

See this example http://qt-project.org/doc/qt-4.8/qthread.html on how to use a slot to do the work on a separate thread.

Upvotes: 3

Related Questions