QT开发中文网

我希望可以让用户自己选择要添加多少个child

好的,你可以添加一个QSpinBox控件,让用户选择要添加的子节点数量。然后,在生成XML文档时根据用户选择的数量动态创建对应数量的子节点。

以下是修改过的示例代码:

  1. 在Qt Designer中将一个QSpinBox控件拖拽到UI界面中,并给它命名为“childCountSpinBox”。

  2. 在mainwindow.h文件中添加以下代码:

private:
    int m_childCount = 0; // 记录用户选择的子节点数量

private slots:
    void on_generateButton_clicked();
  1. 修改on_generateButton_clicked()函数如下:
void MainWindow::on_generateButton_clicked()
{
    // 创建XML文档对象
    QDomDocument doc;
    QDomElement root = doc.createElement("root");
    doc.appendChild(root);

    // 添加子节点
    for (int i = 1; i <= m_childCount; ++i) {
        QDomElement person = doc.createElement("person");
        person.setAttribute("id", QString::number(i));
        root.appendChild(person);
        QDomElement name = doc.createElement("name");
        name.appendChild(doc.createTextNode(ui->nameTextEdit->toPlainText()));
        person.appendChild(name);
        QDomElement age = doc.createElement("age");
        age.appendChild(doc.createTextNode(ui->ageLineEdit->text()));
         person.appendChild(age);
     }

     // 将XML文档写入文件
     QFile file(ui->filenameLineEdit->text());
     if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
         return;
     QTextStream out(&file);
     out.setCodec("UTF-8"); // 设置编码格式为UTF-8
     out << doc.toString();

     ui->statusBar->showMessage(tr("XML generated successfully for %1 persons.").arg(m_childCount));
}
  1. 将QSpinBox控件的valueChanged()信号与槽函数on_childCountSpinBox_valueChanged()连接起来,并在其中记录用户选择的子节点数量。在mainwindow.h文件中添加以下代码:
private slots:
    void on_childCountSpinBox_valueChanged(int count);
void MainWindow::on_childCountSpinBox_valueChanged(int count)
{
    m_childCount = count;
}
  1. 运行程序,用户可以通过QSpinBox控件选择要添加的子节点数量,然后点击“Generate”按钮生成对应数量的XML文档。

希望这个示例能够帮到你!

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=2731

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?