Qt Connecting SIGNAL and SLOT in object member of MainWindow

余生长醉 提交于 2019-12-20 04:50:33

问题


I have a class MyClass with:

  - private: 
      pushButton *button;
      void connectSignalAndSlot();
  - private slot: 
      void buttonAction();

I want to connect these in MyClass using connectSignalAndSlot(), like so:

  void MyClass::connectSignalAndSlot()
  {
    QObject::connect(button,SIGNAL(clicked()),this,SLOT(buttonAction()));
  }

This gives me an error of

no matching function for call to 'QObject::connect(QPushButton*&, const char*, MyClass* const, const char*)';

If I inherit QObject with MyClass, the program compiles and starts, but then I get the following issues displayed in my Application Output pane:

QObject::connect: No such slot QObject::buttonAction() in ..\MyProject\myclass.cpp:48

Do I have to make the button and slot public and use them in the MainWindow class only? Is there no way to keep this at the MyClass level?

Thanks for your help!


回答1:


You must have MyClass inherit from QObject AND add Q_OBJECT macro in your MyClass definition (header file) to have slots/signals work.

class MyClass : public QObject
{
     Q_OBJECT

public:
     ....
};



回答2:


Inheriting QObject is the right way, but your still missing Qt-Meta Object Code. Your header-file for your class should look like this:

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass : public QObject {
    Q_OBJECT
    // your methods, variables, slots and signals
}

#endif

Don't forget to create the moc file, the easiest way is to use qmake or the QtCreator IDE.



来源:https://stackoverflow.com/questions/24982358/qt-connecting-signal-and-slot-in-object-member-of-mainwindow

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