gpt4 book ai didi

c++ - 将信号从 QML 连接到 Qt : var to QList

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:55 26 4
gpt4 key购买 nike

我正在尝试将来自 QML 的信号连接到来自 Qt 的 SLOT。信号传递一个 QList 变量。

QML:

property var cases: ["A", "B", "C"]

signal casesClicked(list cases)

Qt:

d->m_view->setSource(QUrl("qrc:/qml/main.qml"));
d->m_item = d->m_view->rootObject();
QObject::connect(d->m_item, SIGNAL(casesClicked(QList<QString>)), this, SLOT(onCasesClicked(QList<QString>)));

我遇到的问题是我不知道如何从QML端声明QList,所以直接拿来了。如果我声明它:

signal casesClicked(var cases)

然后,信号未连接,如果我将其声明为列表或数组,它会显示 "Invalid signal parameter type: list/Array"

有什么建议吗?我对单个 int、bool 或 string 没有任何问题。谢谢,

最佳答案

我认为在 C++ 端建立连接是不合适的,因为在编译时它不知道 QML 中创建的信号,一个可能的解决方案是在 QML 端建立连接。下面我举个例子

main.cpp

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QDebug>
class Test: public QObject{
QQuickView *view;
Q_OBJECT
public:
Test(QObject *parent=Q_NULLPTR):QObject(parent)
{
view = new QQuickView;
view->rootContext()->setContextProperty("Test", this);
view->setSource(QUrl("qrc:/main.qml"));
view->show();
}
public slots:
void onCasesClicked(QVariantList cases){
qDebug()<<cases;
}
};

int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

QGuiApplication app(argc, argv);
Test test;
return app.exec();
}

#include "main.moc"

ma​​in.qml

import QtQuick 2.9

Item {
id: it
visible: true
width: 640
height: 480

signal casesClicked(var cases)

MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: it.casesClicked(["B", 1, "D"])
}

Connections{
target: it
onCasesClicked: Test.onCasesClicked(cases)
}
// or
// onCasesClicked: Test.onCasesClicked(cases)
// if the connection is made in the same item
}

输出:

(QVariant(QString, "B"), QVariant(int, 1), QVariant(QString, "D"))

关于c++ - 将信号从 QML 连接到 Qt : var to QList<QString>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48426521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com