如何从QML组合框中访问值,该组合框从表/模型中获取值?

时间:2016-04-20 11:54:07

标签: c++ qt qml

我有一个从表中获取值的组合框。我使用:

获取组合框对象
QObject * object=engine->rootObjects().at(0)->findChild<QObject* >("comboobjectname");

现在,如何从组合框列表中设置一个值并使用C ++在GUI上设置它?

1 个答案:

答案 0 :(得分:2)

我总是建议:如果你有一个模型,请使用模型更新你的GUI。

我不知道你的整个项目,但是如果你有C ++中的模型,你应该有一个类,可以添加,删除和获取数据。

在这个例子中,我将向您展示一个非常简单的模型Animal,它有两个值:类型和大小。

<强> animal.h

#ifndef ANIMAL_H
#define ANIMAL_H

#include <QString>

class Animal
{
public:
    Animal(const QString &type, const QString &size);

    QString type() const;
    QString size() const;

private:
    QString m_type;
    QString m_size;
};

#endif // ANIMAL_H

<强> animal.cpp

#include "animal.h"

Animal::Animal(const QString &type, const QString &size)
    : m_type(type), m_size(size)
{
}

QString Animal::type() const
{
    return m_type;
}

QString Animal::size() const
{
    return m_size;
}

<强> animalmodel.h

#ifndef ANIMALMODEL_H
#define ANIMALMODEL_H

#include <QAbstractListModel>
#include <QStringList>
#include "animal.h"

class AnimalModel : public QAbstractListModel
{
    Q_OBJECT
public:
    enum AnimalRoles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    AnimalModel(QObject *parent = 0);

    Q_INVOKABLE void addAnimal(const QString &type, const QString &size);

    void addAnimal(const Animal &animal);

    Q_INVOKABLE void removeAnimal(int row);

    int rowCount(const QModelIndex & parent = QModelIndex()) const;

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;

protected:
    QHash<int, QByteArray> roleNames() const;
private:
    QList<Animal> m_animals;
};

#endif // ANIMALMODEL_H

<强> animalmodel.cpp

#include "animalmodel.h"
#include <QDebug>
#include <QListIterator>

AnimalModel::AnimalModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

void AnimalModel::addAnimal(const QString &type, const QString &size)
{
    addAnimal(Animal(type, size));
}

void AnimalModel::addAnimal(const Animal &animal)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_animals << animal;
    endInsertRows();
}

void AnimalModel::removeAnimal(int row)
{
    beginRemoveRows(QModelIndex(), row, row);
    m_animals.removeAt(row);
    removeRow(row, QModelIndex());
    endRemoveRows();
}

int AnimalModel::rowCount(const QModelIndex & parent) const {
    Q_UNUSED(parent);
    return m_animals.count();
}

QVariant AnimalModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_animals.count())
        return QVariant();

    const Animal &animal = m_animals[index.row()];
    if (role == TypeRole)
        return animal.type();
    else if (role == SizeRole)
        return animal.size();
    return QVariant();
}

QHash<int, QByteArray> AnimalModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    roles[SizeRole] = "size";
    return roles;
}

感谢此模型,我们可以在QML中使用它来显示,例如TableViewComboBox

import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.4

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("")

    toolBar: ToolBar {
        id: toolbar
        width: parent.width

        style: ToolBarStyle {
            padding {
                left: 20
                right: 20
                top: 15
                bottom: 15
            }
            background: Rectangle {
                implicitWidth: 100
                implicitHeight: 40
                border.color: "#999"
                gradient: Gradient {
                    GradientStop { position: 0 ; color: "#fff" }
                    GradientStop { position: 1 ; color: "#aaa" }
                }
            }
        }
        ColumnLayout{
            spacing: 2
            RowLayout {
                Button {
                    id: addButton
                    anchors.verticalCenter: parent.verticalCenter

                    text: "Add item"

                    onClicked: {
                        if (typeBox.text || sizeBox.text) {
                            myModel.addAnimal(typeBox.text, sizeBox.text)
                        }
                    }
                }
                TextField {
                    id: typeBox
                    placeholderText: "type"

                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: addButton.right
                    anchors.leftMargin: 5
                }

                TextField {
                    id: sizeBox
                    placeholderText: "size"

                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: typeBox.right
                    anchors.leftMargin: 5
                }
            }

            RowLayout {
                Button {
                    id: deleteButton
                    anchors.verticalCenter: parent.verticalCenter

                    text: "Delete item"

                    onClicked: {
                        if(tableView.currentRow != -1)
                        {
                            myModel.removeAnimal(tableView.currentRow)
                        }
                    }
                }
            }
            ColumnLayout{
                spacing: 2
                RowLayout {
                    ComboBox {
                        id: myCombobox
                        currentIndex: 2
                        model: myModel
                        textRole : "type"
                    }

                    Button {
                        id: printvaluesButton
                        anchors.verticalCenter: parent.verticalCenter

                        text: "Print values"

                        onClicked: {
                            console.debug(myCombobox.currentIndex)
                            comboboxManagement.printValues(myModel,
                                                           myModel.index(myCombobox.currentIndex, 0))
                        }
                    }
                }
            }
        }
    }

    TableView {
        id: tableView

        frameVisible: false
        sortIndicatorVisible: true

        anchors.fill: parent

        Layout.minimumWidth: 400
        Layout.minimumHeight: 240
        Layout.preferredWidth: 600
        Layout.preferredHeight: 400

        TableViewColumn {
            role: "type"
            title: "Type"
            width: 100
        }

        TableViewColumn {
            role: "size"
            title: "Size"
            width: 200
        }

        model: myModel
    }
}

如您所见,我们有一些按钮来添加和删除项目。单击按钮后,TableViewComboBox都会更新。

在我们的ComboBox的特定情况下,我们有一个C ++类来打印所选元素。是否有这样的课程来执行这些任务取决于您并且取决于您的要求。

<强> comboboxmanagement.h

#ifndef COMBOBOXMANAGEMENT_H
#define COMBOBOXMANAGEMENT_H

#include <QObject>
#include <QDebug>
#include "animalmodel.h"

class ComboboxManagement : public QObject
{
    Q_OBJECT
public:
    explicit ComboboxManagement(QObject *parent = 0);

    Q_INVOKABLE bool printValues(AnimalModel* model,
                               const QModelIndex &modelIndex);

};

#endif // COMBOBOXMANAGEMENT_H

<强> comboboxmanagement.cpp

#include "comboboxmanagement.h"

ComboboxManagement::ComboboxManagement(QObject *parent) : QObject(parent)
{

}

bool ComboboxManagement::printValues(AnimalModel* model,
                       const QModelIndex &modelIndex) {
    qDebug() << model->data(modelIndex, AnimalModel::TypeRole);
    return true;
}

最后,main.cpp

#include "animalmodel.h"
#include "comboboxmanagement.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>

int main(int argc, char ** argv)
{
    QGuiApplication app(argc, argv);

    AnimalModel model;
    model.addAnimal(Animal("Wolf", "Medium"));
    model.addAnimal(Animal("Polar bear", "Large"));
    model.addAnimal(Animal("Quoll", "Small"));

    ComboboxManagement comboboxManagement;
    QQmlApplicationEngine engine;

    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty("myModel", &model);    
    ctxt->setContextProperty("comboboxManagement", &comboboxManagement);

    engine.load(QUrl(QStringLiteral("qrc:/view.qml")));

    return app.exec();
}
相关问题