[英]Update TextArea in QML from C++
我的問題很簡單。 但是,我無法弄清楚。 我在.qml
文件中定義了一個TextArea
,需要從C ++代碼動態更新。
不幸的是,我不知道如何從imserver.cpp
類中訪問/更新TextArea
。
有人可以幫我嗎?
這是.qml文件:
import QtQuick 2.2
import QtQuick.Controls 1.1
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("IMServer")
menuBar: MenuBar {
Menu {
title: qsTr("File")
MenuItem {
text: qsTr("Exit")
onTriggered: Qt.quit();
}
}
}
TextArea {
id: serverInformation
x: 0
y: 0
width: 247
height: 279
}
}
我的main.cpp:
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include "imserver.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
IMServer server(2000);
qmlRegisterUncreatableType<IMServer>("App", 1, 0, "IMServer", "");
engine.rootContext()->setContextProperty("imserver", &server);
server.startServer();
return app.exec();
}
imserver.h
#ifndef IMSERVER_H
#define IMSERVER_H
#include <QTcpServer>
#include <QTcpSocket>
#include <QAbstractSocket>
#include <QThreadPool>
class IMServer : public QTcpServer {
Q_OBJECT
Q_PROPERTY(QString text WRITE setText NOTIFY textChanged)
public:
explicit IMServer(int port, QObject *parent = 0);
void startServer();
void setText(const QString &txt);
signals:
void textChanged();
public slots:
protected:
void incomingConnection(qintptr fd);
private:
int port;
QThreadPool *pool;
QString m_text;
};
#endif // IMSERVER_H
imserver.cpp:
#include "imserver.h"
#include "clienthandler.h"
IMServer::IMServer(int port, QObject *parent) : QTcpServer(parent) {
this->pool = new QThreadPool(this);
this->pool->setMaxThreadCount(100);
this->port = port;
}
void IMServer::startServer() {
setText("TEST");
if (!this->listen(QHostAddress::Any, this->port)) {
qDebug() << "Server could not be started";
} else {
qDebug() << "Server started, listening...";
}
}
void IMServer::setText(const QString &txt) {
m_text = txt;
emit textChanged();
}
void IMServer::incomingConnection(qintptr fd) {
ClientHandler *client = new ClientHandler();
client->setAutoDelete(true);
client->fd = fd;
this->pool->start(client);
}
有幾種方法。 這是我的方法。
首先,您應該注冊您的IMServer類:
qmlRegisterUncreatableType<IMServer>("App", 1, 0, "IMServer", "");
然后,將您的IMServer實例添加到QML:
enigne.rootContext()->setContextProperty("imserver", &server);
然后,您的IMServer類需要一個信號,您的TextArea可以連接到該信號,甚至更好地添加一個屬性(對於只讀屬性,您還需要在此處添加getText()函數和textChanged()信號):
更新:
Q_PROPERTY(QString text READ getText NOTIFY textChanged)
然后,您可以在TextArea中創建綁定:
TextArea {
text: imserver.text
}
然后,無論何時在IMServer類中發出textChanged,TextArea的文本都會被更新。 有關更多信息: http : //doc.qt.io/qt-5/qtqml-cppintegration-topic.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.