d
dufusApril 7, 2019, 5:35 a.m.

Как вывести combobox динамически, чтоб каждый combobox соответствовал определённому idModel?

ComboBox, qt, QAbstractListModel, qml

Как вывести combobox динамически, чтоб каждый combobox соответствовал определённому idModel? У меня есть ThreeDModelTexture наследник QAbstractListModel, который имеет роли
Код проблеммы

    enum ThreeDModelRolse {
        nameRole = Qt::DisplayRole,
        idModelRole = Qt::UserRole + 1,
        urlRole = Qt::UserRole + 2
    };
  roles[idModelRole] = "idModel"; roles[nameRole] = "name"; roles[urlRole] = "url";

Полностью класс :
threedmodeltexture.h

#ifndef THREEDMODELTEXTURE_H
#define THREEDMODELTEXTURE_H

#include <QString>
#include <QObject>
#include <QString>
#include <QAbstractListModel>
#include <QList>
#include <QVariant>
#include <QModelIndex>
#include "baseqmlabstractlistmodel.h"
class Texture;

class ThreeDModelTexture: public QAbstractListModel
{
    Q_PROPERTY(int _idModel READ idmodel(int) )
    Q_PROPERTY(QString _name READ name(int) )
    Q_PROPERTY(QString _url READ url(int) )
public:
    ThreeDModelTexture(QObject *parent = nullptr);
    ~ThreeDModelTexture();
    enum ThreeDModelRolse {
        nameRole = Qt::DisplayRole,
        idModelRole = Qt::UserRole + 1,
        urlRole = Qt::UserRole + 2
    };
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    Q_INVOKABLE int rowCount(const QModelIndex &parent) const; // количество элементов в модели
    void addTexture(Texture tex)const;
    Q_INVOKABLE static int Count();
    Q_INVOKABLE static int boolMatchSearch(int id);

    Q_INVOKABLE int idmodel(const int &id);
    Q_INVOKABLE QString name(const int &id);
    Q_INVOKABLE QString url(const int &id);

public slots:
    QHash<int, QByteArray> roleNames() const;
    Q_INVOKABLE static QList<Texture> textures;
    QHash<int, QByteArray> roles; // роли
};

class Texture
{
public:
    Texture(int _idModel, QString _name, QString _url)
        :idModel(_idModel)
        , name(_name)
        , url(_url)
    {
//        idModel = _idModel;
//        name = _name;
//        url = _url;
    }
    void setName (QString _name)
    {
        name = _name;
    }
    void seturl (QString _url)
    {
        url = _url;
    }
    void setidModel (int _idModel)
    {
        idModel = _idModel;
    }
    QString getName() const
    {
        return name;
    }
    QString getUrl() const
    {
        return url;
    }
    int getIDModel() const
    {
        return idModel;
    }
private:
    int idModel;
    QString name;
    QString url;

};

#endif // THREEDMODELTEXTURE_H

threedmodeltexture.cpp

#include "threedmodeltexture.h"
#include <QDebug>
ThreeDModelTexture::ThreeDModelTexture(QObject *parent) :
    QAbstractListModel(parent)
{
    roles[idModelRole] = "idModel";
    roles[nameRole] = "name";
    roles[urlRole] = "url";
}

QList<Texture> ThreeDModelTexture::textures;

ThreeDModelTexture::~ThreeDModelTexture()
{

}

QVariant ThreeDModelTexture::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() > ThreeDModelTexture::textures.count())
        return QVariant();
    const Texture tex = ThreeDModelTexture::textures[index.row()];
    if (role == idModelRole)
        return tex.getIDModel();
    else if (role == nameRole)
        return tex.getName();
    else if (role == urlRole)
        return tex.getUrl();
    return QVariant();
}

QHash<int, QByteArray> ThreeDModelTexture::roleNames() const
{
    return roles;
}

void ThreeDModelTexture::addTexture(Texture tex) const
{
    ThreeDModelTexture::textures << tex;
}

int ThreeDModelTexture::rowCount(const QModelIndex &parent) const
{
    return ThreeDModelTexture::textures.size();
}

