c++ - 如何从从表/模型获取值的 QML 组合框中访问值?

标签 c++ qt qml

我有一个从表中获取值的组合框。我使用以下方法获取组合框对象:

QObject * object=engine->rootObjects().at(0)->findChild<QObject* >("comboobjectname");

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

最佳答案

我总是建议相同的:使用模型更新您的 GUI(如果有的话)。

我不知道你的整个项目,但如果你有 C++ 模型,你应该有一个包含添加、删除和获取数据方法的类。

在此示例中,我将向您展示一个非常简单的模型 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

动物.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

动物模型.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();
}

关于c++ - 如何从从表/模型获取值的 QML 组合框中访问值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36742982/

相关文章:

c++ - Mongodb : error while loading shared libraries: libboost_thread. so.1.54.0: > 无法打开共享对象文件:没有这样的文件或目录

qt - 如何使用QT国际化

c# - 适用于 Mac 和 Windows 的音频框架

.net - ATL COM Server - 从此服务器创建 ATL Server 中定义的 COM 对象

c++ - 在 QtCreator 中跳过第二个自动生成的报价

qt - 如何将具有自定义属性的组件移动到 QML 中的单独文件

qt - 如何在 QtControls 2.0 中为 SpinBox 设置对齐方式?

C++ 从压缩 DATE 转换为 CTime

c++ - 如何使用 GDI+ 和 C++ 从 SQL Server 数据库加载和保存图像?

qt - 如何在我处理之前报告进度而不浏览整个文件