我想实例化有关其名称的类。我发现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
。也许我忘了一些东西去上课了。你有主意吗?
谢谢
最佳答案
您还需要向qRegisterMetaType()
注册类型,以在运行时使用该名称。 Q_DECLARE_METATYPE
使基于模板的Qt函数在编译时知道该类型。