Model не определяется в QQuickWidget
проектный файл
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
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.Вам это нравится? Поделитесь в социальных сетях!
Комментарии
Только авторизованные пользователи могут публиковать комментарии.
Пожалуйста, авторизуйтесь или зарегистрируйтесь
Пожалуйста, авторизуйтесь или зарегистрируйтесь
- Дмитрий
- 7 мая 2024 г. 19:40
C++ - Тест 004. Указатели, Массивы и Циклы
- Результат:60баллов,
- Очки рейтинга-1
d
- dsfs
- 26 апреля 2024 г. 14:56
C++ - Тест 004. Указатели, Массивы и Циклы
- Результат:80баллов,
- Очки рейтинга4
Последние комментарии
Qt Linux - Урок 001. Автозапуск Qt приложения под Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Урок 007. Работаем с ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий Кононенко5 февраля 2024 г. 12:50
EVA25 декабря 2023 г. 21:30
Boost - статическая линковка в CMake проекте под Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
Qt/C++ - Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Сейчас обсуждают на форуме
добавить qlineseries в функции в функции: "GPlotter::addSeries(QString title, QVector &arr)" я вызываю метод setChart(...), я в конструктор передал адрес на QChartView элемент
BlinCT5 мая 2024 г. 15:46
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi3 мая 2024 г. 0:07
IscanderChe30 апреля 2024 г. 14:22
c таким оформлением даже не хочу начинать смотреть код
на нет и суда нет.