【发布时间】:2014-08-19 07:53:15
【问题描述】:
我正在尝试将 QML 组合框的 currentIndexChanged 信号连接到我班级的插槽。 问题是,rootObject->findChild 总是返回 NULL,就好像那个特定的组合框不存在一样。
我收到以下错误:
qrc:main.qml:134: ReferenceError: combo is not defined
QObject::connect: Cannot connect (null)::currentIndexChanged(int) to ComboBoxSignalReceiver::cppSlot(int)
,虽然我为组合框定义了 objectName。
main.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();
}
main.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
}
}
comboboxsignalreceiver.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;
}
};
【问题讨论】: