【问题标题】:Can't connect QML combobox signal to C++ slot无法将 QML 组合框信号连接到 C++ 插槽
【发布时间】: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;
    }
};

【问题讨论】:

    标签: c++ qt combobox


    【解决方案1】:

    您不能将 ComboBox 转换为 QComboBox,因为它实例化的是 QQuickItem 而不是 QComboBox。 findChild 方法通过 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)));
    }
    

    【讨论】:

      【解决方案2】:

      objectName 应该是一个字符串。在你的情况下。 QML 正在搜索标识符为 combo 的对象,但没有找到(因此出现错误消息)

       objectName: "combo"
      

      应该可以解决您的问题。

      请参阅QObject::objectName 属性以供参考

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-15
        • 2021-12-12
        • 1970-01-01
        相关资源
        最近更新 更多