如何/应该在Qt中创建ui表单和数据成员之间的自动链接

How can/should I create automatic link between ui forms and data members in Qt?

本文关键字:之间 数据成员 链接 表单 ui Qt 创建 如何      更新时间:2023-10-16

这是一个通用问题,我不知道通常是如何处理的,我正在寻找一种好的(??)方法:

我有一个ui,它有许多数字形式,对应于我程序的各种选项。我有几个使用ui提供的数据的结构。

显然,我需要同步表单和数据。现在我手动完成,并编写这样的函数:

Options GetOptions(){ //fetches data from ui and stores it in my structure
        options.fil.alpha = ui.fil_consecutive_alpha->value();
        options.fil.beta = ui.fil_consecutive_beta->value();
        options.fil.gamma = ui.fil_consecutive_gamma->value();
        options.fil.delta = ui.fil_consecutive_delta->value();
        options.fil.k_max = ui.fil_consecutive_k_max->value();
        options.fil.radius = ui.fil_consecutive_radius->value();
        options.fil.omega = ui.fil_consecutive_omega->value();
        options.fil.side_length = ui.fil_consecutive_side_length->value();
        options.fil.norm = ui.fil_consecutive_norm->value();
        options.fil.consecutive_images = true;
}
void SetOptions(const Options& options){ //update ui forms with the loaded options sdtored in the structure
        ui.fil_consecutive_alpha->setValue(options.fil.alpha);
        ui.fil_consecutive_beta->setValue(options.fil.beta );
        ui.fil_consecutive_gamma->setValue(options.fil.gamma);
        ui.fil_consecutive_delta->setValue(options.fil.delta);
        ui.fil_consecutive_k_max->setValue(options.fil.k_max);
        ui.fil_consecutive_radius->setValue(options.fil.radius);
        ui.fil_consecutive_omega->setValue(options.fil.omega);
        ui.fil_consecutive_side_length->setValue(options.fil.side_length);
        ui.fil_consecutive_norm->setValue(options.fil.norm);
    }

每次添加ui字段时,我都必须更新集合并获取函数。这些功能看起来很笨,而且随着时间的推移,情况越来越糟,我被告知计算机擅长处理这种重复的笨任务。

那么,你认为以某种方式说每个以"fil_consective_"开头的ui表单都应该与结构选项.fil相关联是个好主意吗?我如何通过程序实现这一点?

我会给你一个想法。您可以将objectName设置为窗体。如果在Designer中设置ObjectName,则将在生成的ui.hh文件中完成。使用QList存储所有特定表单和选项的QMap。

...
// set form's name somewhere
ui.fil_consecutive_alpha->setObjectName("fil_consecutive_omega");
...
...
// colect forms like this
QObjectList list = this.children();
QObjectList forms = QObjectList();
for (int i = 0; i < list.size(); ++i) {
    if list[i].objectName().startsWith("fil_consecutive_")
         forms << list[i];
...
...
// then your function will be
void getOptions(QObjectList forms){
    ...
    for (int i = 0; i < forms.size(); ++i) {
         QString opt = forms[i].objectName().mid(QString("fil_consecurive_").length())
         options.fil[opt] = forms[i].property("value");
    }
    ...
}