سلام
من از کد زیر برای نمایش آنلاین دیتاهای پورت سریال در کنترل Txet فرم استفاده کردم. آیا این بهترین روشه؟ شما روش و یا کد دیگه ای توصیه می کنید که کارایی برنامه بالاتر بره؟
main.cpp:
int main(int argc, char *argv[]){
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
MyDisplay myDisplay;
myDisplay.setText("neda");
engine.rootContext()->setContextProperty("myDisplay", &myDisplay);
MySerialPort iSerialPort;
iSerialPort.setDisplay(&myDisplay);
iSerialPort.openSerialPort();
return app.exec();
}
mydisplay.h:
class MyDisplay : public QObject{
Q_OBJECT
Q_PROPERTY(QString newText READ getText WRITE setText NOTIFY textChanged)
public:
MyDisplay();
MyDisplay(QString);
Q_INVOKABLE QString getText() const;
public slots:
void setText(QString text);
signals:
void textChanged(QString);
private:
QString newText;
};
mydisplay.cpp:
#include "mydisplay.h"#include "qstring.h"
MyDisplay::MyDisplay()
{
newText = "";
}
MyDisplay::MyDisplay(QString text)
{
newText = text;
}
QString MyDisplay::getText() const
{
return newText;
}
void MyDisplay::setText(QString text)
{
if (text != newText)
{
newText = text;
emit textChanged(text);
}
}
serialport.cpp:
void MySerialPort::readData(){
QByteArray data = serial->readAll();
qDebug() << data;
QString dataString=data;
myDisplay->setText(dataString);
}
void MySerialPort::setDisplay(MyDisplay * m_display)
{
myDisplay = m_display;
}
main.qml:
ApplicationWindow { visible: true
width: 640
height: 480
title: qsTr("Hello World")
Text {
id: text1Text
//objectName: text1Text
width: 400
height: 29
color: "red"
text: myDisplay.newText
font.pixelSize: 12
}
}