Qt 为什么';t这将QVector中的QObject*相加<;QObject*>;

Qt 为什么';t这将QVector中的QObject*相加<;QObject*>;,qt,extern,qvector,qproperty,Qt,Extern,Qvector,Qproperty,我有两个视图模型,MainVM和AddVM。在main.cpp中,MainVM是这样声明的: MainVM *mvm; int main(int argc, char *argv[]) { ... mvm = new MainVM(); ... engine.rootContext()->setContextProperty("mainContext", mvm); engine.rootContext()->set

我有两个视图模型,
MainVM
AddVM
。在
main.cpp
中,
MainVM
是这样声明的:

MainVM *mvm;    
int main(int argc, char *argv[])
{
    ...
    mvm = new MainVM();
    ...
    engine.rootContext()->setContextProperty("mainContext", mvm);
    engine.rootContext()->setContextProperty("addContext", new AddVM());
    ...
}
MainVM
中,我有一个
Q\u属性

class MainVM : public QObject
{
    Q_OBJECT
    ...
    PROPERTY(QVector<Plot*>, plots)
    ...
public:
    ...
    QSqlDatabase db;
    int maxPlotId, maxSpaceId, maxTenantId, maxHeadId, maxLeaseId;
    ...
};
在我的
AddVM
中,我有另一个
Q_属性
newPlot和一个
Q_可调用的
addNewPlot:

class AddVM : public QObject
{
    Q_OBJECT
    PROPERTY(Plot*, newPlot)
public:
    explicit AddVM(QObject *parent = nullptr);
    Q_INVOKABLE void addNewPlot();
}; 
AddVM.cpp
之上,我有以下内容:

#include "MainVM.h"
extern MainVM *mvm;
addNewPlot
函数具有以下说明:

void AddVM::addNewPlot()
{
    mvm->db.open();
    QSqlQuery query;
    query.prepare("INSERT INTO Plots (Name, Description) VALUES(:Name, :Description)");
    query.bindValue(":Name", newPlot()->name());
    query.bindValue(":Description", newPlot()->description());
    query.exec();
    mvm->db.close();

    mvm->plots().push_back(newPlot());
    setnewPlot(new Plot());
    newPlot()->setid(++mvm->maxPlotId);
}
除了
mvm->plots(),此函数中的所有内容都按预期工作行!这不会在
MainVM的
QVector
中添加
newPlot

编辑

最好的方法可能是在宏中重新定义
getter
,如下所示:

QType& name(){return m_##name;} \

因此,我现有的代码可以不做任何修改地工作。

当您调用
mvm->plots()
时,它会返回一个真实plots向量的副本(这是我的猜测,因为您没有显示
plots()
的功能)。因此,新的绘图将添加到副本而不是原始向量。因此,我认为最好的方法是在
MainVM
中添加一个名为“addPlot()”的函数,例如,您可以在其中直接内部添加到plots向量。

当您调用
mvm->plots()
时,它会返回一个真实plots向量的副本(我猜是因为您没有显示
plots()
的功能)。因此,新的绘图将添加到副本而不是原始向量。因此,我认为最好的方法是在
MainVM
中添加一个名为“addPlot()”的函数,例如,您可以在该函数中直接内部添加到plots向量。

是的,在宏中它返回
m#name
,名称为
plots
。在
MainVM
中添加一个函数将起作用。我在MainVM中添加了
QVector&plotsReference(){return m_plots;}
函数,而不是
plots()->push_back
中的
QVector&plotsReference()
函数。谢谢。是的,在宏中它返回
m##name
,名称为
plots
。在
MainVM
中添加一个函数将起作用。我在MainVM中添加了
QVector&plotsReference(){return m_plots;}
函数,而不是
plots()->push_back
中的
QVector&plotsReference()
函数。谢谢
QType& name(){return m_##name;} \