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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt Qml连接到Context属性的QObject属性的信号相关的知识,希望对你有一定的参考价值。

所以这可能看起来像一个奇怪的设置。为简单起见,我有一个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

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

答案

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

qazxsw我就够了。

但是将context->setContextProperty("MasterGuiLogic", MainGuiLogic);注册为Type并添加名为MasterGuiLogic的Object可以在QML世界中自我覆盖。

设置它像qazxsw poi来消除这种行为。

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

MasterGuiLogic

只需使用原子类型和值context->setContextProperty("MyGuiLogic", MainGuiLogic);;并给它一个名称,以便能够在QML中将其用作命名值:

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

这是一个像你的结构的例子,它的工作原理。只需单击窗口并查看输出控制台即可。

test.h:

(const bool)

TEST.CPP:

void connectedToPortChanged(bool connected)

main.cpp中:

#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

main.qml:

#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);
}
另一答案

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

#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();
}

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

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);
        }
    }
}

不要在困倦时尝试编程......哈哈

以上是关于Qt Qml连接到Context属性的QObject属性的信号的主要内容,如果未能解决你的问题,请参考以下文章

如何从 C++ 端连接到 QML 项目的 onClick 事件

javascript QML - 连接到属性更改事件的函数

将 QML 信号连接到 PySide2 插槽

Qt SSL:从 QML 发出的请求握手失败

Qt:将C ++类暴露给QML时出错

Qt5 - QML:如何正确连接 ProgressBar 和 Button 以进行长时间运行的循环计算