Qt Designer - How to connect a signal to a static function?

前端 未结 2 1160
悲哀的现实
悲哀的现实 2021-01-13 11:14

Okay I\'m using Qt Designer to build a GUI. I\'ve managed to figure out how to make the menuBar and I\'ve added some actions to the bar, but now I need to connect the actio

相关标签:
2条回答
  • 2021-01-13 12:08

    The second argument is incorrect. You should specify the class name, not object name. So it should be:

    QObject::connect(actionOpen, &QAction::triggered, fileOpen);
    

    Complete working example (tested):

    void fileOpen() {
      qDebug() << "ok";
    }
    
    int main(int argc, char *argv[]) {
      QApplication a(argc, argv);
      QMenu menu;
      QAction* actionOpen = menu.addAction("test");
      QObject::connect(actionOpen, &QAction::triggered, fileOpen);
      menu.show();
      return a.exec();
    }
    
    0 讨论(0)
  • 2021-01-13 12:12

    1.) Create regular slot and call the static function.

    OR

    2.) I suppose you could create a singleton Q_OBJECT class and connect to it - of course like option 1 you'd then make the call to whatever static/global function.

    /**
     * Pseudo-code!, the singleton should be in its own header file 
     * not in the global main.cpp file.
     */
    class Singleton : public QObject
    {
    Q_OBJECT
    public:
      Singleton() : QObject() {}
      static Singleton* getInstance() {
        if(!_instance) _instance = new Singleton();
        return _instance;
      }
    public slots:
      void mySlot() { qDebug() << __FILE__ << " " << __FUNCTION__ << __LINE__;
      }
    private:
      static Singleton* _instance;
    };
    
    Singleton* Singleton::_instance = NULL;
    
    int main(int argc, char *argv[])
    {
      QApplication a(argc, argv);
      MainWindow w;
      w.show();
    
      Singleton* instance = Singleton::getInstance();
      QObject::connect(&w, SIGNAL(destroyed()), instance, SLOT(mySlot()));
    
      return a.exec();
    }
    

    I'm just trying my best to answer the question, but like many of the comments above - this isn't something that I've needed ever needed to do. I can say that QtCreator/Designer is a really amazing tool and as you overcome some of the learning curves it'll be less frustrating.

    0 讨论(0)
提交回复
热议问题