gpt4 book ai didi

c++ - 无法将 QML 组合框信号连接到 C++ 插槽

转载 作者:行者123 更新时间:2023-11-28 02:42:50 25 4
gpt4 key购买 nike

我正在尝试将 QML 组合框的 currentIndexChanged 信号连接到我类(class)的插槽。问题是,rootObject->findChild 总是返回 NULL,就好像那个特定的组合框不存在一样。

我遇到了这些错误:

qrc:main.qml:134: ReferenceError: combo is not defined
QObject::connect: Cannot connect (null)::currentIndexChanged(int) to ComboBoxSignalReceiver::cppSlot(int)

,尽管我为组合框定义了 objectName。


主要.cpp

#include <QQuickView>
#include <QQmlContext>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QListView>
#include <QtQuick>
#include <QComboBox>
#include <comboboxsignalreceiver.h>

int main(int argc, char *argv[])
{


QStringList event_types;
event_types.append("concerts");
event_types.append("exhibitions");

QApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl("qrc:main.qml"));
view.setResizeMode(QQuickView::SizeRootObjectToView);

QQmlContext *context = view.rootContext();
QObject* rootObject = view.rootObject();

context->setContextProperty("comboBoxModel", QVariant::fromValue(event_types));

QComboBox* combo = rootObject->findChild<QComboBox*>("combo");
ComboBoxSignalReceiver comboBoxSignalReceiver;

QObject::connect(combo, SIGNAL(currentIndexChanged(int)),
&comboBoxSignalReceiver, SLOT(cppSlot(int)));

view.show();

return app.exec();

}

主.qml

import QtQuick 2.0
import QtQuick.Controls 1.1
import QtQuick.Dialogs 1.2
import QtQuick.Window 2.0

Rectangle {
width: 510
height: 400
clip: true

ComboBox {
id: comboBox1
objectName: combo
model: comboBoxModel
currentIndex: 0
x: 418
y: 8
width: 84
height: 20
activeFocusOnPress: true
}
}

组合框信号接收器.h

#include <QObject>
#include <iostream>

class ComboBoxSignalReceiver : public QObject
{
Q_OBJECT
public slots:
void cppSlot(const int &v) {
std::cout << "Called the C++ slot with value:" << v;
}
};

最佳答案

您不能将 ComboBox 转换为 QComboBox,因为它实例化了 QQuickItem 而不是 QComboBox。findChild 方法通过 objectName 查找子项来工作,objectName 需要是一个 string。所以 combo 应该是一个字符串作为“combo”。此外,ComboBox 元素没有 currentIndexChanged 信号(至少我没看到),您可以使用 activated 信号,如下所示:

QQuickItem *item = view.rootObject()->findChild<QQuickItem*>("combo");
if(item) {
QObject::connect(item,SIGNAL(activated(int)),&comboBoxSignalReceiver,SLOT(cppSlot(int)));
}

关于c++ - 无法将 QML 组合框信号连接到 C++ 插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25378235/

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