o
ost.vldJune 8, 2021, 3:46 p.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, 5:52 p.m.

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

    o
    • June 8, 2021, 6:27 p.m.

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

      Comments

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

      Qt - Test 001. Signals and slots

      • Result:84points,
      • Rating points4
      Ua

      Qt - Test 001. Signals and slots

      • Result:42points,
      • Rating points-8
      ОК

      Qt - Test 001. Signals and slots

      • Result:47points,
      • Rating points-6
      Last comments
      ИМ
      Игорь МаксимовNov. 22, 2024, 9:51 p.m.
      Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
      Evgenii Legotckoi
      Evgenii LegotckoiOct. 31, 2024, 11:37 p.m.
      Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
      A
      ALO1ZEOct. 19, 2024, 5:19 p.m.
      Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
      ИМ
      Игорь МаксимовOct. 5, 2024, 4:51 p.m.
      Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
      d
      dblas5July 5, 2024, 8:02 p.m.
      QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
      Now discuss on the forum
      AH
      Abdul HadiFeb. 13, 2025, 3:21 p.m.
      Are you Looking for best painter services in Qatar? Looking for top painter Services in Qatar? Get high-quality, affordable, and professional painting for homes & offices. Contact expert painters today!
      d
      dubaicushionsFeb. 13, 2025, 3:17 p.m.
      Are Looking for custom swing cushions in Dubai for home decor? Looking for Custom Swing Cushions in Dubai? Get high-quality, weather-resistant, and stylish cushions for your outdoor swing. Order now for comfort & elegance!
      d
      dubaicustomizedsofaFeb. 13, 2025, 3:11 p.m.
      Are you Looking for a custom sofa in Dubai? Looking for a Custom Sofa in Dubai ? Get high-quality, stylish, and tailor-made sofas to match your space. Order now for comfort, luxury, and perfect design!
      b
      blinds12Feb. 11, 2025, 4:08 p.m.
      Why Bamboo Blinds Are the Perfect Choice for Your Home When it comes to enhancing the aesthetics and functionality of your living space, choosing the right window treatment is crucial. Bamboo blinds have emerged as a popular choice for homeowners wh…
      i
      imperial3130Feb. 11, 2025, 3:40 p.m.
      How to Select the Right Carpet for Your Bedroom Aesthetic Choosing the perfect carpet for your bedroom involves more than just picking a color or pattern you like. Carpets can transform the ambiance of your space, adding warmth, comfort, and style. How…

      Follow us in social networks