我想实例化一个关于其名称的类。我发现Qt允许QMetaType::create
我还发现我们必须使用Q_DECLARE_METATYPE
注册该类。
但我做了所需的一切(我认为),但它没有用。
那是我的基本课程:
#ifndef __BLOCK_HH__
# define __BLOCK_HH__
# include <QMetaType>
# include <QObject>
# include <string>
# include <vector>
# include "Util.hpp"
# include "Common.hh"
class Block
{
protected:
std::string _name;
uint32 _u32StartAddr;
uint32 _u32EndAddr;
uint8 *_pu8Content;
bool _bSure;
bool _bVirgin;
std::string _type;
std::vector<std::string> _errorCauses;
Block(const std::string&, uint32, uint32, uint8 *, const std::string&);
public:
Block(const std::string& = "", uint32 = 0, uint32 = 0, uint8 * = 0);
Block(const Block&);
virtual ~Block();
Block& operator=(const Block&);
void setName(const std::string&);
void setStartAddr(uint32);
void setEndAddr(uint32);
void setContent(uint8 *);
void sure();
void notSure();
void erase();
const std::string& getName() const;
uint32 getStartAddr() const;
uint32 getEndAddr() const;
uint8 *getContent() const;
bool isSure() const;
bool isVirgin() const;
const std::string& getType() const;
void addError(const std::string&);
void dumpError(std::ostream& = std::cerr) const;
virtual void dump(std::ostream& = std::cout) const;
virtual void parse();
virtual bool operator<(const Block&) const;
};
Q_DECLARE_METATYPE(Block)
#endif
这是继承的类之一:
#ifndef __CSS_HH__
# define __CSS_HH__
# include "Block.hh"
typedef struct
{
uint32 boot_lma;
uint32 boot_vma;
uint32 boot_length;
uint32 boot_entry;
uint32 nb_of_param;
} t_css;
class CSS : public Block
{
uint32 _u32BootFlashAddr;
uint32 _u32BootSdramAddr;
uint32 _u32BootSize;
uint32 _u32Bep;
uint32 _u32CpuClock;
uint32 _u32SdramSize;
bool _bEncram;
public:
CSS(uint32 = 0, uint32 = 0, uint8 * = 0);
virtual ~CSS();
virtual void dump(std::ostream& = std::cout) const;
virtual void parse();
uint32 getBootFlashAddr() const;
uint32 getBootSdramAddr() const;
uint32 getBootSize() const;
uint32 getBEP() const;
uint32 getCpuClock() const;
uint32 getSdramSize() const;
bool encramEnabled() const;
};
Q_DECLARE_METATYPE(CSS)
#endif
这就是我用来实例化的代码:
Block *Mapper::constructBlock(const std::string& name, uint32 u32Start, uint32 u32End, uint8 *pu8Content)
{
Block *block = 0;
int32 i32Id = QMetaType::type(name.c_str());
if (i32Id != QMetaType::UnknownType)
{
block = static_cast<Block *>(QMetaType::create(i32Id));
if (block)
{
block->setStartAddr(u32Start);
block->setEndAddr(u32End);
block->setContent(pu8Content);
block->parse();
}
}
return (block);
}
我在这里给出的名称是Block的“Block”和CSS类的“CSS”。但QMetaType::type
总是返回QMetaType::UnknownType
也许我忘记了注册课程的东西。你知道吗?
由于
答案 0 :(得分:2)
您还需要使用qRegisterMetaType()
注册类型,以便在运行时使名称可用。 Q_DECLARE_METATYPE
在编译时将类型称为基于模板的Qt函数。