簡體   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