我认为我的问题非常简单。然而,我无法弄明白。我的TextArea
文件中定义了.qml
,需要从C ++代码动态更新。
很遗憾,我不知道如何从TextArea
类中访问/更新imserver.cpp
。
有人可以帮帮我吗?
这是.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);
}
答案 0 :(得分:2)
有几种方法。我就是这样做的。
首先,您应该注册您的IMServer类:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
txtTeacherId cannot be resolved
txtTeacherName cannot be resolved
cmbDepName cannot be resolved
txtTeacherCnicNo cannot be resolved
txtTeacherCellNo cannot be resolved
at NewTry.main(NewTry.java:17)
然后将IMServer实例添加到QML:
qmlRegisterUncreatableType<IMServer>("App", 1, 0, "IMServer", "");
然后你的IMServer类需要一个信号,你的TextArea可以连接到,或者甚至更好地添加一个属性(你需要在这里添加getText()函数和textChanged()信号,以获得只读属性):
更新:
enigne.rootContext()->setContextProperty("imserver", &server);
然后,您可以在TextArea中创建绑定:
Q_PROPERTY(QString text READ getText NOTIFY textChanged)
然后,只要在IMServer类中发出textChanged,TextArea的文本就会更新。 有关详细信息:http://doc.qt.io/qt-5/qtqml-cppintegration-topic.html