Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. Hi, I have a qml integrate problem

Hi, I have a qml integrate problem

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
4 Posts 2 Posters 197 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • E Offline
    E Offline
    erdemaksyy
    wrote on last edited by
    #1

    I am receiving different data with RTOS over the serial port and I want to show this data on the screen, but somehow I cannot achieve this. I will be grateful if you could help me. I am sharing the files with you.

    CommSerial.h

    #ifndef COMMSERIAL_H
    #define COMMSERIAL_H
    #pragma once
    #include <QObject>
    
    #include <QThread>
    #include <QObject>
    #include <QSerialPort>
    #include <QVariant>
    #include <QTimer>
    
    #include "qmlworker.h"
    
    Q_DECLARE_METATYPE(QSerialPort::SerialPortError)
    
    class CommSerial : public QObject
    {
        Q_OBJECT
    public:
        CommSerial();
        int gaugeValue;
    
    /* serial okuma */
    signals:
        void bytesReceived(CommSerial* link, QByteArray data);
        void calculatedGauge(QVariant deger);
    
    /* Serial ile aldigim veriler icin kulanacagim fonksiyonlari tanimladim */
    private slots:
        void _readBytes();
        void SplitDataet();
        void SplitDatadolar();
    
    /* haberlesme icin kullanilacak data typelar tanimladim */
    private:
          QSerialPort *m_port;
          QThread *m_serialThread;
    
          QString serialBuffer;
          QByteArray serialData;
          QString parsed_data;
          QByteArray buffer;
    
          QString serialBuffer_;
          QByteArray serialData_;
          QString parsed_data_;
          QByteArray buffer_;
    
          QThread *workerThread;
    
    };
    
    #endif // COMMSERIAL_H
    
    

    QmlWorker.h

    #ifndef QMLWORKER_H
    #define QMLWORKER_H
    
    #include <QObject>
    #include <QVariant>
    
    class QmlWorker : public QObject
    {
        Q_OBJECT
    public:
        QmlWorker();
        int mInput;
    public slots:
        void setInput(QVariant result);
    
    signals:
        void resultReady(QVariant result);
    
    };
    
    #endif // QMLWORKER_H
    
    

    CommSerial.cpp

    #include <commserial.h>
    #include <QThread>
    #include <QSerialPort>
    #include <QCoreApplication>
    
    #include<iostream>
    #include <sstream>
    #include <string>
    
    #include <QDebug>
    
    using namespace std;
    QmlWorker worker;
    
    CommSerial::CommSerial()
        : QObject(nullptr)
    {
    
        m_serialThread = new QThread();     /* Thread icin tanimlama yaptim */
        workerThread = new QThread();
        m_port = new QSerialPort("ttyUSB0", nullptr); /* Serial için Port tanimlama yaptim */
    
    
    
        //deneme->start();
    
        /* Serial icin baglantilari yaptim */
        QObject::connect(m_port, &QIODevice::readyRead, this, &CommSerial::_readBytes, Qt::QueuedConnection);
        QObject::connect(m_port, &QIODevice::readyRead, this, &CommSerial::SplitDataet, Qt::QueuedConnection);
        QObject::connect(m_port, &QIODevice::readyRead, this, &CommSerial::SplitDatadolar, Qt::QueuedConnection);
    
    
       // connect(worker, &QmlWorker::resultReady, worker, &QObject::deleteLater);
    
    
        /* thread ile port kontrolu yaptim */
        for (int openRetries = 0; openRetries < 3; openRetries++) {
            if (!m_port->open(QIODevice::ReadWrite)) {
                for (unsigned i = 0; i < 50; i++) {
                    QThread::msleep(5);
                    qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
                }
                qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
            } else {
                break;
            }
        }
    
        if (!m_port->isOpen() ) {
    
            m_port->close();
            delete m_port;
            m_port = NULL;
        }
    
        /* Konfigre ayarlarini yaptim ve haberlesmeyi hazir duruma getirdim */
        m_port->setDataTerminalReady(true);
    
        m_port->setBaudRate     (QSerialPort::Baud9600);
        m_port->setDataBits     (QSerialPort::Data8);
        m_port->setFlowControl  (QSerialPort::SoftwareControl);
        m_port->setStopBits     (QSerialPort::OneStop);
        m_port->setParity       (QSerialPort::NoParity);
    
    
        /* moveToThread = ***fonksiyona bir daha bak */
    
        //worker->thread();
        // as soon as we move worker to another thread, its thread should change
    
    
    
    
    
        worker.moveToThread(workerThread);
    
        m_port->moveToThread(m_serialThread);
        this->moveToThread(m_serialThread);
    
        m_serialThread->start(); /* thread baslatarak ayni anda birden fazla fonksiyon baslattim */
        workerThread->start();
    }
    
    /* Serial okuma yapildi */
    void CommSerial::_readBytes(void)
    {
        if (m_port && m_port->isOpen())
        {
            if (m_port && m_port->isOpen())
            {
                qint64 byteCount = m_port->bytesAvailable();
                if (byteCount)
                {
                    buffer.resize(byteCount);
                    m_port->read(buffer.data(), buffer.size());
                    emit bytesReceived(this, buffer);
                }else{
                }
            }
        }
    }
    
    /* @ ile baslayan veriler icin parcalama yaptim */
    void CommSerial::SplitDataet()
    {
        QStringList buffer_split = serialBuffer.split("@");
        if(buffer_split.length() < 3)
        {
            serialData = buffer;
            serialBuffer = serialBuffer + QString::fromStdString(serialData.toStdString());
            serialData.clear();
        }else{
            if(buffer_split[2] == "")
            {
                serialBuffer = "";
                QStringList x = buffer_split[1].split("$");
                parsed_data = x[0];
                gaugeValue = parsed_data.toInt();
                parsed_data = QString::number(gaugeValue, 'g', 4);
                worker.setInput(QVariant(gaugeValue));
    
                //qDebug()<<"hiz = " <<gaugeValue << endl;
            }
        }
    
    
    }
    
    
    /* $ ile baslayan veriler icin parcalama yaptim */
    void CommSerial::SplitDatadolar()
    {
    
        QStringList buffer_split_ = serialBuffer_.split("$");
    
        if(buffer_split_.length() < 3){
    
            serialData_ = buffer;
            serialBuffer_ = serialBuffer_ + QString::fromStdString(serialData_.toStdString());
            serialData_.clear();
    
        }else{
            if(buffer_split_[2] == "")
            {
                serialBuffer_ = "";
                //qDebug() << buffer_split_ << "\n";
                QStringList y = buffer_split_[1].split("@");
                parsed_data_ = y[0];
                //qDebug()<<"sinyaller = " <<parsed_data_ << endl;
            }
        }
    
    }
    
    
    
    

    QmlWorker.cpp

    #include "qmlworker.h"
    #include <QThread>
    #include <QDebug>
    #include <QVariant>
    
    QmlWorker::QmlWorker()
    {
    
    }
    
    void QmlWorker::setInput(QVariant result)
    {
        mInput = result.toInt();
        emit resultReady(QVariant(mInput));
        qDebug() << "Input string: " << mInput;
    
    }
    
    

    main.cpp

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QVariant>
    #include <QThread>
    #include <QDebug>
    #include "commserial.h"
    #include "qmlworker.h"
    #include <QQmlContext>
    
    #include <QSharedPointer>
    int main(int argc, char *argv[])
    {
    #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        CommSerial *serial = new CommSerial;
        //QmlWorker qml;
    
    
        //QQmlContext * rootContext = engine.rootContext();
        //engine.rootContext() -> setContextProperty("qml",&qml);
    
        qmlRegisterType<QmlWorker> ("erdo.classA",1,0,"Dlg"); /* qml ile c++ entegre ettim */
    
        //localThread->changeGaugeValue(MyThread().gaugeValue);
        //qmlRegisterType<QmlWorker> ("erdo.classA",1,0,"Dlg"); /* qml ile c++ entegre ettim */
    
        //engine.rootContext()->setContextProperty("CommSerial",&serial);
       /* engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        engine.thread()->setObjectName("MainThread");
    
        if (engine.rootObjects().isEmpty())
            return -1;*/
    
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
    
        engine.load(url);
    
    
        return app.exec();
    
    
    }
    
    

    main.qml

    import QtQuick 2.15
    import QtQuick.Window 2.15
    import QtQuick.VirtualKeyboard 2.15
    import QtQuick.Extras 1.4
    import QtQuick.Controls.Styles 1.4
    import QtQuick.Controls 2.12
    
    import erdo.classA 1.0
    
    Window
    {
        id: window
        width: 800
        height: 800
        visible: true
        property int hiz
    
        Dlg
        {
            id: dlg
            onResultReady: (result) =>
                           {
                               hiz = result
                           }
    
        }
    
        Rectangle
        {
          id: dashboard
          anchors.centerIn: parent
          height: 500
          width: 1000
          color: "black"
    
    
        Row
        {
          id: dashboardRow
          spacing: dashboard.width * 0.02
          anchors.centerIn: parent
    
          TextEdit {
              id: gear
          }
    
    
        CircularGauge
        {
           id: speedometer
           value: hiz
           width: height
           height: dashboard.height * 0.6
           maximumValue: 100
    
           property bool acceleration: false
    
           style: GaugeDesign {}
    
           Behavior on value { NumberAnimation { duration: 1000 }}
           Component.onCompleted:  forceActiveFocus();
    
        }
    
        }
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi and welcome to devnet,

      You should explain exactly what you are expecting because "I cannot achieve" and read the whole code to help is not a nice way to ask for help.

      One suggestion to get started: remove all the threading code. Qt is asynchronous and most of the time, especially for serial port management, there's no need for any threads.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      E 1 Reply Last reply
      0
      • SGaistS SGaist

        Hi and welcome to devnet,

        You should explain exactly what you are expecting because "I cannot achieve" and read the whole code to help is not a nice way to ask for help.

        One suggestion to get started: remove all the threading code. Qt is asynchronous and most of the time, especially for serial port management, there's no need for any threads.

        E Offline
        E Offline
        erdemaksyy
        wrote on last edited by
        #3

        @SGaist Thank you very much for your nice welcome. I am reading the data with the Serial port, which I am trying to explain, but I cannot combine the data I read with qml and I do not get an error.
        Thank you again.

        1 Reply Last reply
        0
        • SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #4

          There's no data because there's nothing using your CommSerial object on the QML side.

          By the way, calling a C++ class QmlWorker and then naming it Dlg in your QtQuick code does not make your code easy to understand.

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          0

          • Login

          • Login or register to search.
          • First post
            Last post
          0
          • Categories
          • Recent
          • Tags
          • Popular
          • Users
          • Groups
          • Search
          • Get Qt Extensions
          • Unsolved