以下是一个示例代码:

// ThreadWorker.h

#ifndef THREADWORKER_H #define THREADWORKER_H

#include #include

class ThreadWorker : public QObject { Q_OBJECT

public: explicit ThreadWorker(QObject *parent = nullptr);

public slots: void loadXmlFile(const QString &filePath);

signals: void xmlLineLoaded(const QString &line);

private: QThread thread; };

#endif // THREADWORKER_H

// ThreadWorker.cpp

#include "ThreadWorker.h" #include #include

ThreadWorker::ThreadWorker(QObject *parent) : QObject(parent) { moveToThread(&thread); thread.start(); }

void ThreadWorker::loadXmlFile(const QString &filePath) { QFile file(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;

QXmlStreamReader xml(&file);
while (!xml.atEnd() && !xml.hasError()) {
    QXmlStreamReader::TokenType token = xml.readNext();
    if (token == QXmlStreamReader::StartElement) {
        QString name = xml.name().toString();
        emit xmlLineLoaded(name); // 发送信号
    }
}

file.close();

}

// MainWindow.h

#ifndef MAINWINDOW_H #define MAINWINDOW_H

#include

namespace Ui { class MainWindow; }

class ThreadWorker;

class MainWindow : public QMainWindow { Q_OBJECT

public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow();

private slots: void on_pushButton_clicked(); void handleXmlLineLoaded(const QString &line);

private: Ui::MainWindow *ui; ThreadWorker *worker; };

#endif // MAINWINDOW_H

// MainWindow.cpp

#include "MainWindow.h" #include "ui_MainWindow.h" #include "ThreadWorker.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), worker(new ThreadWorker) { ui->setupUi(this);

connect(worker, &ThreadWorker::xmlLineLoaded, this, &MainWindow::handleXmlLineLoaded); // 连接信号和槽

}

MainWindow::~MainWindow() { delete ui; delete worker; }

void MainWindow::on_pushButton_clicked() { QString filePath = QFileDialog::getOpenFileName(this, tr('Open XML File'), '', tr('XML Files (*.xml)')); if (filePath.isEmpty()) return;

worker->loadXmlFile(filePath); // 在子线程中加载XML文件

}

void MainWindow::handleXmlLineLoaded(const QString &line) { ui->textEdit->append(line); // 在主线程中更新UI }

Qt C++ 子线程加载 XML 文件并更新 UI

原文地址: https://www.cveoy.top/t/topic/mUOi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录