int ThreeDModelTexture::Count()
{
    return ThreeDModelTexture::textures.size();
}

int ThreeDModelTexture::boolMatchSearch(int id)
{
    for(int i=0; i<ThreeDModelTexture::textures.size();i++)
    {
        if (ThreeDModelTexture::textures.at(i).getIDModel()==id)
        {
            return i;
        } else {
            return -1;
        }
    }
    return -1;
}

int idmodel(const int &id)
{
    for(int i=0; i<ThreeDModelTexture::textures.size();i++)
    {
        if (ThreeDModelTexture::textures.at(i).getIDModel()==id)
        {
            return ThreeDModelTexture::textures.at(i).getIDModel();
        } else {
            return -1;
        }
    }
}
QString name(const int &id)
{
    for(int i=0; i<ThreeDModelTexture::textures.size();i++)
    {
        if (ThreeDModelTexture::textures.at(i).getIDModel()==id)
        {
            return ThreeDModelTexture::textures.at(i).getName();
        } else {
            return "";
        }
    }
}
QString url(const int &id)
{
    for(int i=0; i<ThreeDModelTexture::textures.size();i++)
    {
        if (ThreeDModelTexture::textures.at(i).getIDModel()==id)
        {
            return ThreeDModelTexture::textures.at(i).getUrl();
        } else {
            return "";
        }
    }
}

main.cpp

создание экземпляров модели:

    ...
    ThreeDModels.addThreeDModel(new ThreeDModel("false", 1, "ccc","c"));
    ThreeDModels.addThreeDModel(new ThreeDModel("false", 3, "aaa","a"));
    ThreeDModels.addThreeDModel(new ThreeDModel("false", 5, "bbb","b"));


    TextureModel.addTexture(Texture(1, "masta", "masta.jpg"));
    TextureModel.addTexture(Texture(3, "aaa", "aaa.jpg"));
    TextureModel.addTexture(Texture(5, "bbb", "bbb.jpg"));
    TextureModel.addTexture(Texture(3, "ttt", "ttt.jpg"));

    view.engine()->rootContext()->setContextProperty("ThreeDM", &ThreeDModels);
    view.engine()->rootContext()->setContextProperty("TextureM", &TextureModel);

    view.setSource(QUrl("qrc:/Samples/Analysis/ViewshedGeoElement/ViewshedGeoElement.qml"));
    ...

