Qt Qml连接到Context属性的QObject属性的信号

时间:2017-11-16 06:35:06

标签: c++ qt qml qt-signals qproperty

所以这可能看起来像一个奇怪的设置。我有一个C ++对象,它继承自QObject,名为" MasterGuiLogic"为简单起见。它是用指向另一个名为" MainEventBroker"的对象的指针创建的。正如您可能猜到的那样处理我的所有应用程序事件。 MasterGuiLogic对象在qml中注册为上下文属性,因此它的属性可以在我的qml中的任何位置使用。所以main.cpp看起来像这样:

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    MasterEventBroker *MainEventBroker = new MasterEventBroker();
    MasterGuiLogic *MainGuiLogic = new MasterGuiLogic(*MainEventBroker);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;
    QQmlContext* context = engine.rootContext();

    context->setContextProperty("MasterGuiLogic", &(*MainGuiLogic));

    engine.load(QUrl(QLatin1String("qrc:/QmlGui/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

MasterGuiLogic创建另一个名为SerialCom的类的实例,该类设置为Q_PROPERTY,以便通过MasterGuiLogic属性可以在qml中访问它的属性和公共槽。

MasterGuiLogic.h:

class MasterGuiLogic : public QObject
{
    Q_OBJECT
    Q_PROPERTY(GuiLogic_SerialCom* serialCom READ serialCom CONSTANT)
public:
    MasterEventBroker *eventBroker;

    explicit MasterGuiLogic(MasterEventBroker &ev, QObject *parent = nullptr);


    GuiLogic_SerialCom* serialCom() const {
        return Gui_SerialCom;
    }

private:

    GuiLogic_SerialCom *Gui_SerialCom;

MasterGuiLogic.cpp:

MasterGuiLogic::MasterGuiLogic(MasterEventBroker &ev, QObject *parent) : QObject(parent)
{
    this->eventBroker = &ev;
    this->Gui_SerialCom = new GuiLogic_SerialCom(this);
}

SerialCom.h:

//Forward Declare our parent
class MasterGuiLogic;

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QStringList portNames READ portNames NOTIFY portNamesChanged)
    Q_PROPERTY(bool connectedToPort READ connectedToPort NOTIFY connectedToPortChanged)
public:

    MasterGuiLogic *parent;
    explicit GuiLogic_SerialCom(MasterGuiLogic *parent = nullptr);

    std::map<QString, QSerialPortInfo> portsMap;


    QStringList portNames() {
        return _portNames;
    }

    bool connectedToPort() {
        return _connectedToPort;
    }

private:

    QStringList _portNames;
    bool _connectedToPort = false;


signals:

    void portNamesChanged(const QStringList &);
    void connectedToPortChanged(const bool &);

public slots:

    void connectToPort(const QString portName);
    void disconnectFromPort(const QString portName);

};

SerialCom.cpp:

GuiLogic_SerialCom::GuiLogic_SerialCom(MasterGuiLogic *parent) : QObject(qobject_cast<QObject *>(parent))
{
    this->parent = parent;


    QList<QSerialPortInfo> allPorts = QSerialPortInfo::availablePorts();

    for (int i = 0; i < allPorts.size(); ++i) {
        this->_portNames.append(allPorts.at(i).portName());
        this->portsMap[allPorts.at(i).portName()] = allPorts.at(i);
    }

    emit portNamesChanged(_portNames);

}

void GuiLogic_SerialCom::connectToPort(const QString portName) {
    //TODO: Connect To Port Logic Here;

    //Set Connected
    this->_connectedToPort = true;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

void GuiLogic_SerialCom::disconnectFromPort(const QString portName) {
    //TODO: DisConnect To Port Logic Here;

    //Set DisConnected
    this->_connectedToPort = false;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

因此,从qml开始,它很容易读取任何这些属性,甚至可以将信号从qml发送到c ++

例如,这很好用:

connectCom.onClicked: {
        if (MasterGuiLogic.serialCom.connectedToPort === false) {
            MasterGuiLogic.serialCom.connectToPort(comPort.currentText);
        } else {
            MasterGuiLogic.serialCom.disconnectFromPort(comPort.currentText);
        }
    }

问题是,我似乎无法找到一种方法来连接从SerialCom发出的信号。我以为我可以做这样的事情:

Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            if (MasterGuiLogic.serialCom.connectedToPort === false) {
                connectCom.text = "Disconnect";
                comPort.enabled = false;
            } else {
                connectCom.text = "Connect";
                comPort.enabled = true;
            }
        }
    }

这应该监听SerialCom上的boolean属性进行更改,但是我收到以下错误:

QQmlApplicationEngine failed to load component
qrc:/QmlGui/main.qml:21 Type Page1 unavailable
qrc:/QmlGui/Page1.qml:49 Invalid attached object assignment

这只是意味着我无法连接&#34;使用上面的目标线。有没有其他方法可以连接到ContextProperty中QObject类型的Q_PROPERTY的信号?

2 个答案:

答案 0 :(得分:1)

首先应该&(*MainGuiLogic)是什么意思? 您正在取消引用并再次引用MainGuiLogic?为什么呢?

context->setContextProperty("MasterGuiLogic", MainGuiLogic);将被采纳。

但是将MasterGuiLogic注册为 Type 并添加名为MasterGuiLogic Object 可以在QML世界中自我覆盖。

将其设置为context->setContextProperty("MyGuiLogic", MainGuiLogic);以消除此行为。

也不要在C ++和QML世界之间传递引用,例如:

void connectedToPortChanged(**const bool &**);

只使用原子类型和值(const bool); 并给它一个名称,以便能够在QML中将其用作命名值

void connectedToPortChanged(bool connected)

这是一个像你这样的结构的例子,它有效。只需在窗口中单击并查看输出控制台即可。

<强> test.h

#ifndef TEST_H
#define TEST_H

#include <QObject>

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
public:
    GuiLogic_SerialCom(){}

signals:
    void connectedToPortChanged(bool connected);

public slots:
    void connectToPort(const QString & portName);
};

class MasterGuiLogic : public QObject
{
    Q_OBJECT
public:
    MasterGuiLogic();

    Q_PROPERTY(GuiLogic_SerialCom * serialCom READ serialCom CONSTANT)
    GuiLogic_SerialCom* serialCom() const {return test;}

    Q_INVOKABLE void generate_signal();

private:
    GuiLogic_SerialCom * test;
};

#endif // TEST_H

<强> TEST.CPP

#include "test.h"
#include <QDebug>

MasterGuiLogic::MasterGuiLogic()
{
    this->test = new GuiLogic_SerialCom();
}

void MasterGuiLogic::generate_signal()
{
    qDebug() << __FUNCTION__ << "Calling serialcom to gen signal";
    this->test->connectToPort("88");
}


void GuiLogic_SerialCom::connectToPort(const QString &portName)
{
    qDebug() << __FUNCTION__ << "got signal" << portName;
    emit this->connectedToPortChanged(true);
}

<强>的main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty(QStringLiteral("Test"), new MasterGuiLogic());

    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

<强> main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

import GrblCom 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            Test.generate_signal();
        }
    }

    Connections
    {
        target: Test.serialCom
        onConnectedToPortChanged:
        {
            console.log("Got signal from SerialCom in QML. passed bool value is: " + connected);
        }
    }
}

答案 1 :(得分:1)

好的,我发现了问题......提供的答案虽然确实有其他原因,但并不是正确的解决方案。在通过@Xplatforms翻阅代码之后,我无法弄清楚我在做什么和他做了什么之间的区别......直到我在自己的代码中看到这个:

Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            ...
        }
    }

不应该有冒号(:) ......

Connections {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            ...
        }
    }

永远不要在困倦时尝试编程... lol