Qt QMetaObject::invokeMethod 跨线程操作 UI 控件
传递自定义类型
如果需要传递自定义类型,必须先注册该类型。
#include <QApplication>
#include <QPushButton>
#include <QDebug>
#include <thread>
#include <chrono>
// 自定义类型
struct CustomData {
QString name;
int value;
};
// 注册自定义类型
Q_DECLARE_METATYPE(CustomData)
class MainWindow : public QWidget {
Q_OBJECT
public:
MainWindow() {
qRegisterMetaType<CustomData>(); // 注册自定义类型
button = new QPushButton("Start", this);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(button);
setLayout(layout);
connect(button, &QPushButton::clicked, this, &MainWindow::startThread);
}
void startThread() {
std::thread([this]() {
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
CustomData data = {"Item", i};
// 传递自定义类型
QMetaObject::invokeMethod(this, "updateButton", Qt::QueuedConnection,
Q_ARG(CustomData, data));
}
}).detach(); // 分离线程,让它在后台运行
}
public slots:
void updateButton(const CustomData &data) {
button->setText(QString("%1: %2").arg(data.name).arg(data.value));
qDebug() << "Button text updated:" << button->text();
}
private:
QPushButton *button;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
#include "main.moc"
from deepseek.
浙公网安备 33010602011771号