7

我正在尝试使用 Qt 创建一个接口,以强制任何子类实现两个主要方法 set 和 get title。但是当我尝试编译它时,我收到一条奇怪的错误消息,上面写着关于 qt_check_for_QOBJECT_macro 和 staticMetaObject 的信息。在 mainwindow.cpp 中,我必须将任何页面转换为界面,以便我可以依赖 getter 和 setter 方法。我看不出有任何其他方法可以做到这一点。

这是我的代码:

//IPage.h
#ifndef IPAGE_H
#define IPAGE_H

#include <QString>

class IPage
{
public:
 virtual QString title()=0;
 virtual void setTitle(QString t)=0;
};

#endif // IPAGE_H


//buildings.h:
#ifndef BUILDINGS_H
#define BUILDINGS_H

#include "IPage.h"
#include <QDialog>

class Buildings : public IPage, public QDialog
{
   Q_OBJECT
 private:
   QString m_title;
 //stuff...
};
#endif
//buildings.cpp
//stuff...

void Buildings::setTitle(QString t)
{
   m_title = t;
   setWindowTitle(t);
}

QString Buildings::title()
{
   return m_title;
}

//mainwindow.cpp:
QMdiSubWindow *MainWindow::findChild(const QString &title)
{
    foreach (QMdiSubWindow *window, mdiArea->subWindowList()) {
        IPage *child = qobject_cast<IPage *>(window->widget()); /*line 178*/
        if (child->title() == title)
            return window;
    }
    return 0;
}

编译代码时收到此错误消息:

In file included from c:\QtSDK\Desktop\Qt\4.8.1\mingw\include/QtCore/qabstractanimation.h:45,
             from c:\QtSDK\Desktop\Qt\4.8.1\mingw\include/QtCore/QtCore:3,
             from c:\QtSDK\Desktop\Qt\4.8.1\mingw\include\QtGui/QtGui:3,
             from mainwindow.cpp:1:
c:\QtSDK\Desktop\Qt\4.8.1\mingw\include/QtCore/qobject.h: In function 'T qobject_cast(QObject*) [with T = IPage*]':
mainwindow.cpp:178:   instantiated from here
c:\QtSDK\Desktop\Qt\4.8.1\mingw\include/QtCore/qobject.h:378: error: 'class IPage' has no member named 'qt_check_for_QOBJECT_macro'
c:\QtSDK\Desktop\Qt\4.8.1\mingw\include/QtCore/qobject.h:380: error: 'class IPage' has no member named 'staticMetaObject'
mingw32-make.exe[1]: Leaving directory `D:/Dropbox/Programmi/Qt/Scadenziario'
mingw32-make.exe[1]: *** [build/o/mainwindow.o] Error 1
mingw32-make.exe: *** [debug] Error 2
01:23:26: The process "C:\QtSDK\mingw\bin\mingw32-make.exe" exited with code 2.
Error while building project scadenziario (target: Desktop)
When executing build step 'Make'

我无法理解错误信息。我试图用谷歌搜索它,但我找不到任何有用的信息。任何帮助将不胜感激,在此先感谢。

4

3 回答 3

11

元对象编译器要求您继承的第一个类是QObject派生类

所以你应该改变:

class Buildings : public IPage, public QDialog

至:

class Buildings : public QDialog, public IPage

于 2013-03-03T16:22:05.013 回答
2

使用时qobject_cast<T *>T必须继承自QObject. 在您的情况下,T=IPageIPage不继承QObject. 这就是你得到错误的原因。

于 2012-07-15T00:26:13.660 回答
0

添加到 air-dex 的答案:

由于 提供的元数据QObject,当在QObjects 之间转换时不需要 RTTI,这使得操作更快(如果您专门使用它,您可以关闭可执行文件中的 RTTI 支持,使其更小)。但是,它并非旨在以您尝试的方式使用 - 作为dynamic_cast. 所以只需改变:

IPage *child = qobject_cast<IPage *>(window->widget()); /*line 178*/

至:

IPage *child = dynamic_cast<IPage *>(window->widget()); /*line 178*/
于 2012-07-16T08:22:46.490 回答