IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Qt Quick Discussion :

Envoyer des informations de C++ vers QML [Débuter]


Sujet :

Qt Quick

  1. #1
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Juillet 2012
    Messages
    24
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2012
    Messages : 24
    Points : 16
    Points
    16
    Par défaut Envoyer des informations de C++ vers QML
    Bonjour,

    Je m' entraine sur quelques exemples qml sous gnu/linux
    Je n ai pas rencontré trop de problemes dans mes exercices precedents, par contre je bute sur celui de "dialcontrol"



    Je voulais remplacer le slider par le monitoring du cpu load mais impossible d' y parvenir, le dialcontrol reste inactif.

    " ReferenceError: Can't find variable: loadcpu"

    cpuload.h
    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
     
    #ifndef CPULOAD_H
    #define CPULOAD_H
    #include <QList>
    #include <QByteArray>
    #include <QObject>
     
    class CPULoad : public QObject
     
    {
        Q_OBJECT
     
    public:
        explicit CPULoad(QObject *parent = 0);
     
        void init();
     
        void update();
     
        Q_INVOKABLE int  cpuLoad() const;
     
    private:
     
        typedef QList<QByteArray> TimeList;
     
        CPULoad(const CPULoad &);
     
        CPULoad & operator= (const CPULoad &);
     
        TimeList  readTimeList();
     
    private:
     
        TimeList   m_timeList;
     
        int        m_load;
     
        static int m_forcedLoad;
     
    };
     
    #endif // CPULOAD_H

    cpuload.cpp

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
     
    #include "cpuload.h"
    #include <QFile>
    #include <QDebug>
     
    /*!
     
     * \class CPULoad
     
     * \brief CPULoad calculates the current CPU load.
     
     */
     
    int CPULoad::m_forcedLoad = -1;
     
    //! Constructor
     
    CPULoad::CPULoad(QObject *parent) :
     
        m_load(-1)
     
    {}
     
    /*!
     
     * Reads /proc/stat file
     
     * ToDo: use sscanf if it faster
     
     */
     
    CPULoad::TimeList CPULoad::readTimeList()
     
    {
     
    #ifdef Q_OS_LINUX
     
        QFile fin(QString("/proc/stat"));
     
        if (fin.open(QIODevice::ReadOnly | QIODevice::Text))
     
            return fin.readLine().split(' ');
     
    #endif
     
        return TimeList();
     
    }
     
    /*!
     
     * Initialize. Currently only sets the value to -1.
     
     */
     
    void CPULoad::init()
     
    {
     
        m_load = -1;
     
    }
     
    /*!
     
     * Update the value.
     
     * This must be called periodically (e.g. 1 - 5 seconds) in order to update the measurement.
     
     * The data is obtained from first line of /proc/stat file
     
     */
     
    void CPULoad::update()
     
    {
     
        // Read timing from the file
     
        TimeList v(readTimeList());
     
        if (m_timeList.length()) {
     
            // Take delta with the previous timing
     
            int sum  = 0;
     
            int idle = 0;
     
            int iowait = 0;
     
            int cpu = 0;
     
            for (int i = 2; i < 7 && i < v.length(); i++)
     
                sum += v.at(i).toInt() - m_timeList.at(i).toInt();
     
            idle = v.at(5).toInt() - m_timeList.at(5).toInt();
     
            iowait = v.at(6).toInt() - m_timeList.at(6).toInt();
     
            cpu = sum - idle - iowait;
     
            // Calculate load
     
            m_load = 100.0 - (100.0 * idle / sum);
     
        } else {
     
            m_load = -1;
     
        }
     
        // Store the current timing
     
        m_timeList = v;
     
    }
     
    /*!
     
     * Returns The current value of the load in the range of 0 to 100
     
     * or -1 if nothing measured.
     
     */
     
    int CPULoad::cpuLoad() const
     
    {
     
        return m_forcedLoad > -1 ? m_forcedLoad : m_load;
     
    }

    main.cpp
    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    #include "cpuload.h"
     
    Q_DECL_EXPORT int main(int argc, char *argv[])
    {
        QScopedPointer<QApplication> app(createApplication(argc, argv));
     
        QmlApplicationViewer viewer;
        viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
        viewer.setMainQmlFile(QLatin1String("qml/conkycloneqml/main.qml"));
        viewer.showExpanded();
     
        CPULoad execProcess;
        QDeclarativeView view;
        QDeclarativeContext *context = view.rootContext();
        context->setContextProperty("loadcpu", &execProcess);
     
        return app->exec();
    }

    main.qml (ligne 117-120)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
     
    /****************************************************************************
    **
    ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
    ** Contact: http://www.qt-project.org/
    **
    ** This file is part of the examples of the Qt Toolkit.
    **
    ** $QT_BEGIN_LICENSE:BSD$
    ** You may use this file under the terms of the BSD license as follows:
    **
    ** "Redistribution and use in source and binary forms, with or without
    ** modification, are permitted provided that the following conditions are
    ** met:
    **   * Redistributions of source code must retain the above copyright
    **     notice, this list of conditions and the following disclaimer.
    **   * Redistributions in binary form must reproduce the above copyright
    **     notice, this list of conditions and the following disclaimer in
    **     the documentation and/or other materials provided with the
    **     distribution.
    **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
    **     the names of its contributors may be used to endorse or promote
    **     products derived from this software without specific prior written
    **     permission.
    **
    ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
    **
    ** $QT_END_LICENSE$
    **
    ****************************************************************************/
     
    //! [imports]
    import QtQuick 1.0
    import Qt 4.7
    import "content"
    //! [imports]
     
    //! [0]
    Rectangle {
        color: "#545454"
        width: 300; height: 300
     
        // Dial with a slider to adjust it
        Dial {
            id: dial
            x: -42
            y: -42
            width: 210
            height: 210
            anchors.verticalCenterOffset: -87
            anchors.horizontalCenterOffset: -87
            scale: 0.600
            anchors.centerIn: parent
            value: slider.x * 100 / (container.width - 34)
     
        }
     
        Rectangle {
            id: container
            anchors { bottom: parent.bottom; left: parent.left
                right: parent.right; leftMargin: 20; rightMargin: 20
                bottomMargin: 10
            }
            height: 16
     
            radius: 8
            opacity: 0.7
            smooth: true
            gradient: Gradient {
                GradientStop { position: 0.0; color: "gray" }
                GradientStop { position: 1.0; color: "white" }
            }
     
            Rectangle {
                id: slider
                x: 1; y: 1; width: 30; height: 14
                radius: 6
                smooth: true
                gradient: Gradient {
                    GradientStop { position: 0.0; color: "#424242" }
                    GradientStop { position: 1.0; color: "black" }
                }
     
                MouseArea {
                    anchors.fill: parent
                    anchors.margins: -16 // Increase mouse area a lot outside the slider
                    drag.target: parent; drag.axis: Drag.XAxis
                    drag.minimumX: 2; drag.maximumX: container.width - 32
                }
            }
        }
        QuitButton {
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.margins: 10
        }
     
        Dial {
            id: dial1
            x: 84
            y: -42
            width: 210
            height: 210
            anchors.verticalCenterOffset: -87
            anchors.horizontalCenterOffset: 39
            anchors.centerIn: parent
            //value: dial1.value = loadcpu.cpuLoad()
            scale: 0.600
            onValueChanged{
                loadcpu.cpuLoad();
            }
        }
    }
    //! [0]

    http://qt.gitorious.org/qtplayground...b01fe/src/core

    Si vous aviez l' amabilitée de m' orienter sur la facon de proceder?
    Merci d' avance.
    Je debute et cela n' est pas evident pour moi.

  2. #2
    Rédacteur
    Avatar de Amnell
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2009
    Messages
    1 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2009
    Messages : 1 840
    Points : 5 545
    Points
    5 545
    Par défaut
    Bonsoir,

    Le problème est que vous avez créé une QDeclarativeView vide dans laquelle vous avez assigné la propriété contextuelle "loadcpu" au lieu de l'assigner au QmlApplicationViewer (une classe dérivée de QDeclarativeView) qui charge les fichiers QML. De ce fait, remplacez :

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
        QmlApplicationViewer viewer;
        viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
        viewer.setMainQmlFile(QLatin1String("qml/conkycloneqml/main.qml"));
        viewer.showExpanded();
     
        CPULoad execProcess;
        QDeclarativeView view;
        QDeclarativeContext *context = view.rootContext();
        context->setContextProperty("loadcpu", &execProcess);

    Par :

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
        CPULoad execProcess;
     
        QmlApplicationViewer viewer;
        viewer.rootContext()->setContextProperty("loadcpu", &execProcess);
        viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
        viewer.setMainQmlFile(QLatin1String("qml/conkycloneqml/main.qml"));
        viewer.showExpanded();

    Cela devrait fonctionner.

    Bonne soirée,
    Amnell.

  3. #3
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Juillet 2012
    Messages
    24
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2012
    Messages : 24
    Points : 16
    Points
    16
    Par défaut
    Un grand merci à vous, en effet le probleme etait bien la.

    Par contre j ai voulu verifier la valeur cpu dans un Qlabel et il me retourne tjrs la valeur -1

    le cpuload.cpp et .h viennent de:

    http://qt.gitorious.org/qtplayground...b01fe/src/core


  4. #4
    Rédacteur
    Avatar de Amnell
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2009
    Messages
    1 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2009
    Messages : 1 840
    Points : 5 545
    Points
    5 545
    Par défaut
    Bonjour,

    Si vous lancez le programme sous autre chose que Linux, ça me semble logique vu que la fonction CPULoad::readTimeList() retourne une liste vide. La variable membre m_load contiendra donc -1 vu qu'il n'entrera pas dans la condition if (m_timeList.length()). Le cas échéant, vérifiez votre /proc/stat, que vous appelez bien périodiquement update() et/ou bien montrez-moi le fichier QML.

    Bonne continuation,
    Amnell.

  5. #5
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Juillet 2012
    Messages
    24
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2012
    Messages : 24
    Points : 16
    Points
    16
    Par défaut
    Tout se fait sous gnu/linux, ubuntu 12.10 pour dev, 12.04 et archlinux pour tester.

    Voici le qml (qmllabel est un rajout entre temps donc n' en tenez pas rigueure.)

    qml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
     
     
    //! [imports]
    import QtQuick 1.0
    import Qt 4.7
    import "content"
    import qmlLabel 1.0
    //! [imports]
     
    //! [0]
    Rectangle {
        color: "#545454"
        width: 300; height: 300
     
        QmlLabel {
            id: label1
                x:150; y:150
                width: 100
                height: 24
                text: loadcpu.cpuLoad()
                //text: loadcpu.update()
                //text: "UnTest test"
                z: 1
        }
     
        // Dial with a slider to adjust it
        Dial {
            id: dial
            x: -42
            y: -42
            width: 210
            height: 210
            anchors.verticalCenterOffset: -87
            anchors.horizontalCenterOffset: -87
            scale: 0.600
            anchors.centerIn: parent
            value: slider.x * 100 / (container.width - 34)
     
        }
     
        Rectangle {
            id: container
            anchors { bottom: parent.bottom; left: parent.left
                right: parent.right; leftMargin: 20; rightMargin: 20
                bottomMargin: 10
            }
            height: 16
     
            radius: 8
            opacity: 0.7
            smooth: true
            gradient: Gradient {
                GradientStop { position: 0.0; color: "gray" }
                GradientStop { position: 1.0; color: "white" }
            }
     
            Rectangle {
                id: slider
                x: 1; y: 1; width: 30; height: 14
                radius: 6
                smooth: true
                gradient: Gradient {
                    GradientStop { position: 0.0; color: "#424242" }
                    GradientStop { position: 1.0; color: "black" }
                }
     
                MouseArea {
                    anchors.fill: parent
                    anchors.margins: -16 // Increase mouse area a lot outside the slider
                    drag.target: parent; drag.axis: Drag.XAxis
                    drag.minimumX: 2; drag.maximumX: container.width - 32
                }
            }
        }
        QuitButton {
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.margins: 10
        }
     
        Dial {
            id: dial1
            x: 84
            y: -42
            width: 210
            height: 210
            anchors.verticalCenterOffset: -87
            anchors.horizontalCenterOffset: 39
            anchors.centerIn: parent
            value: dial1.value = loadcpu.update()
            scale: 0.600
            //onValueChanged: {loadcpu.cpuLoad();}
        }
    }
    //! [0]
    Cordialement.

  6. #6
    Rédacteur
    Avatar de Amnell
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2009
    Messages
    1 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2009
    Messages : 1 840
    Points : 5 545
    Points
    5 545
    Par défaut
    Bonsoir,

    De ce fait, vous n'avez aucun appel à update() dans votre code, d'où le -1. De plus, vous faites :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    text: loadcpu.cpuLoad()
    Ainsi, la propriété est définie statiquement (au lancement) et ne changera jamais.

    Je vous propose une petite modification du début du QML pour faire marcher le label, je vous laisserai ajuster le reste du code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
     
    Rectangle {
        color: "#545454"
        width: 300; height: 300
     
        // Définition d'une propriété par commodité
        property int currentCpuValue: -1
     
        // Création d'un timer qui va appeler update() toutes les 2sec et
        // modifier la valeur de la propriété currentCpuValue
        Timer {
            running: true
            repeat: true
            interval: 2000
            onTriggered{
                loadcpu.update();
                currentCpuValue = loadcpu.cpuLoad();
            }
        }
     
        QmlLabel {
            id: label1
            x: 150; y: 150
            width: 100
            height: 24
            text: currentCpuValue // On lie le texte dynamiquement à la valeur de la propriété
            z: 1
        }
    Il sera nécessaire de marquer Q_INVOKABLE la méthode update() de la classe CPULoad.

    L'intérêt de passer par une propriété intermédiaire est d'éviter de la duplication de code et de multiples appels inutiles aux méthodes du CPULoad. Là, on va juste modifier toutes les deux secondes une propriété currentCpuValue, et toutes les propriétés liées à cette dernière (exemple : par "text: currentCpuValue") vont être automatiquement mises à jour (car quand une propriété est modifiée, elle émet un signal NOTIFY informant les propriétés y étant liées dans le QML de se mettre à jour et de recalculer leur valeur, en gros). L'alternative aurait été de modifier toutes les propriétés à la main dans onTriggered, ce qui n'aurait pas été très joli.

    Bonne continuation,
    Amnell.

  7. #7
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Juillet 2012
    Messages
    24
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Juillet 2012
    Messages : 24
    Points : 16
    Points
    16
    Par défaut

    Un grand merci à vous, car sans votre aide je n' aurais pas pu m' en sortir.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Envoyer des information instantanées du controlleur vers la vue
    Par Ludoztw dans le forum Zend Framework
    Réponses: 2
    Dernier message: 15/04/2015, 16h59
  2. Envoyer des informations vers 2 urls
    Par luffyfr dans le forum Langage
    Réponses: 2
    Dernier message: 16/05/2011, 17h20
  3. [XL-2003] Envoyer des informations de Excel vers Internet Explorer
    Par Banosjo dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 17/04/2011, 21h39
  4. Envoyer des informations en POST vers une url en vb6
    Par bugz57 dans le forum VB 6 et antérieur
    Réponses: 14
    Dernier message: 18/06/2008, 08h59
  5. envoyer des informations du controleur vers la vue
    Par leon1983 dans le forum Servlets/JSP
    Réponses: 1
    Dernier message: 22/05/2008, 15h36

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo