简体   繁体   English

Qt在MainWindow的对象成员中连接SIGNAL和SLOT

[英]Qt Connecting SIGNAL and SLOT in object member of MainWindow

I have a class MyClass with: 我有一个MyClass类:

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

I want to connect these in MyClass using connectSignalAndSlot(), like so: 我想使用connectSignalAndSlot()在MyClass中连接它们,如下所示:

  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: 如果我使用MyClass继承了QObject,则程序将编译并启动,但是随后在“应用程序输出”窗格中显示以下问题:

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? 我是否必须公开按钮和插槽并仅在MainWindow类中使用它们? Is there no way to keep this at the MyClass level? 没有办法将其保持在MyClass级别吗?

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. 必须具有从QObject继承的MyClass ,并在MyClass定义(头文件)中添加Q_OBJECT宏,才能使插槽/信号起作用。

class MyClass : public QObject
{
     Q_OBJECT

public:
     ....
};

Inheriting QObject is the right way, but your still missing Qt-Meta Object Code. 继承QObject是正确的方法,但是仍然缺少Qt元对象代码。 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. 不要忘记创建moc文件,最简单的方法是使用qmakeQtCreator IDE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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