繁体   English   中英

将Qt宏Q_OBJECT用于插槽

[英]Using Qt macro Q_OBJECT for slots

这个问题相当确定,但看起来像是重复的,但是在进行研究并查看相同的问题之后,我发现需要使用宏Q_OBJECT进行SLOT使用,但是当我使用它时,出现了编译错误。 这是我的代码段。

main.cpp

#include <QApplication>
#include "window_general.h"

int main(int argc, char **argv)
{
 QApplication app (argc, argv);

 Window_General window_general;

 window_general.show();
 return app.exec();
}

windows_general.h

#ifndef WINDOW_GENERAL_H
#define WINDOW_GENERAL_H

#include <QWidget>
#include <QApplication>

class QPushButton;
class Window_General : public QWidget
{

public:
  explicit Window_General(QWidget *parent = 0);


private slots:
  void MyhandleButton();

private:
 QPushButton *m_button;
};


#endif // WINDOW_GENERAL_H

windows_general.cpp

#include "window_general.h"
#include <QPushButton>


Window_General::Window_General(QWidget *parent) :
 QWidget(parent)
 {
 // Set size of the window
 setFixedSize(800, 500);
 // Create and position the button
 m_button = new QPushButton("Hello World", this);
 m_button->setGeometry(10, 10, 80, 30);

  connect(m_button, SIGNAL (released()), this, SLOT (MyhandleButton()));
}

void Window_General::MyhandleButton()
{
 m_button->setText("Example");
 m_button->resize(100,100);
}

在这段代码中,我有一个运行时错误:

QObject::connectQWidget::MyhandleButton() :14中没有这样的插槽QWidget::MyhandleButton()

如果我在这里放一个Q_OBJECT宏,

class Window_General : public QWidget
{
Q_OBJECT
public:
  explicit Window_General(QWidget *parent = 0);


private slots:
  void MyhandleButton();

private:
 QPushButton *m_button;
};

然后我有这个错误:

D:\\ work \\ my_qt \\ prj \\ window_general.h:8:错误: Window_Generalvtable未定义引用

我的问题是,如何在此代码集中使用按钮事件?

看来您需要调用qmake实用程序来重新生成moc。 Q_OBJECT将一些QObject的重写成员函数声明放到您的类中,而qmake将它们的定义生成到yourclass.moc.cpp中。 每次放置新的Q_OBJECT ,都需要调用qmake。

通过使用指针到成员函数语法而不是SIGNALSLOT宏,可以完全避免使用Q_OBJECT宏。 例如:

connect(m_button, &QPushButton::released, this, &Window_General::MyhandleButton);

暂无
暂无

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

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