Search code examples
c++qtsignalsemit

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.


Solution

  • 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 );
    }