QQmlComponent_ *newComponent(QQmlEngine_ *engine, QObject_ *parent) { QQmlEngine *qengine = reinterpret_cast<QQmlEngine *>(engine); //QObject *qparent = reinterpret_cast<QObject *>(parent); QQmlComponent *qcomponent = new QQmlComponent(qengine); // Qt 5.2.0 returns NULL on qmlEngine(qcomponent) without this. QQmlEngine::setContextForObject(qcomponent, qengine->rootContext()); return qcomponent; }
void tst_qqmlengine::contextForObject() { QQmlEngine *engine = new QQmlEngine; // Test null-object QVERIFY(!QQmlEngine::contextForObject(0)); // Test an object with no context QObject object; QVERIFY(!QQmlEngine::contextForObject(&object)); // Test setting null-object QQmlEngine::setContextForObject(0, engine->rootContext()); // Test setting null-context QQmlEngine::setContextForObject(&object, 0); // Test setting context QQmlEngine::setContextForObject(&object, engine->rootContext()); QCOMPARE(QQmlEngine::contextForObject(&object), engine->rootContext()); QQmlContext context(engine->rootContext()); // Try changing context QTest::ignoreMessage(QtWarningMsg, "QQmlEngine::setContextForObject(): Object already has a QQmlContext"); QQmlEngine::setContextForObject(&object, &context); QCOMPARE(QQmlEngine::contextForObject(&object), engine->rootContext()); // Delete context delete engine; engine = 0; QVERIFY(!QQmlEngine::contextForObject(&object)); }
void tst_qqmlengine::rootContext() { QQmlEngine engine; QVERIFY(engine.rootContext()); QCOMPARE(engine.rootContext()->engine(), &engine); QVERIFY(!engine.rootContext()->parentContext()); }
int main(int argc, char* argv[]) { QGuiApplication app(argc, argv); // Use QCommandLineParser to parse arguments (see documentation) QQmlEngine engine; // Register needed types registerQmlTypes(); // Add image provider engine.addImageProvider(QStringLiteral("svgelement"), new qtouch::SvgElementProvider(QQmlImageProviderBase::Image, QUrl(QStringLiteral("qrc:///images/")))); qtouch::DataModel dataModel; try { dataModel.init(); } catch (qtouch::Exception& e) { qCritical() << e.message(); return EXIT_FAILURE; } qtouch::CourseModel* courseModel = new qtouch::CourseModel(&dataModel, &app); qtouch::ProfileModel* profileModel = new qtouch::ProfileModel(&dataModel, &app); // Embed view models engine.rootContext()->setContextProperty("$courseModel", courseModel); engine.rootContext()->setContextProperty("$profileModel", profileModel); // Create root component QQmlComponent component(&engine); QQuickWindow::setDefaultAlphaBuffer(true); component.loadUrl(QUrl(QStringLiteral("qrc:/qml/MainWindow.qml"))); if (componentError(&component)) return EXIT_FAILURE; if (component.isReady()) { component.create(); if (componentError(&component)) return EXIT_FAILURE; } else { qWarning() << component.errorString(); return EXIT_FAILURE; } // FIXME: Not nice but fixes initialization problem courseModel->selectCourse(0); return app.exec(); }
void WelcomeMode::addPages(const QList<IWelcomePage *> &pages) { QList<IWelcomePage *> addedPages = pages; Utils::sort(addedPages, [](const IWelcomePage *l, const IWelcomePage *r) { return l->priority() < r->priority(); }); // insert into m_pluginList, keeping m_pluginList sorted by priority QQmlEngine *engine = m_welcomePage->engine(); auto addIt = addedPages.begin(); auto currentIt = m_pluginList.begin(); while (addIt != addedPages.end()) { IWelcomePage *page = *addIt; QTC_ASSERT(!m_idPageMap.contains(page->id()), ++addIt; continue); while (currentIt != m_pluginList.end() && (*currentIt)->priority() <= page->priority()) ++currentIt; // currentIt is now either end() or a page with higher value currentIt = m_pluginList.insert(currentIt, page); m_idPageMap.insert(page->id(), page); page->facilitateQml(engine); ++currentIt; ++addIt; } // update model through reset QQmlContext *ctx = engine->rootContext(); ctx->setContextProperty(QLatin1String("pagesModel"), QVariant::fromValue( Utils::transform(m_pluginList, // transform into QList<QObject *> [](IWelcomePage *page) -> QObject * { return page; }))); }
// QTBUG-21310 - crash test void tst_qqmlexpression::syntaxError() { QQmlEngine engine; QQmlExpression expression(engine.rootContext(), 0, "asd asd"); QVariant v = expression.evaluate(); QCOMPARE(v, QVariant()); }
void tst_QQmlPropertyMap::controlledWrite() { MyPropertyMap map; QCOMPARE(map.isEmpty(), true); //make changes in QML QQmlEngine engine; QQmlContext *ctxt = engine.rootContext(); ctxt->setContextProperty(QLatin1String("testdata"), &map); const char *qmlSource = "import QtQuick 2.0\n" "Item { Component.onCompleted: { testdata.key1 = 'Hello World'; testdata.key2 = 'Goodbye' } }"; QQmlComponent component(&engine); component.setData(qmlSource, QUrl::fromLocalFile("")); QVERIFY(component.isReady()); QObject *obj = component.create(); QVERIFY(obj); delete obj; QCOMPARE(map.value(QLatin1String("key1")), QVariant("HELLO WORLD")); QCOMPARE(map.value(QLatin1String("key2")), QVariant("Goodbye")); }
void tst_QQmlPropertyMap::changed() { QQmlPropertyMap map; QSignalSpy spy(&map, SIGNAL(valueChanged(const QString&, const QVariant&))); map.insert(QLatin1String("key1"),100); map.insert(QLatin1String("key2"),200); QCOMPARE(spy.count(), 0); map.clear(QLatin1String("key1")); QCOMPARE(spy.count(), 0); //make changes in QML QQmlEngine engine; QQmlContext *ctxt = engine.rootContext(); ctxt->setContextProperty(QLatin1String("testdata"), &map); QQmlComponent component(&engine); component.setData("import QtQuick 2.0\nText { text: { testdata.key1 = 'Hello World'; 'X' } }", QUrl::fromLocalFile("")); QVERIFY(component.isReady()); QQuickText *txt = qobject_cast<QQuickText*>(component.create()); QVERIFY(txt); QCOMPARE(txt->text(), QString('X')); QCOMPARE(spy.count(), 1); QList<QVariant> arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(0).toString(),QLatin1String("key1")); QCOMPARE(arguments.at(1).value<QVariant>(),QVariant("Hello World")); QCOMPARE(map.value(QLatin1String("key1")), QVariant("Hello World")); }
void engineSetContextForObject(QQmlEngine_ *engine, QObject_ *object) { QQmlEngine *qengine = reinterpret_cast<QQmlEngine *>(engine); QObject *qobject = reinterpret_cast<QObject *>(object); QQmlEngine::setContextForObject(qobject, qengine->rootContext()); }
void TestSimpleQmlLoad::compileAndLoadSignal2() { const QString TEST_FILE(":/testqml/testsignal2.qml"); QQmlEngine *engine = new QQmlEngine; QQmlComponent* component = compileAndLoad(engine, TEST_FILE); QVERIFY(component); SignalTester st; engine->rootContext()->setContextProperty("st", &st); QObject *myObject = component->create(); QVERIFY(myObject != NULL); QVariant var = myObject->property("sigReceived"); QVERIFY(!var.isNull()); QVERIFY(var.toBool() == false); st.sendSig(); var = myObject->property("sigReceived"); QVERIFY(!var.isNull()); QVERIFY(var.toBool() == true); delete component; delete engine; }
void TestSimpleQmlLoad::loadSignal3() { QQmlEngine *engine = new QQmlEngine; const QString TEST_FILE(":/testqml/testsignal3.qml"); QQmlComponent* component = load(engine, TEST_FILE); QVERIFY(component); SignalTester st; engine->rootContext()->setContextProperty("st", &st); QObject *myObject = component->create(); QVERIFY(myObject != NULL); st.sendSig(); QVariant ret; QMetaObject::invokeMethod(myObject, "getSubWidth1", Q_RETURN_ARG(QVariant, ret)); QVERIFY(ret.toInt() == 10); st.sendSig(); QMetaObject::invokeMethod(myObject, "getSubWidth1", Q_RETURN_ARG(QVariant, ret)); QVERIFY(ret.toInt() == 20); delete component; delete engine; }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlEngine engine; QMLBattleStationContext* context = new QMLBattleStationContext(); engine.rootContext()->setContextProperty(QString("context"), context); QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml"))); component.create(); // Init/create subsystems if (SDL_Init(SDL_INIT_JOYSTICK)) { QString* err = new QString(SDL_GetError()); qWarning() << LOG_ERROR << "SDL init error:" << err; // TODO UI notification } else { qDebug() << LOG_OK << "SDL init"; } Serial* serial = new Serial(); InputHandler* inputHandler = new InputHandler(); // Connect Serial and BSC QObject::connect(context, SIGNAL(SelectedSerialDeviceChanged(QString)), serial, SLOT(SetActiveSerialDevice(QString))); // Connect Input and BSC QObject::connect(context, SIGNAL(SelectedJoystickAChanged(QString)), inputHandler, SLOT(SetMainJoystick(QString*))); // Connect Input to Serial QObject::connect(inputHandler, SIGNAL(MotorValuesChanged(quint8[])), serial, SLOT(SetMotorValues(quint8[]))); QObject::connect(inputHandler, SIGNAL(PostToolUpdate(quint16,quint16)), serial, SLOT(EnqueueToolEvent(quint16,quint16))); return app.exec(); }
void Editor::init() { if(m_initialized){ return; } Engine* engine = Engine::getInstance(); QQmlEngine* qmlEngine = engine->getQmlEngine(); QQmlContext* context = qmlEngine->rootContext(); context->setContextProperty("editor",this); editorUiComponent = new QQmlComponent(qmlEngine,Util::getUrlPathToAsset("qml/editor/EditorUi.qml")); for(QQmlError error :editorUiComponent->errors()){ qDebug() << "Error on Line" << error.line() << ":" << error.description(); } if(editorUiComponent->isReady()){ initUi(); }else { connect(editorUiComponent,SIGNAL(statusChanged(QQmlComponent::Status)), this,SLOT(onLoadingUiChanged(QQmlComponent::Status))); } m_initialized = true; }
int main(int argc, char **argv) { QApplication app(argc, argv); const QUrl documentUrl = QUrl("qrc:///main.qml"); QQmlEngine engine; #ifdef Q_OS_MACOS engine.addImportPath(QStringLiteral("%1/../PlugIns").arg(QCoreApplication::applicationDirPath())); #else engine.addImportPath(PLUGIN_IMPORT_PATH); #endif Editor editor; engine.rootContext()->setContextProperty("_editor", &editor); QObject::connect(&engine, &QQmlEngine::quit, QCoreApplication::instance(), &QCoreApplication::quit); QQmlComponent component(&engine, documentUrl); QWidget *widget = qobject_cast<QWidget*>(component.create()); if (!widget) qFatal("Failed to create widget from QML"); widget->show(); return app.exec(); }
void tst_qqmlexpression::exception() { QQmlEngine engine; QQmlExpression expression(engine.rootContext(), 0, "abc=123"); QVariant v = expression.evaluate(); QCOMPARE(v, QVariant()); QVERIFY(expression.hasError()); }
void MainView::newPacket() { QQmlEngine *engine = new QQmlEngine; QQmlComponent component(engine); engine->rootContext()->setContextProperty("__packet__", new EthernetDisplay()); component.loadUrl(QUrl(QStringLiteral("qrc:/views/ethernet.qml"))); if (component.isReady()) component.create(); }
void testContextProperty() { QQmlEngine engine; engine.rootContext()->setContextProperty("myContextProp", 42); auto adaptor = PropertyAdaptorFactory::create(engine.rootContext(), this); QVERIFY(adaptor); #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0) auto idx = indexOfProperty(adaptor, "myContextProp"); QVERIFY(idx >= 0); auto data = adaptor->propertyData(idx); QCOMPARE(data.name(), QStringLiteral("myContextProp")); QCOMPARE(data.value().toInt(), 42); adaptor->writeProperty(idx, 23); QCOMPARE(engine.rootContext()->contextProperty("myContextProp").toInt(), 23); #endif }
int main(int argc, char *argv[]) { QGuiApplication a(argc, argv); COpenVROverlayController::SharedInstance()->Init(); // Get the base path DWORD size = MAX_PATH; WCHAR path[MAX_PATH]; HKEY oculusKey; RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Oculus VR, LLC\\Oculus", 0, KEY_READ | KEY_WOW64_32KEY, &oculusKey); RegQueryValueEx(oculusKey, L"Base", NULL, NULL, (PBYTE)path, &size); // Create a QML engine. QQmlEngine qmlEngine; qmlEngine.rootContext()->setContextProperty("ReviveManifest", CReviveManifestController::SharedInstance()); // Set the properties. QString str = QString::fromWCharArray(path); QUrl url = QUrl::fromLocalFile(str); QString base = QDir::fromNativeSeparators(str); qmlEngine.rootContext()->setContextProperty("baseURL", url.url()); qmlEngine.rootContext()->setContextProperty("basePath", base); QQmlComponent qmlComponent( &qmlEngine, QUrl("qrc:/Overlay.qml")); if (qmlComponent.isError()) { qDebug(qUtf8Printable(qmlComponent.errorString())); return -1; } QObject *rootObject = qmlComponent.create(); QQuickItem *rootItem = qobject_cast<QQuickItem*>( rootObject ); COpenVROverlayController::SharedInstance()->SetQuickItem( rootItem ); // don't show the window that you're going display in an overlay //view.show(); return a.exec(); }
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(parent, flags), IPersistentSettings(this) { qfLogFuncFrame(); Q_ASSERT(self == nullptr); self = this; m_pluginLoader = nullptr; Application *app = Application::instance(); app->m_frameWork = this; QQmlEngine *qe = app->qmlEngine(); qe->rootContext()->setContextProperty("FrameWork", this); }
void tst_qqmlengine::baseUrl() { QQmlEngine engine; QUrl cwd = QUrl::fromLocalFile(QDir::currentPath() + QDir::separator()); QCOMPARE(engine.baseUrl(), cwd); QCOMPARE(engine.rootContext()->resolvedUrl(QUrl("main.qml")), cwd.resolved(QUrl("main.qml"))); QDir dir = QDir::current(); dir.cdUp(); QVERIFY(dir != QDir::current()); QDir::setCurrent(dir.path()); QCOMPARE(QDir::current(), dir); QUrl cwd2 = QUrl::fromLocalFile(QDir::currentPath() + QDir::separator()); QCOMPARE(engine.baseUrl(), cwd2); QCOMPARE(engine.rootContext()->resolvedUrl(QUrl("main.qml")), cwd2.resolved(QUrl("main.qml"))); engine.setBaseUrl(cwd); QCOMPARE(engine.baseUrl(), cwd); QCOMPARE(engine.rootContext()->resolvedUrl(QUrl("main.qml")), cwd.resolved(QUrl("main.qml"))); }
MasterSurfaceRenderer::MasterSurfaceRenderer(const size_t surfaceIndex, DisplayGroupPtr group, QQmlEngine& engine, QQuickItem& parentItem) : _group{group} , _groupController{new DisplayGroupController{*_group}} { if (surfaceIndex == 0) { _setContextProperties(*engine.rootContext()); _createControlSurfaceItem(engine); } else _createBasicSurfaceItem(engine); _surfaceItem->setParentItem(&parentItem); _createGroupRenderer(engine); }
Launcher::Launcher( int& argc, char* argv[] ) : QGuiApplication( argc, argv ) { const CommandLineOptions options( argc, argv ); const MasterConfiguration config( options.getConfiguration( )); const auto deflectStreamId = options.getStreamId().toStdString(); _qmlStreamer.reset( new deflect::qt::QmlStreamer( deflectQmlFile, deflectHost, deflectStreamId )); connect( _qmlStreamer.get(), &deflect::qt::QmlStreamer::streamClosed, this, &QCoreApplication::quit ); auto item = _qmlStreamer->getRootItem(); // General setup item->setProperty( "restPort", config.getWebServicePort( )); if( options.getWidth( )) item->setProperty( "width", options.getWidth( )); if( options.getHeight( )) item->setProperty( "height", options.getHeight( )); // FileBrowser setup const auto filters = ContentFactory::getSupportedFilesFilter(); item->setProperty( "filesFilter", filters ); item->setProperty( "rootFilesFolder", config.getContentDir( )); item->setProperty( "rootSessionsFolder", config.getSessionsDir( )); QQmlEngine* engine = _qmlStreamer->getQmlEngine(); #if TIDE_ASYNC_THUMBNAIL_PROVIDER engine->addImageProvider( thumbnailProviderId, new AsyncThumbnailProvider ); #else engine->addImageProvider( thumbnailProviderId, new ThumbnailProvider ); #endif engine->rootContext()->setContextProperty( "fileInfo", &_fileInfoHelper ); // DemoLauncher setup item->setProperty( "demoServiceUrl", config.getDemoServiceUrl( )); item->setProperty( "demoServiceImageFolder", config.getDemoServiceImageFolder( )); item->setProperty( "demoServiceDeflectHost", QHostInfo::localHostName( )); }
void TestSimpleQmlLoad::compileAndLoadListView1() { QQmlEngine *engine = new QQmlEngine; const QString TEST_FILE(":/testqml/testlistview1.qml"); QList<QObject*> l; l.append(new TestObject(1)); engine->rootContext()->setContextProperty("model1", QVariant::fromValue(l)); QQmlComponent* component = compileAndLoad(engine, TEST_FILE); QVERIFY(component); QObject *myObject = component->create(); QVERIFY(myObject != NULL); delete component; delete engine; }
int main(int argc, char* argv[]) { QScopedPointer<qf::core::LogDevice> file_log_device(qf::core::FileLogDevice::install()); file_log_device->setDomainTresholds(argc, argv); file_log_device->setPrettyDomain(true); qfError() << QThread::currentThread() << "QFLog(ERROR) test OK."; qfWarning() << "QFLog(WARNING) test OK."; qfInfo() << "QFLog(INFO) test OK."; qfDebug() << "QFLog(DEBUG) test OK."; TheApp app(argc, argv); QCoreApplication::setOrganizationName("OrienteeringTools"); QCoreApplication::setOrganizationDomain("sourceforge.net"); QCoreApplication::setApplicationName("QSiCli"); QQmlEngine engine; #ifdef Q_OS_UNIX engine.addImportPath(QCoreApplication::applicationDirPath() + "/../lib/qml"); #else engine.addImportPath(QCoreApplication::applicationDirPath() + "/qml"); #endif engine.rootContext()->setContextProperty("TheApp", &app); QUrl extensions_url = QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/divers/qsicli/extensions/qml/init.qml"); qfDebug() << "creating extensions on path:" << extensions_url.toString(); QQmlComponent component(&engine, extensions_url); if(!component.isReady()) { qfError() << component.errorString(); } else { QObject *extensions_root = qobject_cast<QWidget*>(component.create()); qfDebug() << "extensions created" << extensions_root; } MainWindow w; //qDebug() << "showing main window"; w.show(); //qDebug() << "enterring the message loop"; int ret = app.exec(); qfInfo() << "bye ..."; return ret; }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); // регистриуем QML типы qmlRegisterType<ChatClient>("ChatClient", 1,0, "ChatClient"); qmlRegisterType<ChatUser>("ChatUser", 1,0, "ChatUser"); qmlRegisterType<Message>("Message", 1,0, "Message"); qRegisterMetaType<ChatUser::ChatUserId>("ChatUserId"); QQmlEngine *engine = new QQmlEngine(); // close window -> quit app app.connect(engine, SIGNAL(quit()), SLOT(quit())); ChatClient * client = new ChatClient; // регистрируем QML доступные переменные engine->rootContext()->setContextProperty("client", client); QQmlComponent *component = new QQmlComponent(engine); component->loadUrl(QUrl("qrc:/qml/main.qml")); QObject *object = component->create(); QQuickWindow *window = qobject_cast<QQuickWindow *>(object); window->show(); return app.exec(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlEngine engine; qmlRegisterType<SpeakerModel>("ddt.model", 1, 0, "SpeakerModel"); qmlRegisterType<QListQmlWrapper>("ddt.model", 1, 0, "QListQMLWrapper"); qmlRegisterUncreatableType<Debate>("ddt.model", 1, 0, "Debate", "Debate is abstract."); qmlRegisterType<OPDebate>("ddt.model", 1, 0, "OPDDebate"); qmlRegisterType<BPSDebate>("ddt.model", 1, 0, "BPSDebate"); qmlRegisterType<SeatToSpeakerMapper>("ddt.model", 1, 0, "SeatToSpeakerMapper"); qmlRegisterType<MainModel>("ddt.model", 1, 0, "MainModel"); qmlRegisterType<TableNames>("ddt.model", 1, 0, "TableNames"); qmlRegisterType<Team>("ddt.model", 1, 0, "Team"); qmlRegisterType<AutoCompleteModel>("ddt.model", 1, 0, "AutoCompleteModel"); qmlRegisterType<MixedValueSpeakerModel>("ddt.model",1, 0, "MixedValueSpeakerModel"); QQmlComponent component(&engine); MainModel *rootModel = new MainModel(); engine.rootContext()->setContextProperty("rootModel", rootModel); component.loadUrl(QUrl("qml/ddt/main.qml")); if ( !component.isReady() ) { qWarning("%s", qPrintable(component.errorString())); return -1; } QObject *topLevel = component.create(); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); if ( !window ) { qWarning("Error: Your root item has to be a Window."); return -1; } QObject::connect(&engine, SIGNAL(quit()), &app, SLOT(quit())); window->show(); return app.exec(); }
void tst_qqmllistreference::engineTypes() { QQmlEngine engine; QQmlComponent component(&engine, testFileUrl("engineTypes.qml")); QObject *o = component.create(); QVERIFY(o); QQmlProperty p1(o, QLatin1String("myList")); QVERIFY(p1.propertyTypeCategory() == QQmlProperty::List); QQmlProperty p2(o, QLatin1String("myList"), engine.rootContext()); QVERIFY(p2.propertyTypeCategory() == QQmlProperty::List); QVariant v = p2.read(); QVERIFY(v.userType() == qMetaTypeId<QQmlListReference>()); QQmlListReference ref = qvariant_cast<QQmlListReference>(v); QVERIFY(ref.count() == 2); QVERIFY(ref.listElementType()); QVERIFY(ref.listElementType() != &QObject::staticMetaObject); delete o; }
TrackListPanel::TrackListPanel(const iscore::ApplicationContext &ctx): iscore::PanelDelegate{ctx}, m_widget{new QWidget}, m_trackModel(new TrackModel), m_layout{new QVBoxLayout}, m_containerpanel{new QMLContainerPanel} { m_trackModel->addTrack(Track(100, 0, 0)); QQuickWidget* container = m_containerpanel->container(); QQmlEngine* engine = container->engine(); QQmlContext* rootctxt = engine->rootContext(); rootctxt->setContextProperty(QString("trackModel"), m_trackModel); m_containerpanel->setSource(QString("qrc:/qml/TrackList.qml")); m_containerpanel->setContainerSize(m_containerpanel->size()); m_containerpanel->setObjectName("TrackList"); m_containerpanel->setBaseSize(m_widget->size()); m_layout->addWidget(m_containerpanel); m_widget->setLayout(m_layout); }
Main::Main(Marsyas::MarSystem * system) { root_system = system; //qRegisterMetaType<Marsyas::MarSystem*>(); qmlRegisterType<MarSystemView>("Marsyas", 1, 0, "MarSystemView"); qmlRegisterType<MarSystemViewAttached>(); qmlRegisterType<MarSystemControlView>("Marsyas", 1, 0, "MarSystemControlView"); QQmlEngine *engine = new QQmlEngine(this); //engine->rootContext()->setContextProperty("myModel", QVariant::fromValue<QObject*>(model)); engine->rootContext()->setContextProperty("mySystem", QVariant::fromValue(system)); #if 0 QQmlComponent component(&engine, QString("main.qml")); if (component.status() != QQmlComponent::Ready) { qCritical("Not ready!"); return 1; } QObject *root_view = component.create(); if (!root_view) return 1; root_view->setProperty("model", QVariant::fromValue<QObject*>(model)); //root_view->setProperty("index"); //root_view->setProperty("text", QString::fromStdString(system->getPrefix())); QQuickWindow *window = new QQuickWindow(); root_view->setParent( window->contentItem() ); window->show(); #endif toolbar = new QToolBar(); QAction *tick_action = toolbar->addAction("Tick"); connect( tick_action, SIGNAL(triggered()), this, SLOT(tickSystem()) ); /////////////////// system_view = new QQuickView(engine, 0); system_view->setColor( QApplication::palette().color(QPalette::Window) ); system_view->setSource(QUrl::fromLocalFile("/home/jakob/programming/marsyas/src/qt5apps/inspector/main.qml")); system_view->setResizeMode(QQuickView::SizeRootObjectToView); QWidget *marsystem_widget = QWidget::createWindowContainer(system_view); marsystem_widget->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); controls_widget = new ControlsWidget; controls_widget->setSystem(system); //controls_widget->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); realvec_widget = new RealvecWidget; realvec_widget->setSystem(system); //realvec_widget->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); QObject::connect( controls_widget, SIGNAL(controlClicked(QString)), realvec_widget, SLOT(displayControl(QString)) ); QSplitter *data_splitter = new QSplitter(); data_splitter->setOrientation( Qt::Vertical ); data_splitter->addWidget( controls_widget ); data_splitter->addWidget( realvec_widget ); QSplitter *splitter = new QSplitter(); splitter->addWidget( marsystem_widget ); splitter->addWidget( data_splitter ); QVBoxLayout *column = new QVBoxLayout(); column->addWidget(toolbar); column->addWidget(splitter); QWidget *window = new QWidget(); window->setLayout(column); window->resize(1000, 600); window->show(); //window->showMaximized(); QObject *system_item = system_view->rootObject(); if (system_item) { QObject::connect( system_item, SIGNAL(clicked(QString)), this, SLOT(systemClicked(QString)) ); } else { qWarning("Could not find top system item!"); } QShortcut *quit_shortcut = new QShortcut(QString("Ctrl+Q"), splitter); QObject::connect( quit_shortcut, SIGNAL(activated()), qApp, SLOT(quit()) ); }
int main(int argc, char *argv[]) { QOptions options(get_common_options()); options.add(QLatin1String("QMLPlayer options")) ("scale", 1.0, QLatin1String("scale of graphics context. 0: auto")) ; options.parse(argc, argv); if (options.value(QLatin1String("help")).toBool()) { options.print(); return 0; } QGuiApplication app(argc, argv); QDir::setCurrent(qApp->applicationDirPath()); qDebug() << "arguments======= " << app.arguments(); set_opengl_backend(options.option(QStringLiteral("gl")).value().toString(), app.arguments().first()); load_qm(QStringList() << QStringLiteral("QMLPlayer"), options.value(QStringLiteral("language")).toString()); QtQuick2ApplicationViewer viewer; QString binDir = qApp->applicationDirPath(); if (binDir.endsWith(QLatin1String(".app/Contents/MacOS"))) { binDir.remove(QLatin1String(".app/Contents/MacOS")); binDir = binDir.left(binDir.lastIndexOf(QLatin1String("/"))); } QQmlEngine *engine = viewer.engine(); if (!engine->importPathList().contains(binDir)) engine->addImportPath(binDir); qDebug() << engine->importPathList(); engine->rootContext()->setContextProperty(QStringLiteral("PlayerConfig"), &Config::instance()); qDebug(">>>>>>>>devicePixelRatio: %f", qApp->devicePixelRatio()); QScreen *sc = app.primaryScreen(); qDebug() << "dpi phy: " << sc->physicalDotsPerInch() << ", logical: " << sc->logicalDotsPerInch() << ", dpr: " << sc->devicePixelRatio() << "; vis rect:" << sc->virtualGeometry(); // define a global var for js and qml engine->rootContext()->setContextProperty(QStringLiteral("screenPixelDensity"), qApp->primaryScreen()->physicalDotsPerInch()*qApp->primaryScreen()->devicePixelRatio()); qreal r = sc->physicalDotsPerInch()/sc->logicalDotsPerInch(); if (std::isinf(r) || std::isnan(r)) #if defined(Q_OS_ANDROID) r = 2.0; #else r = 1.0; #endif float sr = options.value(QStringLiteral("scale")).toFloat(); #if defined(Q_OS_ANDROID) sr = r; if (sr > 2.0) sr = 2.0; //FIXME #endif if (qFuzzyIsNull(sr)) sr = r; engine->rootContext()->setContextProperty(QStringLiteral("scaleRatio"), sr); QString qml = QStringLiteral("qml/QMLPlayer/main.qml"); if (QFile(qApp->applicationDirPath() + QLatin1String("/") + qml).exists()) qml.prepend(qApp->applicationDirPath() + QLatin1String("/")); else qml.prepend(QLatin1String("qrc:///")); viewer.setMainQmlFile(qml); viewer.show(); QOption op = options.option(QStringLiteral("width")); if (op.isSet()) viewer.setWidth(op.value().toInt()); op = options.option(QStringLiteral("height")); if (op.isSet()) viewer.setHeight(op.value().toInt()); op = options.option(QStringLiteral("x")); if (op.isSet()) viewer.setX(op.value().toInt()); op = options.option(QStringLiteral("y")); if (op.isSet()) viewer.setY(op.value().toInt()); if (options.value(QStringLiteral("fullscreen")).toBool()) viewer.showFullScreen(); viewer.setTitle(QStringLiteral("QMLPlayer based on QtAV. [email protected]")); /* * find root item, then root.init(argv). so we can deal with argv in qml */ #if 1 QString json = app.arguments().join(QStringLiteral("\",\"")); json.prepend(QLatin1String("[\"")).append(QLatin1String("\"]")); json.replace(QLatin1String("\\"), QLatin1String("/")); //FIXME QMetaObject::invokeMethod(viewer.rootObject(), "init", Q_ARG(QVariant, json)); //#else QObject *player = viewer.rootObject()->findChild<QObject*>(QStringLiteral("player")); if (player) { AppEventFilter *ae = new AppEventFilter(player, player); qApp->installEventFilter(ae); } QString file; #ifdef Q_OS_ANDROID file = QAndroidJniObject::callStaticObjectMethod("org.qtav.qmlplayer.QMLPlayerActivity" , "getUrl" , "()Ljava/lang/String;") .toString(); #endif if (app.arguments().size() > 1) { file = options.value(QStringLiteral("file")).toString(); if (file.isEmpty()) { if (argc > 1 && !app.arguments().last().startsWith(QLatin1Char('-')) && !app.arguments().at(argc-2).startsWith(QLatin1Char('-'))) file = app.arguments().last(); } } qDebug() << "file: " << file; if (player && !file.isEmpty()) { if (!file.startsWith(QLatin1String("file:")) && QFile(file).exists()) file.prepend(QLatin1String("file:")); //qml use url and will add qrc: if no scheme file.replace(QLatin1String("\\"), QLatin1String("/")); //qurl QMetaObject::invokeMethod(player, "play", Q_ARG(QUrl, QUrl(file))); } #endif QObject::connect(viewer.rootObject(), SIGNAL(requestFullScreen()), &viewer, SLOT(showFullScreen())); QObject::connect(viewer.rootObject(), SIGNAL(requestNormalSize()), &viewer, SLOT(showNormal())); ScreenSaver::instance().disable(); //restore in dtor return app.exec(); }