ViewshedGeoElement.qml

        C1.TableView {
            anchors.top: rowLayout.bottom
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            id: tableView
            clip: true
            sortIndicatorVisible: true
            currentRow: rowCount ? 0 : -1
            model: SortFilterProxyModel {
                source: ThreeDM.rowCount() > 0 ? ThreeDM : null

                sortOrder: tableView.sortIndicatorOrder
                sortCaseSensitivity: Qt.CaseInsensitive
                sortRole: ThreeDM.rowCount() && tableView.getColumn(tableView.sortIndicatorColumn).role !== "check" > 0 ?
                              tableView.getColumn(tableView.sortIndicatorColumn).role : ""
            }
            C1.TableViewColumn {
                width: 30
                role: "check"
                resizable: false
                delegate: C1.CheckBox {
                    id: checkBox
                    anchors.left: parent.left
                    anchors.leftMargin: parent.width / 3
                    checked: model.check
                    onVisibleChanged: if (visible) checked = model.check
                    onClicked: model.check = checked
                }
            }
            C1.TableViewColumn {
                width: 30
                role: "id"
                title: "id"
            }
            C1.TableViewColumn {
                width: 90
                role: "description"
                title: "description"
            }
            C1.TableViewColumn {
                width: 60
                role: "code"
                title: "code"
            }
            C1.TableViewColumn {
                width: 100
                role: "combobox"
                resizable: false
                title: "Текстура"
                delegate: C1.ComboBox {
                    id: comboListTexture
                    model: ListModel {
                        id: comboModel
                        dynamicRoles: true
                    }
                    Component.onCompleted: {
                        reload()
                    }
                    textRole:"name"
                    onActivated: console.log("Combo Box Index Changed To:", index, model.data(model.index(index, 0), Qt.UserRole + 2 ))

                    function reload() {
                        var i = comboListTexture.currentIndex
                        // console.log("TextureM.boolMatchSearch(1)",TextureM.getidmodel(1),TextureM.getname(1),TextureM.geturl(1))
                        // console.log("TextureM.boolMatchSearch(1)",TextureM._name,TextureM._idModel,TextureM._url)

                        comboListTexture.model = TextureM
                        comboListTexture.currentIndex = i
                    }
                }
            }

...
            style: TableViewStyle {
                headerDelegate: Rectangle {
                    height: textItem.implicitHeight
                    width: textItem.implicitWidth
                    Text {
                        id: textItem
                        anchors.fill: parent
                        anchors.leftMargin: 6
                        verticalAlignment: Text.AlignVCenter
                        horizontalAlignment: styleData.textAlignment
                        text: styleData.value
                    }
                    C1.CheckBox {
                        anchors.left: parent.left
                        anchors.leftMargin: parent.width / 3
                        property bool isPressed: styleData.pressed
                        visible: styleData.column === 0
                        onIsPressedChanged: {
                            if (isPressed && styleData.column === 0) {
                                checked  = !checked
                                for(var i = 0; i < ThreeDM.rowCount(); i++) {
                                    ThreeDM.setData(ThreeDM.index(i, 0), checked, "check")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

2
Evgenii Legotckoi
  • April 8, 2019, 3:36 a.m.
  • (edited)

Добрый день

При беглом взгляде на код возникает мысль, что вам нужно в методе onCompleted использовать модифицированную версию функции reload, в которой будет устанавливаться первоначальное состояние комбобоксов в зависимости от наименования объекта, то есть названия aaa, bbb, и т.д. Нужно пройтись в цикле по модели и инициализировать модель.

Либо сделать этот сразу в методе addThreeDModel .

    Алексей Внуков
    • April 8, 2019, 5:28 a.m.

    у комбобокса есть ф-я currentText(), сделайте проверку на соответствие, если не сходится, то установите индекс в соответствующую позицию

      Comments

      Only authorized users can post comments.
      Please, Log in or Sign up
      AD

      C ++ - Test 004. Pointers, Arrays and Loops

      • Result:50points,
      • Rating points-4
      m

      C ++ - Test 004. Pointers, Arrays and Loops

      • Result:80points,
      • Rating points4
      m

      C ++ - Test 004. Pointers, Arrays and Loops

      • Result:20points,
      • Rating points-10
      Last comments
      i
      innorwallNov. 11, 2024, 10:12 p.m.
      Django - Tutorial 055. How to write auto populate field functionality Freckles because of several brand names retin a, atralin buy generic priligy
      i
      innorwallNov. 11, 2024, 6:23 p.m.
      QML - Tutorial 035. Using enumerations in QML without C ++ priligy cvs 24 Together with antibiotics such as amphotericin B 10, griseofulvin 11 and streptomycin 12, chloramphenicol 9 is in the World Health Organisation s List of Essential Medici…
      i
      innorwallNov. 11, 2024, 3:50 p.m.
      Qt/C++ - Lesson 052. Customization Qt Audio player in the style of AIMP It decreases stress, supports hormone balance, and regulates and increases blood flow to the reproductive organs buy priligy online safe Promising data were reported in a PDX model re…
      i
      innorwallNov. 11, 2024, 2:19 p.m.
      Heap sorting algorithm The role of raloxifene in preventing breast cancer priligy precio
      i
      innorwallNov. 11, 2024, 1:55 p.m.
      PyQt5 - Lesson 006. Work with QTableWidget buy priligy 60 mg 53 have been reported by Javanovic Santa et al
      Now discuss on the forum
      i
      innorwallNov. 11, 2024, 8:56 p.m.
      добавить qlineseries в функции buy priligy senior brother Chu He, whom he had known for many years
      i
      innorwallNov. 11, 2024, 10:55 a.m.
      Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
      9
      9AnonimOct. 25, 2024, 9:10 a.m.
      Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

      Follow us in social networks