Aquarius_Girl
Aquarius_Girl

Reputation: 22906

Unable to populate ComboBox model with QVariantList

From QML: AudioInfoCpp is the C++ class's object. Aim to to get data from C++ and fill it in the model of the combobox.

property ListModel comboModel: cbItems
AudioInfoCpp
{
    id: audioInfoCpp
    Component.onCompleted:
    {
        fetchInputDevices()
        comboModel.append(inputDevices1)

        console.log(inputDevices1)
    }
}

ComboBox
{
    id: comboBoxM;
    width: 100
    model: audioInfoCpp.inputDevices1;
    textRole: "langDescription";
}

From .h

#ifndef AUDIOINFO_H
#define AUDIOINFO_H

#include <QAudioDeviceInfo>
#include <QList>
#include <QVariantList>

class AudioInfo : public QObject
{
    Q_OBJECT

protected:
    QAudioDeviceInfo objQAudioDeviceInfo;

public:
    AudioInfo();

    Q_PROPERTY(QVariantList inputDevices1 READ inputDevices1 WRITE setInputDevices1 NOTIFY inputDevices1Changed)


    Q_INVOKABLE void fetchInputDevices();

    QVariantList inputDevices1() const
    {
        return m_inputDevices1;
    }

public slots:
    void setInputDevices1(QVariantList inputDevices1)
    {
        if (m_inputDevices1 == inputDevices1)
            return;

        m_inputDevices1 = inputDevices1;
        emit inputDevices1Changed(m_inputDevices1);
    }

signals:
    void inputDevices1Changed(QVariantList inputDevices1);

private:
    QVariantList m_inputDevices1;
};

#endif // AUDIOINFO_H

.cpp :

void AudioInfo::fetchInputDevices()
{
    QList<QAudioDeviceInfo> devices1 = QAudioDeviceInfo::availableDevices(QAudio::AudioInput);
    if (devices1.empty())
    {
        qDebug() << "No audio input devices";
    }

    QVariantList tt;

    for (const QAudioDeviceInfo& device : devices1)
    {
        tt.append(device.deviceName());
    }

    setInputDevices1( tt );
}

In QML as well as CPP I can see the data printed from the list but I am not able to populate the combobox. There are no errors.

Please guide.

Upvotes: 0

Views: 317

Answers (1)

JarMan
JarMan

Reputation: 8277

The problem comes from this line:

textRole: "langDescription"

That means it will look through each element in your model for the langDescription field. But you are populating your QVariantList with QStrings:

    QVariantList tt;

    for (const QAudioDeviceInfo& device : devices1)
    {
        tt.append(device.deviceName());
    }

QStrings don't have a langDescription field, so nothing gets displayed.

To solve this try completely removing the textRole line and allow QML to automatically figure out how to display the names correctly.

Upvotes: 2

Related Questions