o
ost.vldJune 8, 2021, 5:46 a.m.

Model не определяется в QQuickWidget

QML, QQuickWidget, Model

проектный файл

QT += core gui quickwidgets widgets

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


HEADERS += \
    widget.h

SOURCES += \
        main.cpp \
        widget.cpp

RESOURCES += qml.qrc


# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target


хедер виджета

#ifndef WIDGET_H
#define WIDGET_H

#include <QObject>
#include <QWidget>
#include <QGridLayout>
#include <QStringListModel>

#include <QQuickWidget>
#include <QQmlContext>
#include <QQuickItem>


class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    QGridLayout *gridLayout;
    QQuickWidget *quickWidget;
};

#endif // WIDGET_H

реализация виджета

#include "widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent)
  , gridLayout(new QGridLayout(this))
  , quickWidget (new QQuickWidget(this))
{
    quickWidget->setSource(QUrl("qrc:/main.qml"));
    quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
    gridLayout->addWidget(quickWidget, 1, 0);

    // Добавление модели в qml
    QQmlContext *rootQMLcontext = quickWidget->rootContext();
    QQuickItem *rootObj = quickWidget->rootObject();
    QObject *objListView = rootObj->findChild<QObject *>("ListView");


    if (objListView)
    {
        QStringList  lst;

        for (int i = 0; i < 100; ++i)
        {
            lst << "Item" + QString::number(i);
        }
        QStringListModel *pmodel = new QStringListModel(quickWidget);
        pmodel->setStringList(lst);

        rootQMLcontext->setContextProperty("myModel", pmodel);
    }

    this->setLayout(gridLayout);

}

Widget::~Widget()
{

}

main.qml

import QtQuick 2.5
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.12

Item {

    anchors.fill:  parent

    GridLayout
    {
        id: grid
        x: 20
        y: 20
        columnSpacing: 10
        rows: 10
        columns: 1
        Button{
            id: button
            text: "hello!"
            Layout.row: 0
            Layout.column: 0
        }

        ListView {
                    objectName: "ListView"
                    model: myModel
                    delegate: Text {text: model.display}
                    Layout.row: 1
                    Layout.column: 0
                    Layout.rowSpan: 8
                }
       }

}

main.cpp

#include <QApplication>
#include <QMainWindow>
#include "widget.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMainWindow  m;
    auto qmlMainWidget = new Widget(&m);
    m.setCentralWidget(qmlMainWidget);
    m.show();
    return app.exec();
}

ошибка

QML debugging is enabled. Only use this in a safe environment.
qrc:/main.qml:14: ReferenceError: myModel is not defined

Почему есть ошибка?
ListView поверх кнопки, не смотря на GridLayout

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
Алексей Внуков
  • June 8, 2021, 7:52 a.m.

c таким оформлением даже не хочу начинать смотреть код

    o
    • June 8, 2021, 8:27 a.m.

    на нет и суда нет.

      Comments

      Only authorized users can post comments.
      Please, Log in or Sign up
      г
      • ги
      • April 23, 2024, 9:51 p.m.

      C++ - Test 005. Structures and Classes

      • Result:41points,
      • Rating points-8
      l
      • laei
      • April 23, 2024, 3:19 p.m.

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

      • Result:10points,
      • Rating points-10
      l
      • laei
      • April 23, 2024, 3:17 p.m.

      C++ - Тест 003. Условия и циклы

      • Result:50points,
      • Rating points-4
      Last comments
      k
      kmssrFeb. 9, 2024, 12:43 a.m.
      Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
      Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
      EVA
      EVADec. 25, 2023, 4:30 p.m.
      Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
      J
      JonnyJoDec. 25, 2023, 2:38 p.m.
      Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
      G
      GvozdikDec. 19, 2023, 3:01 a.m.
      Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
      Now discuss on the forum
      G
      GarApril 22, 2024, 11:46 a.m.
      Clipboard Как скопировать окно целиком в clipb?
      DA
      Dr Gangil AcademicsApril 20, 2024, 1:45 p.m.
      Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
      a
      a_vlasovApril 14, 2024, 12:41 p.m.
      Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
      Павел Дорофеев
      Павел ДорофеевApril 14, 2024, 8:35 a.m.
      QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
      f
      fastrexApril 4, 2024, 10:47 a.m.
      Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

      Follow us in social networks