简体   繁体   English

非Qt基类

[英]Non-Qt Base Classes

I'm using Qt (which I'm new to) 4.8.2, with Visual Studio, and I have created a base class named "Contact". 我正在使用Qt(我是新手)4.8.2,使用Visual Studio,我创建了一个名为“Contact”的基类。 I don't want this class to be Qt-exclusive , so my intention was to make another class "QContact" that will inherit "Contact", and QObject and deal with all the Qt-related business, such as the Q_OBJECT macro etc. 我不希望这个类是Qt独占的 ,所以我的目的是创建另一个类“QContact”,它将继承“Contact”,而QObject则处理所有与Qt相关的业务,例如Q_OBJECT宏等。

Unfortunately when I inherited, the build failed, saying: 不幸的是,当我继承时,构建失败了,说:

moc_QContact.cpp(53): error C2039: 'staticMetaObject' : is not a member of 'Contact'
moc_QContact.cpp(75): error C2039: 'qt_metacast' : is not a member of 'Contact'
moc_QContact.cpp(80): error C2039: 'qt_metacall' : is not a member of 'Contact'

I did a little research on the web and found out that you can't derive a Qt class from non-Qt class. 我在网上做了一些研究,发现你不能从非Qt类中派生出一个Qt类。 so to fix it, "Contact" could inherit "QObject" (I tried, it worked). 所以要解决它,“联系”可以继承“QObject”(我试过,它有效)。 but doing so will make it exclusive to Qt which is my problem. 但这样做会使它成为Qt独有的,这是我的问题。

So what I ask is this: How can you make a non-Qt base class for a Qt class? 所以我要问的是:如何为Qt类创建非Qt基类?

Thank you. 谢谢。

You can derive your class from QObject and from other classes that don't derive from it, but QObject needs to be the first base class in the base classes list. 您可以从QObject和其他不从它派生的类派生您的类,但QObject需要是基类列表中的第一个基类

So this is wrong: 所以这是错的:

class QContact: public Contact, public QObject {};

You need to write it as 你需要把它写成

class QContact: public QObject, public Contact {};

From An Introduction To Design Patters in C++ with Qt Chapter 8.4: 从Qt第8.4章开始用C ++设计Patters

To help ensure that moc processes each QObject-derived class in the project, following are some guidelines for writing: C++ code and qmake project files: 为了帮助确保moc处理项目中的每个QObject派生类,以下是一些编写指南:C ++代码和qmake项目文件:

• Each class definition should go in its own .h file. •每个类定义都应该放在自己的.h文件中。

• Its implementation should go in a corresponding .cpp file. •其实现应该在相应的.cpp文件中。

• The header file should be “wrapped” (eg, with #ifndef) to avoid multiple inclusion. •头文件应该“包装”(例如,使用#ifndef)以避免多次包含。 • Each .cpp file should be listed in the SOURCES variable of the project file; •每个.cpp文件都应列在项目文件的SOURCES变量中; otherwise it will not be compiled. 否则不会被编译。

• Each header file should be listed in the HEADERS variable of the .pro file. •每个头文件都应列在.pro文件的HEADERS变量中。 Without this, moc will not preprocess the file. 没有这个,moc将不会预处理文件。

• The Q_OBJECT macro must appear inside the class definition of each QObject derived header file so that moc knows to generate code for it. •Q_OBJECT宏必须出现在每个QObject派生头文件的类定义中,以便moc知道为其生成代码。

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

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