简体   繁体   中英

Qt Connecting SIGNAL and SLOT in object member of MainWindow

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!

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:
     ....
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM