由于您最后需要的是 a QList<AnyClass*>
,因此您可以尝试这样的事情(假设AnyClass
源自QObject
)
注意:我对您的原始代码进行了一些修改,以通过引用传递您的列表,因为返回一个巨大的列表可能效率不高。我没有编译代码,但希望你能弄清楚这段代码中发生了什么
void DbManager::listVO(QString voname, QList<AnyClass*>& listAnyClass)
{
DbManager::VOPropertiesJoin(DbManager::VOKeys(obj),VOJOIN_BOTH,"=");
// Initialise list with an empty list
listAnyClass = QList<AnyClass*>();
QString voquery = "select * from %1";
voquery = voquery.arg(voname);
QSqlQueryModel *volist = DbManager::makeSelect(voquery);
for(int i = 0; i < volist->rowCount(); i++)
{
QObject *voinstance = GetInstance(voname, volist->record(i));
// Trying to cast into an AnyClass
AnyClass* pAnyClass = qobject_cast<AnyClass*>(voinstance);
// If pAnyClass is a valid AnyClass* update your list
if(pAnyClass)
{
listAnyClass.append(pAnyClass);
}
}
}
QObject* DbManager::GetInstance(QString sVoname, const QSqlRecord& record)
{
return DbManager::instantiateVO
(
voname,
record.value(0),
record.value(1),
record.value(2),
record.value(3),
record.value(4),
record.value(5),
record.value(6),
record.value(7)
)
}
调用DbManager::listVO(QString voname, QList<AnyClass*>& listAnyClass)
函数后,listAnyClass
将相应地填充。与返回列表相比,这很有效。
编辑:
因此,简而言之,您要将 a 转换QList<QObject*>
为QList<AnyClass*>
. 因此,请保持原始代码不变,并在您想要进行此转换的地方实现这样的方法:
void ConvertToAnyClassList(const QList<QObject*>& listQObjects, QList<AnyClass*>& listAnyClass)
{
listAnyClass = QList<AnyClass*>();
for( int i = 0; i < listQObjects.length(); ++i )
{
AnyClass* pAnyClass = qobject_cast<AnyClass*>(listQObjects.at(i));
if(pAnyClass)
{
listAnyClass.append(pAnyClass)
}
}
}
你可以这样称呼它:
QList<QObject*> listQObjects = DbManager::listVO("AnyClass");
QList<AnyClass*> listAnyClass;
ConvertToAnyClassList(listQObjects,listAnyClass);
假设您有多种类型,因此您可能希望为每种类型实现函数,如下所示:
ConvertToUserList(listQObjects,listUserObjects);
ConvertToCountryList(listQObjects,listCountryObjects);