gpt4 book ai didi

c++ - 如何使用C++更新QML文本

转载 作者:行者123 更新时间:2023-12-02 10:22:34 26 4
gpt4 key购买 nike

我有一个小问题。有人可以告诉我如何从c++更新qml文本。我有一个使用线程的示例,但我不想应用此方法,因为我不知道如何设置
run()函数中的参数。要完全理解我的代码,是我的代码。在主函数中,当我启动线程时,我想放置自定义文本或包含文本的字符串变量。

thread.h

#ifndef THREAD_H
#define THREAD_H

#include <QThread>

class Thread : public QThread
{
Q_OBJECT
public:
Thread(QObject *parent=nullptr);
~Thread() override;
Q_SLOT void stop();
Q_SIGNAL bool textChanged(const QString & text);
protected:
void run() override;
};

#endif // THREAD_H


thread.c
#include "thread.h"
#include <QDebug>

Thread::Thread(QObject *parent):
QThread(parent)
{
}

Thread::~Thread()
{
}

void Thread::stop()
{
requestInterruption();
wait();
}

void Thread::run() //here I want to specify a QString variable such that in main function to call the function with my text, and not specified the text from here
{
int i=0;

while(!isInterruptionRequested()){
QString text;
text = QString("I changed the text"); // I don't want to declare from here the text.
Q_EMIT textChanged(text);
QThread::msleep(20);
qDebug() <<i++;

}
}


main.cpp
...
Thread thread;
QQmlApplicationEngine engine;
QObject::connect(&app, &QGuiApplication::aboutToQuit, &thread, &Thread::stop);
thread.start();
engine.rootContext()->setContextProperty("thread", &thread);
engine.load(QUrl("qrc:/main.qml"));
thread.stop();
...

main.qml
  .....
Text {
objectName: "myLabel"
id: txt
width: 200
height: 29
color: "#faf9f9"
text: qsTr("Text")
font.pixelSize: 12
}
Connections{
target: thread
onTextChanged: txt.text = text
}

.....

最佳答案

您可以使用信号将数据从C++发送到qml,如下所示:

//main.cpp

int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

// Class init
YourClass yourObject;

// Embedding C++ Objects into QML with Context Properties
QQmlContext* ctx = engine.rootContext();
ctx->setContextProperty("yourObject", &yourObject);

return app.exec();
}

//main.qml
import QtQuick 2.6

Window {
id: mainWindow

Connections {
target: gapi
onSignalData: {
console.log("Data: " + data)
textToChange.text = "Changed to: " + data
}
}

Text {
id: textToChange
text: "beforeChange"
}
}

//yourClass.h
class YourClass : public QObject
{
signals:
// Signal from YourClass to QML
void signalData(QString data);
}

//yourClass.cpp
emit signalData("Hello QML"); // Signal from GAPI to QML

本页 https://felgo.com/cross-platform-development/how-to-expose-a-qt-cpp-class-with-signals-and-slots-to-qml包含有关“如何将带有信号和插槽的Qt C++类公开到QML”的完整教程。

关于c++ - 如何使用C++更新QML文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com