【发布时间】:2018-06-12 16:02:22
【问题描述】:
我从 .ini 文件中读取到 c++ 中的整数,然后通过绑定在 QML 中使用该整数。在运行时,可以更改 .ini 文件中的值,这会导致 c++ 整数也发生更改。我发现虽然整数在 c++ 中确实发生了变化(通过 qDebug() 验证),但 QML 中的绑定值没有改变,尽管发出了所需的 changed() 信号。我的应用程序结构的摘录如下所示:
main.cpp:
//Establish the QQmlApplication engine, set context properties for the two c++ files and load the QML file.
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty(QStringLiteral("MainCpp"), new MainCpp());
engine.rootContext()->setContextProperty(QStringLiteral("Config"), new Config());
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
maincpp.h:
public:
explicit MainCpp(QObject *parent = nullptr);
Q_PROPERTY(int someValue READ someValue NOTIFY someValueChanged)
int someValue(){return m_someValue;}
signals:
void someValueChanged();
private:
int m_someValue;
config.h:
public:
explicit Config(QObject *parent = nullptr);
Q_PROPERTY(int someOtherValue READ someOtherValue NOTIFY someOtheralueChanged)
int someOtherValue(){return m_someOtherValue;}
signals:
void someOtherValueChanged();
public:
void loadSettings();
public:
int m_someOtherValue;
QString m_File;
config.cpp:
Config::Config(QObject *parent) : QObject(parent)
{
m_File = "/some/path/to/settings/file/config.ini";
loadSettings();
}
void Config::loadSettings()
{
QSettings settings(m_File, QSettings::IniFormat);
settings.beginGroup("GROUP_NAME");
m_someOtherValue = settings.value("someOtherValueConfig", "").toInt();
settings.endGroup();
}
maincpp.cpp:
MainCpp::MainCpp(QObject *parent = nullptr) : QObject(parent)
{
Config configPointer;
m_someValue = configPointer.someOtherValue();
emit someValueChanged();
}
main.qml:
Window {
width: 800
height: 480
Text {
id: someText
text: Config.someOtherValue //This does NOT update on changes to m_someOtherValue on the c++ side
//text: MainCpp.someValue //This DOES update on change to m_someValue on the c++ side
}
}
在 maincpp.cpp 中调用以下代码来更新 .ini 文件:
void MainCpp::update(int var)
{
Config configPointer;
QSettings settings("/some/path/to/settings/file/config.ini", QSettings::IniFormat);
settings.setValue("GROUP_NAME/someOtherValueConfig", var);
configPointer.m_someOtherValue = var;
m_someValue = configPointer.someOtherValue;
emit configPointer.someOtherValueChanged();
emit someValueChanged();
}
我添加了“发出 someOtherValueChanged()”信号但无济于事。如前所述,我知道 m_someOtherValue 已更改,因为我使用 qDebug() 对其进行查询。如果 m_someValue 发生变化,为什么 QML 没有观察到 m_someOtherValue 的变化?
【问题讨论】:
-
你说:.ini文件中的值是可以改的,请问你是怎么改的?
-
将
someVOtheralueChanged更改为someOtheralueChanged,错字。 -
我手动修改了 .ini,但我没有看到 2 个值发生变化,请更好地解释自己。
-
它在用户输入时以编程方式更改。我已经通过 qDebug() 和在运行时查看 .ini 文件验证了此函数按预期工作。
-
再补充一句,我们需要一个minimal reproducible example,如果你不放,它不会重现你的错误。