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

守給你的承諾、 提交于 2019-12-01 07:03:49

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!