int main(int argc, char* argv[]) { QApplication app(argc, argv); qRegisterMetaType<TreeViewModel>("TreeViewModel"); qRegisterMetaType<ConfigNode> ("ConfigNode"); qRegisterMetaType<UndoManager> ("UndoManager"); qRegisterMetaType<GUIBackend> ("GUIBackend"); qRegisterMetaType<GUISettings> ("GUISettings"); qmlRegisterType<DataContainer> ("org.libelektra.qtgui", 1, 0, "DataContainer"); QString locale = QLocale::system().name(); QTranslator translator; translator.load(QString(":/qml/i18n/lang_") + locale + QString(".qm")); app.installTranslator(&translator); QQmlApplicationEngine engine; QQmlContext* ctxt = engine.rootContext(); UndoManager manager; GUIBackend backend; GUISettings settings; TreeViewModel treeModel; engine.setObjectOwnership(&treeModel, QQmlApplicationEngine::CppOwnership); ctxt->setContextProperty("undoManager", &manager); ctxt->setContextProperty("externTreeModel", &treeModel); ctxt->setContextProperty("guiBackend", &backend); ctxt->setContextProperty("guiSettings", &settings); treeModel.populateModel(); engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); return app.exec(); }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QString path("."); if (argc == 2) { path = argv[1]; } QtQuick2ApplicationViewer viewer; GitProject git; git.setCurrentPath(path); QQmlContext *context = viewer.rootContext(); context->setContextProperty("gGit", &git); viewer.setMainQmlFile(QStringLiteral("qml/GitGrown/main.qml")); viewer.showExpanded(); return app.exec(); }
bool Chimera_Win::onWindowAttached( FB::AttachedEvent *evt, FB::PluginWindowWin* w ) { vlc_open(); m_quickViewPtr.reset( new QQuickView ); m_quickViewPtr->setResizeMode( QQuickView::SizeRootObjectToView ); m_quickViewPtr->setProperty( "_q_embedded_native_parent_handle", WId( w->getHWND() ) ); m_quickViewPtr->setFlags( m_quickViewPtr->flags() | Qt::FramelessWindowHint ); QQmlContext* context = m_quickViewPtr->rootContext(); m_qmlVlcPlayer = new QmlVlcSurfacePlayerProxy( (vlc::player*)this, m_quickViewPtr.data() ); m_qmlVlcPlayer->classBegin(); context->setContextProperty( "vlcPlayer", QVariant::fromValue( m_qmlVlcPlayer ) ); process_startup_options(); m_quickViewPtr->setSource( getQmlSource() ); MoveWindow( (HWND)m_quickViewPtr->winId(), 0, 0, w->getWindowWidth(), w->getWindowHeight(), FALSE ); m_quickViewPtr->show(); return false; }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext* context = engine.rootContext(); QString currPath = QDir::currentPath(); context->setContextProperty("currentPath", currPath); QScreen *screen = QApplication::screens().at(0); int width = screen->availableSize().width(); context->setContextProperty("availableWidth", width); int height = screen->availableSize().height(); context->setContextProperty("availableHeight", height); MainController* mainController = new MainController(); context->setContextProperty("mainController", mainController); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; DataMethods methodsStopWatch("stopwatchResults.txt"); DataMethods methodsCountDown("countdownResults.txt"); //load stored results from .txt files to listViews of stopWatch and countDown sections methodsStopWatch.loadData(); methodsCountDown.loadData(); QQmlContext *ctxt = engine.rootContext(); //give access to saved models in .txt to stopWatch and countDown sections in QML ( used upon new sesion of program) ctxt->setContextProperty("myStopWatchModel",QVariant::fromValue(&methodsStopWatch)); ctxt->setContextProperty("myCountDownModel",QVariant::fromValue(&methodsCountDown)); //give option to manipulate ( add results and save/clear) .txt file with methods inside DataMethods ctxt->setContextProperty("saveStopWatchModel",QVariant::fromValue(&methodsStopWatch)); ctxt->setContextProperty("saveCountDownModel",QVariant::fromValue(&methodsCountDown)); engine.load(QUrl(QStringLiteral("qrc:/mainSW.qml"))); return app.exec(); }
void MainWindow::updateStatistics() { QQmlContext* context = m_statistics_view->rootContext(); context->setContextProperty("network_total_count", m_network_statistics->totalCount()); context->setContextProperty("network_successful_count", m_network_statistics->successfulCount()); context->setContextProperty("network_failed_count", m_network_statistics->failedCount()); context->setContextProperty("network_slow_count", m_network_statistics->tooSlowConnectionsCount()); context->setContextProperty("network_pending_count", m_network_statistics->pendingConnectionsCount()); }
int main(int argc, char* argv[]) { QApplication app(argc, argv); qDebug() << "library paths" << app.libraryPaths(); QQmlApplicationEngine engine; engine.addImportPath("libview"); // We must set the locale always to C as some tools won't work correctly without it. // e.g. decimal points will always be "." this way. QLocale::setDefault(QLocale::c()); qDebug() << "QLibrary" << QLibraryInfo::location(QLibraryInfo::LibraryExecutablesPath); qDebug() << "QLibraryPrefix" << QLibraryInfo::location(QLibraryInfo::PrefixPath); qDebug() << "QLibraryLocation" << QLibraryInfo::location(QLibraryInfo::LibrariesPath); QtWebEngine::initialize(); PythonLoader pythonLoader{&app}; QObject* dice = pythonLoader.getObject("dice.main", "Dice"); if (!dice) { qDebug() << "Could not initialize the python core!"; return -1; } QQmlContext* context = engine.rootContext(); QVariant vEngine, vContext; vEngine.setValue(&engine); vContext.setValue(context); dice->setProperty("qmlEngine", vEngine); dice->setProperty("qmlContext", vContext); context->setContextProperty("dice", dice); engine.load(QUrl("libview/Window/main.qml")); app.topLevelWindows().first()->setIcon(QIcon("libview/Window/images/dice_logo_grey.svg")); return app.exec(); }
QWidget* GUIExchangesWidget::dockQmlToWidget() { QQuickView* pExchangesWindow = new QQuickView; QWidget* pPlaceHolder = 0; if ( pExchangesWindow ) { QQmlContext* pContext = pExchangesWindow->rootContext(); if ( pContext ) { pContext->setContextProperty( "GUI20Skin", &GUI20Skin::Instance() ); } QQmlEngine* pEngine = pExchangesWindow->engine(); if ( pEngine ) { m_pQmlImageProvider = new QmlImageProvider(); pEngine->addImageProvider( "exchangesImages", m_pQmlImageProvider ); } pExchangesWindow->setSource( QUrl( QStringLiteral( "qrc:/qml/qtquick_controls/qml/QmlGUIExchangesWindow.qml" ) ) ); QQuickItem* pRootObject = pExchangesWindow->rootObject(); if ( pRootObject ) { m_pExchangesControl = pRootObject->findChild<GUIExchangesControl*>(); if ( m_pExchangesControl ) { } } pPlaceHolder = QWidget::createWindowContainer( pExchangesWindow, this ); if ( pPlaceHolder ) { pPlaceHolder->setMinimumSize( 500, 170 ); pPlaceHolder->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); } } return pPlaceHolder; }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; UdpSeret * udpSeret = new UdpSeret(&app); udpExtraDataCACC * udpXDataCACC = new udpExtraDataCACC(&app); UDPSender * udpSender = new UDPSender(&app); UDPVehicle * udpVehicle=new UDPVehicle(&app); QQmlContext * rc = engine.rootContext(); rc->setContextProperty("udpSeret", udpSeret); rc->setContextProperty("udpXDataCACC", udpXDataCACC); rc->setContextProperty("udpSender",udpSender); rc->setContextProperty("udpVehicle",udpVehicle); qmlRegisterType<FileIO, 1>("FileIO", 1, 0, "FileIO"); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); db.setDatabaseName("terkas"); db.setHostName("localhost"); db.setUserName("postgres"); db.setPassword("monrepo"); db.setPort(5432); if (!db.open()) { qDebug() << "ERROR: Database not opened: " << db.lastError().text(); return 0; } StatisticsModel *statisticsModel = new StatisticsModel; QQmlApplicationEngine engine; QQmlContext *ctx = engine.rootContext(); ctx->setContextProperty("statisticsModel", QVariant::fromValue(statisticsModel)); engine.load(QUrl(QStringLiteral("qrc:/qml/Main.qml"))); return app.exec(); }
int main(int argc, char *argv[]) { //! [0] QGuiApplication app(argc, argv); QtWebView::initialize(); //! [0] QGuiApplication::setApplicationDisplayName(QCoreApplication::translate("main", "QtWebView Example")); QCommandLineParser parser; QCoreApplication::setApplicationVersion(QT_VERSION_STR); parser.setApplicationDescription(QGuiApplication::applicationDisplayName()); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("url", "The initial URL to open."); QStringList arguments = app.arguments(); #ifdef Q_OS_WINRT arguments.removeAt(1); // The launcher always passes in the -ServerName parameter, breaking the command line parser #endif parser.process(arguments); const QString initialUrl = parser.positionalArguments().isEmpty() ? QStringLiteral("qt.io") : parser.positionalArguments().first(); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); context->setContextProperty(QStringLiteral("utils"), new Utils(&engine)); context->setContextProperty(QStringLiteral("initialUrl"), Utils::fromUserInput(initialUrl)); QRect geometry = QGuiApplication::primaryScreen()->availableGeometry(); if (!QGuiApplication::styleHints()->showIsFullScreen()) { const QSize size = geometry.size() * 4 / 5; const QSize offset = (geometry.size() - size) / 2; const QPoint pos = geometry.topLeft() + QPoint(offset.width(), offset.height()); geometry = QRect(pos, size); } context->setContextProperty(QStringLiteral("initialX"), geometry.x()); context->setContextProperty(QStringLiteral("initialY"), geometry.y()); context->setContextProperty(QStringLiteral("initialWidth"), geometry.width()); context->setContextProperty(QStringLiteral("initialHeight"), geometry.height()); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
void ManaPlugin::initializeEngine(QQmlEngine *engine, const char *uri) { Mana::ResourceManager *resourceManager = new Mana::ResourceManager(engine); Mana::AttributeDB *attributeDB = new Mana::AttributeDB(engine); Mana::HairDB *hairDB = new Mana::HairDB(engine); Mana::ItemDB *itemDB = new Mana::ItemDB(engine); Mana::MonsterDB *monsterDB = new Mana::MonsterDB(engine); Mana::NpcDB *npcDB = new Mana::NpcDB(engine); Mana::RaceDB *raceDB = new Mana::RaceDB(engine); QQmlContext *context = engine->rootContext(); context->setContextProperty("resourceManager", resourceManager); context->setContextProperty("attributeDB", attributeDB); context->setContextProperty("hairDB", hairDB); context->setContextProperty("itemDB", itemDB); context->setContextProperty("monsterDB", monsterDB); context->setContextProperty("npcDB", npcDB); context->setContextProperty("raceDB", raceDB); int errorCode = enet_initialize(); Q_ASSERT(errorCode == 0); atexit(enet_deinitialize); }
void BrowserWindowMobile::setupDeclarativeEnvironment() { QQmlContext* context = rootContext(); context->setContextProperty("BrowserWindow", this); DatabaseManager* dbManager = DatabaseManager::instance(); context->setContextProperty("HistoryModel", dbManager->historyDataBaseModel()); context->setContextProperty("BookmarkModel", dbManager->bookmarkDataBaseModel()); context->setContextProperty("TabsModel", new TabsModel(this)); context->setContextProperty("UrlTools", new UrlTools(this)); QObject::connect(engine(), SIGNAL(quit()), qApp, SLOT(quit())); setResizeMode(QQuickView::SizeRootObjectToView); #if defined(SNOWSHOE_MEEGO_HARMATTAN) reportContentOrientationChange(Qt::PortraitOrientation); setSource(QUrl("qrc:///mobile/qml/main-harmattan.qml")); #else setSource(QUrl("qrc:///mobile/qml/Main.qml")); #endif }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QGuiApplication::setApplicationDisplayName(QCoreApplication::translate("main", "QtWebView Example")); #ifdef QT_WEBVIEW_WEBENGINE_BACKEND QtWebEngine::initialize(); #endif // QT_WEBVIEW_WEBENGINE_BACKEND QCommandLineParser parser; QCoreApplication::setApplicationVersion(QT_VERSION_STR); parser.setApplicationDescription(QGuiApplication::applicationDisplayName()); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("url", "The initial URL to open."); parser.process(app); const QString initialUrl = parser.positionalArguments().isEmpty() ? QStringLiteral("qt.io") : parser.positionalArguments().first(); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); context->setContextProperty(QStringLiteral("utils"), new Utils(&engine)); context->setContextProperty(QStringLiteral("initialUrl"), Utils::fromUserInput(initialUrl)); QRect geometry = QGuiApplication::primaryScreen()->availableGeometry(); if (!QGuiApplication::styleHints()->showIsFullScreen()) { const QSize size = geometry.size() * 4 / 5; const QSize offset = (geometry.size() - size) / 2; const QPoint pos = geometry.topLeft() + QPoint(offset.width(), offset.height()); geometry = QRect(pos, size); } context->setContextProperty(QStringLiteral("initialX"), geometry.x()); context->setContextProperty(QStringLiteral("initialY"), geometry.y()); context->setContextProperty(QStringLiteral("initialWidth"), geometry.width()); context->setContextProperty(QStringLiteral("initialHeight"), geometry.height()); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
int main(int argc, char *argv[]) { Py_SetProgramName(GetWC(argv[0])); qDebug()<<"Version Of QT: "<<qVersion(); // Load env from QML path char* qml_env_path; qml_env_path = getenv("AFERMER_QML_PATH"); fs::path qml_app_path("/"); if (qml_env_path == NULL) { std::cerr << "AFERMER_QML_PATH not present or directory does not exist. Take directory from startup " << std::endl; fs::path full_path( fs::initial_path<fs::path>() ); full_path = fs::system_complete( fs::path( argv[0] ) ); qml_app_path = full_path.parent_path() / "qml"; if (!fs::exists( qml_app_path )) { std::cerr << "QML directory (" << qml_app_path << ") not found. Exit" << std::endl; return 1; } } else { qml_app_path = fs::path(qml_env_path); } fs::path qml_app_icon_path(qml_app_path); qml_app_icon_path /= "icons"; qml_app_icon_path /= "soft_circl_icon.png"; qml_app_path /= "main.qml"; QGuiApplication app(argc, argv); app.setOrganizationName("afermer"); app.setWindowIcon(QIcon(qml_app_icon_path.string().c_str())); BladeState::declareQML(); JobState::declareQML(); TaskState::declareQML(); QQmlApplicationEngine engine; General general; JobsModel jobs_model; BladesModel blades_model; UsersModel users_model; TasksModel tasks_model; QQmlContext *ctxt =engine.rootContext(); //ctxt->setContextProperty("server_exist", "yes"); ctxt->setContextProperty("General", &general); ctxt->setContextProperty("JobsModel", &jobs_model); ctxt->setContextProperty("BladesModel", &blades_model); ctxt->setContextProperty("UsersModel", &users_model); ctxt->setContextProperty("TasksModel", &tasks_model); engine.load(QUrl::fromLocalFile(qml_app_path.string().c_str())); QObject *rootObject = engine.rootObjects().first(); rootObject->setProperty("visible", true); engine.collectGarbage(); return app.exec(); }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); // QtQuick2ApplicationViewer viewer; // viewer.setMainQmlFile(QStringLiteral("qml/GUI-Scenario/main.qml")); // viewer.showExpanded(); //temp for testing // Story* story; // Item* hammer = new Item{"hammer"}; // //story->add_item(hammer); // QMap<QString, qint16> attributes; // attributes["hp"] = 10; // Character player1{};//attributes, 5, story}; //// player1.set_name("player1"); //// player1.add_to_attribute("hp", 10); // Character player2; // player2.set_name("player2"); //// player2.add_to_attribute("hp", 13); // //player1.add_item(1); does not work for some reasaon LOOK IT UP!!!!! // QList<Character*> characterlist; // //characterlist.append(&player1); // characterlist.append(&player2); // QMap<quint16, Item*> items; // items[1] = hammer; //// qDebug() << "before add"; //// player1.add_item(1); //// qDebug() << "after add"; /// /// //from other main QList<QString> attr_list{"health", "armor", "strength"}; Ruleset *rs; rs = new Ruleset(attr_list); Story* main_story = new Story(rs); QMap<QString, qint16> attr_map{{"health", 10}, {"armor", 2}, {"strength", 5}}; main_story->add_character(new Character(attr_map, 50, main_story)); Character* bob = main_story->get_characters().front(); bob->set_name("BOB!"); try { Item* hammer1 = new Item("Hammer of doom"); main_story->add_item(hammer1); hammer1->set_attribute("Weight", 20); Item* hammer2 = new Item("nicer hammah"); main_story->add_item(hammer2); hammer2->set_attribute("Weight", 20); hammer2->set_attribute("bonk", 50); hammer2->set_attribute("smash", 3000); bob->add_item(hammer1->get_id()); bob->add_item(hammer2->get_id()); qDebug() << "Bob's stuff:"; for (auto item_id : bob->inventory.get_items()) { qDebug() << main_story->get_items().value(item_id)->get_name(); } } catch (const std::out_of_range& e) { qDebug() << "out_of_range exception: " << e.what(); } Character* herman = new Character(attr_map, 10, main_story); main_story->add_character(herman); herman->set_name("Herr Man"); rs->add_skill(new Skill("Break those cuffs")); rs->add_skill(new Skill("Eat horse")); rs->get_skills().at(0)->set_modifier("int", 10); rs->get_skills().at(0)->set_modifier("str", 11); rs->get_skills().at(1)->set_modifier("int" , 5); rs->get_skills().at(1)->set_modifier("str", 25); bob->add_skill(rs->get_skills().at(0)); bob->add_skill(rs->get_skills().at(1)); herman->add_skill(rs->get_skills().at(1)); //connect signals from QML // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(testSignal(QString)),&controller, SLOT(oklart(QString))); // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(setDropAreaParent(int)),&controller, SLOT(set_active_block_number_(int))); // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(setDropAreaSide(QString)),&controller, SLOT(set_active_block_side(QString))); // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(add_block(int, QString)),&controller, SLOT(add_block(int,QString))); // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(editValueBlock(QString, bool, int)),&controller, SLOT(edit_valueblock(QString, bool, int))); // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(setCompareBlockValue(int)),&controller, SLOT(set_compareblock_value(int))); // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(editDamageBlock(QString, bool, int)),&controller, SLOT(edit_damageblock(QString, bool, int))); // //TODO: complete signals below // QObject::connect((QObject*)viewer.rootObject(), SIGNAL(editCompareBlock(QString, bool, int)),&controller, SLOT(edit_compareblock(QString, bool, int))); // QStringList dataList; // dataList.append("Item 1"); // dataList.append("Item 2"); // dataList.append("Item 3"); // dataList.append("Item 4"); // dataList.append("Item 1"); // dataList.append("Item 2"); // dataList.append("Item 3"); // dataList.append("Item 4"); // dataList.append("Item 1"); // dataList.append("Item 2"); // dataList.append("Item 3"); // dataList.append("Item 4"); // dataList.append("Item 1"); // dataList.append("Item 2"); // dataList.append("Item 3"); // dataList.append("Item 4"); // // export instance to qml // QQmlContext *ctxt = viewer.rootContext(); // ctxt->setContextProperty("controller", &controller); //ctxt->setContextProperty("dataList", QVariant::fromValue(dataList)); //ctxt->setContextProperty("sController", &controller); //QML QtQuick2ApplicationViewer viewer; // create a controller ScenarioController controller{herman, main_story->get_characters(),main_story->get_items(),rs->get_skills(),rs->get_attributes()}; // export instance to qml QQmlContext *ctxt = viewer.rootContext(); ctxt->setContextProperty("controller", &controller); viewer.setMainQmlFile(QStringLiteral("qml/GUI-Scenario/main.qml")); viewer.showExpanded(); return app.exec(); }
void StartIlwis::init() { try{ QQmlContext *ctx =_engine->rootContext(); if(!Ilwis::initIlwis(Ilwis::rmDESKTOP)){ exit(-1); } QFileInfo ilwisroot = context()->ilwisFolder(); QString qmlpluginpath = ilwisroot.absoluteFilePath() + "/extensions/ui"; _engine->addImportPath(qmlpluginpath); _engine->addPluginPath(qmlpluginpath); qmlRegisterType<MasterCatalogModel>("MasterCatalogModel",1,0,"MasterCatalogModel"); qmlRegisterType<CatalogModel>("CatalogModel",1,0,"CatalogModel"); qmlRegisterType<WorkSpaceModel>("WorkSpaceModel",1,0,"WorkSpaceModel"); qmlRegisterType<ResourceModel>("ResourceModel",1,0,"ResourceModel"); qmlRegisterType<OperationCatalogModel>("OperationCatalogModel",1,0,"OperationCatalogModel"); qmlRegisterType<OperationModel>("OperationModel",1,0,"OperationModel"); qmlRegisterType<ApplicationFormExpressionParser>("ApplicationFormExpressionParser",1,0,"FormBuilder"); qmlRegisterType<WorkflowMetadataFormBuilder>("WorkflowMetadataFormBuilder",1,0,"WorkflowMetadataFormBuilder"); qmlRegisterType<UserMessageHandler>("UserMessageHandler",1,0,"UserMessageHandler"); qmlRegisterType<MessageModel>("MessageModel",1,0,"MessageModel"); qmlRegisterType<Ilwis::Ui::TranquilizerHandler>("TranquilizerHandler",1,0, "TranquilizerHandler"); qmlRegisterType<TranquilizerModel>("TranquilizerModel",1,0, "TranquilizerModel"); qmlRegisterType<LayerManager>("LayerManager",1,0,"LayerManager"); qmlRegisterType<Ilwis::Ui::LayerModel>("LayerModel",1,0,"LayerModel"); qmlRegisterType<RootLayerModel>("RootLayerModel",1,0,"GlobalLayerModel"); qmlRegisterType<IlwisObjectModel>("IlwisObjectModel",1,0,"IlwisObjectModel"); qmlRegisterType<AttributeModel>("AttributeModel",1,0,"AttributeModel"); qmlRegisterType<VisualAttribute>("VisualAttribute",1,0,"VisualAttribute"); qmlRegisterType<Ilwis::Ui::DomainItemModel>("DomainItemModel",1,0,"DomainItemModel"); qmlRegisterType<OperationsByKeyModel>("OperationsByKeyModel",1,0,"OperationsByKeyModel"); qmlRegisterType<UIContextModel>("UIContextModel", 1,0, "UIContextModel"); qmlRegisterType<VisualPropertyEditor>("VisualPropertyEditor", 1,0, "VisualPropertyEditor"); qmlRegisterType<NumericRepresentationSetter>("NumericRepresentationSetter", 1,0, "NumericRepresentationSetter"); qmlRegisterType<ItemRepresentationSetter>("ItemRepresentationSetter", 1,0, "ItemRepresentationSetter"); qmlRegisterType<RepresentationElementModel>("RepresentationElement", 1,0, "RepresentationElement"); qmlRegisterType<ProjectionParameterModel>("ProjectionParameterModel", 1,0, "ProjectionParameterModel"); qmlRegisterType<WorkflowModel>("WorkflowModel", 1,0, "WorkflowModel"); qmlRegisterType<CatalogOperationEditor>("CatalogOperationEditor", 1, 0, "CatalogOperationEditor"); qmlRegisterType<TableModel>("TableModel", 1,0,"TableModel"); qmlRegisterType<TableOperation>("TableOperation",1,0,"TableOperation"); qmlRegisterType<ColumnModel>("ColumnModel", 1,0,"ColumnModel"); qmlRegisterType<LayerInfoItem>("LayerInfoItem", 1,0,"LayerInfoItem"); qmlRegisterType<CatalogMapItem>("CatalogMapItem", 1,0,"CatalogMapItem"); qmlRegisterType<ChartModel>("ChartModel", 1, 0, "ChartModel"); qmlRegisterType<DataseriesModel>("DataseriesModel", 1, 0, "DataseriesModel"); qmlRegisterType<ChartOperationEditor>("ChartOperationEditor", 1, 0, "ChartOperationEditor"); qmlRegisterType<CatalogFilterModel>("CatalogFilterModel", 1,0,"CatalogFilterModel"); qmlRegisterType<DataPaneModel>("DataPaneModel", 1,0,"DataPaneModel"); qmlRegisterType<TabModel>("TabModel", 1,0,"TabModel"); qmlRegisterType<SidePanelModel>("SidePanelModel", 1,0,"SidePanelModel"); qmlRegisterType<ObjectCreator>("ObjectCreator", 1,0,"ObjectCreator"); qmlRegisterType<IlwisObjectCreatorModel>("IlwisObjectCreatorModel", 1,0,"IlwisObjectCreatorModel"); qmlRegisterType<ModelBuilder>("ModelBuilder", 1,0,"ModelBuilder"); qmlRegisterType<ModelDesigner>("ModelDesigner", 1,0,"ModelDesigner"); qmlRegisterType<ErrorModel>("ErrorModel", 1,0,"ErrorModel"); qmlRegisterType<PreferencesModel>("PreferencesModel",1,0,"PreferencesModel"); qmlRegisterType<InternalDatabaseModel>("InternalDatabaseModel",1,0,"InternalDatabaseModel"); qmlRegisterType<ScriptModel>("ScriptModel",1,0,"ScriptModel"); qmlRegisterType<ApplicationModelUI>("ApplicationModel",1,0,"ApplicationModel"); qmlRegisterType<AnalysisModel>("AnalysisModel",1,0,"AnalysisModel"); qmlRegisterType<ConceptModel>("ConceptModel",1,0,"ConceptModel"); qmlRegisterType<CoverageLayerModel>("CoverageLayerModel", 1, 0, "CoverageLayerModel"); qmlRegisterType<ModelRegistry>("ModelRegistry", 1, 0, "ModelRegistry"); qmlRegisterType<CrossSectionPin>("CrossSectionPin", 1, 0, "CrossSectionPin"); qmlRegisterType<PinDataSource>("PinDataSource", 1, 0, "PinDataSource"); qmlRegisterType<ControlPointModel>("ControlPointModel", 1, 0, "ControlPointModel"); qmlRegisterType<ControlPointsListModel>("ControlPointsListModel", 1, 0, "ControlPointsListModel"); qmlRegisterType<FileSystem>("FileSystem", 1, 0, "FileSystem"); qmlRegisterType<MenuModel>("MenuModel", 1, 0, "MenuModel"); _mastercatalogmodel = new MasterCatalogModel(ctx); _formbuilder = new ApplicationFormExpressionParser(); _messageHandler = new UserMessageHandler(); _operations = new OperationCatalogModel(); _tranquilizers =new TranquilizerHandler(); _modelBuilder =new ModelBuilder(); _datapane =new DataPaneModel(); _objcreator =new ObjectCreator(); _preferences =new PreferencesModel(); _database = new InternalDatabaseModel(); _trqthread = new QThread; /*_filesystemmodel = new QFileSystemModel(); _filesystemmodel->setRootPath(""); _filesystemmodel->setFilter(QDir::Dirs | QDir::Drives | QDir::NoDotAndDotDot);*/ //tree->setCurrentIndex(fsModel->index(QDir::currentPath())); ctx->setContextProperty("mastercatalog", _mastercatalogmodel); ctx->setContextProperty("formbuilder", _formbuilder); ctx->setContextProperty("messagehandler", _messageHandler); ctx->setContextProperty("tranquilizerHandler", _tranquilizers); ctx->setContextProperty("operations", _operations); ctx->setContextProperty("modelbuilder", modelbuilder().get()); ctx->setContextProperty("datapane", _datapane); ctx->setContextProperty("objectcreator", _objcreator); ctx->setContextProperty("preferences",_preferences); ctx->setContextProperty("internaldatabase",_database); ctx->setContextProperty("uicontext", uicontext().get()); ctx->setContextProperty("models", modelregistry().get()); //ctx->setContextProperty("filesystem", _filesystemmodel); //ctx->setContextProperty("rootPathIndex", _filesystemmodel->index(_filesystemmodel->rootPath())); uicontext()->prepare(); uicontext()->qmlContext(ctx); _mastercatalogmodel->prepare(); _operations->prepare({"globaloperationscatalog", true}); qRegisterMetaType<IssueObject>("IssueObject"); qRegisterMetaType<UrlSet>("UrlSet"); _operations->connect(uicontext().get(),&UIContextModel::currentWorkSpaceChanged, _operations, &OperationCatalogModel::workSpaceChanged); _messageHandler->connect(kernel()->issues().data(), &IssueLogger::updateIssues,_messageHandler, &UserMessageHandler::addMessage ); TranquilizerWorker *trw = new TranquilizerWorker; trw->moveToThread(_trqthread); _trqthread->setProperty("workingcatalog", qVariantFromValue(context()->workingCatalog())); _trqthread->connect(kernel(), &Kernel::updateTranquilizer, trw, &TranquilizerWorker::updateTranquilizer); _trqthread->connect(kernel(), &Kernel::createTranquilizer, trw, &TranquilizerWorker::createTranquilizer); _trqthread->connect(kernel(), &Kernel::removeTranquilizer, trw, &TranquilizerWorker::removeTranquilizer); _trqthread->connect(trw, &TranquilizerWorker::sendUpdateTranquilizer, _tranquilizers, &TranquilizerHandler::updateTranquilizer); _trqthread->connect(trw, &TranquilizerWorker::sendCreateTranquilizer, _tranquilizers, &TranquilizerHandler::createTranquilizer); _trqthread->connect(trw, &TranquilizerWorker::sendRemoveTranquilizer, _tranquilizers, &TranquilizerHandler::removeTranquilizer); _trqthread->start(); _keys = new KeyFilter() ; _mastercatalogmodel->connect(_keys, &KeyFilter::keyPressed, _mastercatalogmodel, &MasterCatalogModel::keyPressed); _mastercatalogmodel->connect(_keys, &KeyFilter::keyReleased, _mastercatalogmodel, &MasterCatalogModel::keyReleased); QCoreApplication::instance()->installEventFilter(_keys); } catch(ErrorObject&){ } catch(...){ } }
int main(int argc, char *argv[]) { const QString runGuardName = getRunGuardName(); Helpers::RunGuard guard(runGuardName); if (!guard.tryToRun()) { std::cerr << "Xpiks is already running"; return -1; } // will call curl_global_init and cleanup Conectivity::CurlInitHelper curlInitHelper; Q_UNUSED(curlInitHelper); // will init thread-unsafe XMP toolkit MetadataIO::Exiv2InitHelper exiv2InitHelper; Q_UNUSED(exiv2InitHelper); const char *highDpiEnvironmentVariable = setHighDpiEnvironmentVariable(); qRegisterMetaTypeStreamOperators<Models::ProxySettings>("ProxySettings"); qRegisterMetaType<Common::SpellCheckFlags>("Common::SpellCheckFlags"); initQSettings(); Helpers::AppSettings appSettings; ensureUserIdExists(&appSettings); Suggestion::LocalLibrary localLibrary; QString appDataPath = XPIKS_USERDATA_PATH; if (!appDataPath.isEmpty()) { QDir appDataDir(appDataPath); QString libraryFilePath = appDataDir.filePath(Constants::LIBRARY_FILENAME); localLibrary.setLibraryPath(libraryFilePath); } else { std::cerr << "AppDataPath is empty!"; } #ifdef WITH_LOGS const QString &logFileDir = QDir::cleanPath(appDataPath + QDir::separator() + "logs"); if (!logFileDir.isEmpty()) { QDir dir(logFileDir); if (!dir.exists()) { bool created = QDir().mkpath(logFileDir); Q_UNUSED(created); } QString time = QDateTime::currentDateTimeUtc().toString("ddMMyyyy-hhmmss-zzz"); QString logFilename = QString("xpiks-qt-%1.log").arg(time); QString logFilePath = dir.filePath(logFilename); Helpers::Logger &logger = Helpers::Logger::getInstance(); logger.setLogFilePath(logFilePath); } #endif QMLExtensions::ColorsModel colorsModel; Models::LogsModel logsModel(&colorsModel); logsModel.startLogging(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) qSetMessagePattern("%{time hh:mm:ss.zzz} %{type} T#%{threadid} %{function} - %{message}"); #endif qInstallMessageHandler(myMessageHandler); LOG_INFO << "Log started. Today is" << QDateTime::currentDateTimeUtc().toString("dd.MM.yyyy"); LOG_INFO << "Xpiks" << XPIKS_VERSION_STRING << "-" << STRINGIZE(BUILDNUMBER); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) LOG_INFO << QSysInfo::productType() << QSysInfo::productVersion() << QSysInfo::currentCpuArchitecture(); #else #ifdef Q_OS_WIN LOG_INFO << QLatin1String("Windows Qt<5.4"); #elsif Q_OS_DARWIN LOG_INFO << QLatin1String("OS X Qt<5.4"); #else LOG_INFO << QLatin1String("LINUX Qt<5.4"); #endif #endif QApplication app(argc, argv); LOG_INFO << "Working directory of Xpiks is:" << QDir::currentPath(); LOG_DEBUG << "Extra files search locations:" << QStandardPaths::standardLocations(XPIKS_DATA_LOCATION_TYPE); if (highDpiEnvironmentVariable) { qunsetenv(highDpiEnvironmentVariable); } localLibrary.loadLibraryAsync(); QString userId = appSettings.value(QLatin1String(Constants::USER_AGENT_ID)).toString(); userId.remove(QRegExp("[{}-].")); Models::ArtworksRepository artworkRepository; Models::ArtItemsModel artItemsModel; Models::CombinedArtworksModel combinedArtworksModel; Models::UploadInfoRepository uploadInfoRepository; Warnings::WarningsService warningsService; Models::SettingsModel settingsModel; settingsModel.readAllValues(); Encryption::SecretsManager secretsManager; UndoRedo::UndoRedoManager undoRedoManager; Models::ZipArchiver zipArchiver; Suggestion::KeywordsSuggestor keywordsSuggestor(&localLibrary); Models::FilteredArtItemsProxyModel filteredArtItemsModel; filteredArtItemsModel.setSourceModel(&artItemsModel); Models::RecentDirectoriesModel recentDirectorieModel; Conectivity::FtpCoordinator *ftpCoordinator = new Conectivity::FtpCoordinator(settingsModel.getMaxParallelUploads()); Models::ArtworkUploader artworkUploader(ftpCoordinator); SpellCheck::SpellCheckerService spellCheckerService; SpellCheck::SpellCheckSuggestionModel spellCheckSuggestionModel; MetadataIO::BackupSaverService metadataSaverService; Warnings::WarningsModel warningsModel; warningsModel.setSourceModel(&artItemsModel); warningsModel.setWarningsSettingsModel(warningsService.getWarningsSettingsModel()); Models::LanguagesModel languagesModel; AutoComplete::AutoCompleteModel autoCompleteModel; AutoComplete::AutoCompleteService autoCompleteService(&autoCompleteModel); QMLExtensions::ImageCachingService imageCachingService; Models::FindAndReplaceModel replaceModel(&colorsModel); Models::DeleteKeywordsViewModel deleteKeywordsModel; Conectivity::UpdateService updateService(&settingsModel); MetadataIO::MetadataIOCoordinator metadataIOCoordinator; #if defined(QT_NO_DEBUG) && !defined(TELEMETRY_DISABLED) const bool telemetryEnabled = appSettings.value(Constants::USER_STATISTICS, true).toBool(); #else const bool telemetryEnabled = false; #endif Conectivity::TelemetryService telemetryService(userId, telemetryEnabled); Plugins::PluginManager pluginManager; Plugins::PluginsWithActionsModel pluginsWithActions; pluginsWithActions.setSourceModel(&pluginManager); Helpers::HelpersQmlWrapper helpersQmlWrapper; LOG_INFO << "Models created"; Commands::CommandManager commandManager; commandManager.InjectDependency(&artworkRepository); commandManager.InjectDependency(&artItemsModel); commandManager.InjectDependency(&filteredArtItemsModel); commandManager.InjectDependency(&combinedArtworksModel); commandManager.InjectDependency(&artworkUploader); commandManager.InjectDependency(&uploadInfoRepository); commandManager.InjectDependency(&warningsService); commandManager.InjectDependency(&secretsManager); commandManager.InjectDependency(&undoRedoManager); commandManager.InjectDependency(&zipArchiver); commandManager.InjectDependency(&keywordsSuggestor); commandManager.InjectDependency(&settingsModel); commandManager.InjectDependency(&recentDirectorieModel); commandManager.InjectDependency(&spellCheckerService); commandManager.InjectDependency(&spellCheckSuggestionModel); commandManager.InjectDependency(&metadataSaverService); commandManager.InjectDependency(&telemetryService); commandManager.InjectDependency(&updateService); commandManager.InjectDependency(&logsModel); commandManager.InjectDependency(&localLibrary); commandManager.InjectDependency(&metadataIOCoordinator); commandManager.InjectDependency(&pluginManager); commandManager.InjectDependency(&languagesModel); commandManager.InjectDependency(&colorsModel); commandManager.InjectDependency(&autoCompleteService); commandManager.InjectDependency(&imageCachingService); commandManager.InjectDependency(&replaceModel); commandManager.InjectDependency(&deleteKeywordsModel); commandManager.InjectDependency(&helpersQmlWrapper); commandManager.ensureDependenciesInjected(); keywordsSuggestor.initSuggestionEngines(); // other initializations secretsManager.setMasterPasswordHash(appSettings.value(Constants::MASTER_PASSWORD_HASH, "").toString()); uploadInfoRepository.initFromString(appSettings.value(Constants::UPLOAD_HOSTS, "").toString()); recentDirectorieModel.deserializeFromSettings(appSettings.value(Constants::RECENT_DIRECTORIES, "").toString()); commandManager.connectEntitiesSignalsSlots(); languagesModel.initFirstLanguage(); languagesModel.loadLanguages(); telemetryService.setInterfaceLanguage(languagesModel.getCurrentLanguage()); qmlRegisterType<Helpers::ClipboardHelper>("xpiks", 1, 0, "ClipboardHelper"); qmlRegisterType<QMLExtensions::TriangleElement>("xpiks", 1, 0, "TriangleElement"); QQmlApplicationEngine engine; Helpers::GlobalImageProvider *globalProvider = new Helpers::GlobalImageProvider(QQmlImageProviderBase::Image); QMLExtensions::CachingImageProvider *cachingProvider = new QMLExtensions::CachingImageProvider(QQmlImageProviderBase::Image); cachingProvider->setImageCachingService(&imageCachingService); QQmlContext *rootContext = engine.rootContext(); rootContext->setContextProperty("artItemsModel", &artItemsModel); rootContext->setContextProperty("artworkRepository", &artworkRepository); rootContext->setContextProperty("combinedArtworks", &combinedArtworksModel); rootContext->setContextProperty("appSettings", &appSettings); rootContext->setContextProperty("secretsManager", &secretsManager); rootContext->setContextProperty("undoRedoManager", &undoRedoManager); rootContext->setContextProperty("keywordsSuggestor", &keywordsSuggestor); rootContext->setContextProperty("settingsModel", &settingsModel); rootContext->setContextProperty("filteredArtItemsModel", &filteredArtItemsModel); rootContext->setContextProperty("helpersWrapper", &helpersQmlWrapper); rootContext->setContextProperty("recentDirectories", &recentDirectorieModel); rootContext->setContextProperty("metadataIOCoordinator", &metadataIOCoordinator); rootContext->setContextProperty("pluginManager", &pluginManager); rootContext->setContextProperty("pluginsWithActions", &pluginsWithActions); rootContext->setContextProperty("warningsModel", &warningsModel); rootContext->setContextProperty("languagesModel", &languagesModel); rootContext->setContextProperty("i18", &languagesModel); rootContext->setContextProperty("Colors", &colorsModel); rootContext->setContextProperty("acSource", &autoCompleteModel); rootContext->setContextProperty("replaceModel", &replaceModel); #ifdef QT_DEBUG QVariant isDebug(true); #else QVariant isDebug(false); #endif rootContext->setContextProperty("debug", isDebug); engine.addImageProvider("global", globalProvider); engine.addImageProvider("cached", cachingProvider); LOG_DEBUG << "About to load main view..."; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); LOG_DEBUG << "Main view loaded"; pluginManager.getUIProvider()->setQmlEngine(&engine); QQuickWindow *window = qobject_cast<QQuickWindow *>(engine.rootObjects().at(0)); pluginManager.getUIProvider()->setRoot(window->contentItem()); #ifdef QT_DEBUG if (argc > 1) { QList<QUrl> pathes; for (int i = 1; i < argc; ++i) { pathes.append(QUrl::fromLocalFile(QString::fromUtf8(argv[i]))); } commandManager.addInitialArtworks(pathes); } #endif commandManager.afterConstructionCallback(); return app.exec(); }
int main(int argc, char *argv[]) { QGuiApplication::setApplicationName("WikiToLearn"); QGuiApplication::setOrganizationName("en.wikitolearn.org"); QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QtWebView::initialize(); qmlRegisterType<dbmanager>("en.wtl.org", 1, 0, "dbmanager"); // registers the C++ type in the QML system dbmanager dbman; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty( "dbman", &dbman ); qmlRegisterType<listmodel>("en.wtl.model", 1, 0, "model"); listmodel mod; engine.rootContext()->setContextProperty("mod", &mod); //standard path to store all the application data ( varies from OS to OS ) QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); qDebug() << path; engine.rootContext()->setContextProperty("path", path); // create wtl application data in application data location ( generic ) // cd to the newly created application data dir QDir dir(path); if (!dir.exists()) dir.mkpath(path); if (!dir.exists("WTL_appdata")) dir.mkdir("WTL_appdata"); dir.cd("WTL_appdata"); /* * creates sqlite DB to keep track of all the stored offline pages * and also it's dependencies * */ QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection db.setDatabaseName(dir.absoluteFilePath("WTL.db")); if(!db.open()) { qDebug() <<"error"; } else { qDebug() <<"connected" ; } QSqlQuery query; if( query.exec("CREATE TABLE IF NOT EXISTS `Pages`" "( `page_ID` INTEGER NOT NULL PRIMARY KEY ," "`page_revision` INT NOT NULL ," "`page_title` TEXT NOT NULL);")) { qDebug() << "pages table created"; } else { qDebug() <<query.lastError(); } if(query.exec("CREATE TABLE IF NOT EXISTS `Dependencies` (" "`depe_ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," " `depe_fileName` VARCHAR(45) NOT NULL," "`revision_number` INTEGER NOT NULL);")) { qDebug() << "Dependencies table created"; } else { qDebug() <<query.lastError(); } query.clear(); db.close(); /* * Populate the model to show all the available offline pages ( IF ANY ) * this model list will be showed to user so that he/she can * either read the offline page or delete or update them * */ if(!db.open()) { qDebug() <<"error in opening DB"; } else { qDebug() <<"connected to DB" ; } QSqlQuery quer("SELECT page_ID , page_title FROM Pages"); while (quer.next()) { QString i = quer.value(0).toString(); QString p = quer.value(1).toString(); mod.addpages(list(p,i)); } QQmlContext *ctxt = engine.rootContext(); ctxt->setContextProperty("myModel", &mod); /* *** css download **/ if(QFile::exists(dir.absoluteFilePath("main.css"))) // checks if the css already exist { qDebug() << " already downloaded main.css"; } else{ QString url = "https://en.wikitolearn.org/load.php?debug=false&lang=en&modules=ext.echo.badgeicons%7Cext.echo.styles.badge%7Cext.math.styles%7Cext.visualEditor.desktopArticleTarget.noscript%7Cmediawiki.legacy.commonPrint%2Cshared%7Cmediawiki.sectionAnchor%7Cskin.wikitolearn&only=styles&skin=wikitolearnskin"; css_download(url,"main.css",path); } if(QFile::exists(dir.absoluteFilePath("bootstrap.css"))) { qDebug() << "already downloaded bootstrap.css"; } else{ QString url = "https://en.wikitolearn.org/skins/WikiToLearnSkin/bower_components/font-awesome/css/font-awesome.min.css?314"; css_download(url,"bootstrap.css",path); } if(QFile::exists(dir.absoluteFilePath("wikitolearnskin.css"))) { qDebug() << "already downloaded wikitolearnskin.css"; } else{ QString url = "http://en.wikitolearn.org/load.php?debug=false&lang=en&modules=ext.visualEditor.desktopArticleTarget.noscript%7Cmediawiki.legacy.commonPrint%2Cshared%7Cmediawiki.sectionAnchor%7Cskin.wikitolearn&only=styles&skin=wikitolearnskin"; css_download(url,"wikitolearnskin.css",path); } /* css download end */ /* js download */ if(QFile::exists(dir.absoluteFilePath("wikitolearnskin.js"))) // checks if the js file already exist { qDebug() << " already downloaded wikitolearnskin.js"; } else{ QString url = "https://en.wikitolearn.org/load.php?debug=false&lang=en&modules=startup&only=scripts&skin=wikitolearnskin"; js_download(url,"wikitolearnskin.js",path); } /* js download end */ QSettings settings; QString style = QQuickStyle::name(); if (!style.isEmpty()) settings.setValue("style", style); else QQuickStyle::setStyle(settings.value("style").toString()); //load main.qml and stores the settings engine.load(QUrl("qrc:/main.qml")); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
WebPageActivationData WebPages::page(int tabId, int parentId) { if (!m_webPageComponent) { qWarning() << "TabModel not initialized!"; return WebPageActivationData(0, false); } if (m_activePage && m_activePage->webPage && m_activePage->webPage->tabId() == tabId) { m_activePage->webPage->resumeView(); m_activePage->webPage->setVisible(true); return WebPageActivationData(m_activePage->webPage, false); } #ifdef DEBUG_LOGS qDebug() << "about to create a new tab or activate old:" << tabId; #endif WebPageEntry *pageEntry = m_activePages.value(tabId, 0); bool resurrect = pageEntry && !pageEntry->webPage; if (!pageEntry || resurrect) { QQmlContext *creationContext = m_webPageComponent->creationContext(); QQmlContext *context = new QQmlContext(creationContext ? creationContext : QQmlEngine::contextForObject(m_webContainer)); QObject *object = m_webPageComponent->beginCreate(context); if (object) { context->setParent(object); object->setParent(m_webContainer); DeclarativeWebPage *webPage = qobject_cast<DeclarativeWebPage *>(object); if (webPage) { webPage->setParentItem(m_webContainer); webPage->setParentID(parentId); webPage->setTabId(tabId); webPage->setContainer(m_webContainer); if (!pageEntry) { pageEntry = new WebPageEntry(webPage, 0); } else { pageEntry->webPage = webPage; } m_webPageComponent->completeCreate(); #ifdef DEBUG_LOGS qDebug() << "New view id:" << webPage->uniqueID() << "parentId:" << webPage->parentId() << "tab id:" << webPage->tabId(); #endif m_activePages.insert(tabId, pageEntry); ++m_count; } else { qmlInfo(m_webContainer) << "webPage component must be a WebPage component"; } } else { qmlInfo(m_webContainer) << "Creation of the web page failed. Error: " << m_webPageComponent->errorString(); delete object; object = 0; } } updateActivePage(pageEntry, resurrect); #ifdef DEBUG_LOGS dumpPages(); #endif return WebPageActivationData(pageEntry->webPage, true); }
void run_ui() { #ifdef SUBSURFACE_MOBILE QQmlApplicationEngine engine; register_qml_types(&engine); LOG_STP("run_ui qml engine started"); KirigamiPlugin::getInstance().registerTypes(); #if defined(__APPLE__) && !defined(Q_OS_IOS) // when running the QML UI on a Mac the deployment of the QML Components seems // to fail and the search path for the components is rather odd - simply the // same directory the executable was started from <bundle>/Contents/MacOS/ // To work around this we need to manually copy the components at install time // to Contents/Frameworks/qml and make sure that we add the correct import path const QStringList importPathList = engine.importPathList(); for (QString importPath: importPathList) { if (importPath.contains("MacOS")) engine.addImportPath(importPath.replace("MacOS", "Frameworks")); } qDebug() << "QML import path" << engine.importPathList(); #endif // __APPLE__ not Q_OS_IOS engine.addImportPath("qrc://imports"); DiveListModel diveListModel; LOG_STP("run_ui diveListModel started"); DiveListSortModel *sortModel = new DiveListSortModel(0); sortModel->setSourceModel(&diveListModel); sortModel->setDynamicSortFilter(true); sortModel->setSortRole(DiveListModel::DiveDateRole); sortModel->sort(0, Qt::DescendingOrder); LOG_STP("run_ui diveListModel sorted"); GpsListModel gpsListModel; QSortFilterProxyModel *gpsSortModel = new QSortFilterProxyModel(0); gpsSortModel->setSourceModel(&gpsListModel); gpsSortModel->setDynamicSortFilter(true); gpsSortModel->setSortRole(GpsListModel::GpsWhenRole); gpsSortModel->sort(0, Qt::DescendingOrder); QQmlContext *ctxt = engine.rootContext(); ctxt->setContextProperty("diveModel", sortModel); ctxt->setContextProperty("gpsModel", gpsSortModel); ctxt->setContextProperty("vendorList", vendorList); set_non_bt_addresses(); LOG_STP("run_ui set_non_bt_adresses"); ctxt->setContextProperty("connectionListModel", &connectionListModel); ctxt->setContextProperty("logModel", MessageHandlerModel::self()); engine.load(QUrl(QStringLiteral("qrc:///qml/main.qml"))); LOG_STP("run_ui qml loaded"); qqWindowObject = engine.rootObjects().value(0); if (!qqWindowObject) { fprintf(stderr, "can't create window object\n"); exit(1); } QQuickWindow *qml_window = qobject_cast<QQuickWindow *>(qqWindowObject); qml_window->setIcon(QIcon(":subsurface-mobile-icon")); qDebug() << "qqwindow devicePixelRatio" << qml_window->devicePixelRatio() << qml_window->screen()->devicePixelRatio(); QScreen *screen = qml_window->screen(); QObject::connect(qml_window, &QQuickWindow::screenChanged, QMLManager::instance(), &QMLManager::screenChanged); QMLManager *manager = QMLManager::instance(); LOG_STP("run_ui qmlmanager instance started"); // now that the log file is initialized... show_computer_list(); LOG_STP("run_ui show_computer_list"); manager->setDevicePixelRatio(qml_window->devicePixelRatio(), qml_window->screen()); manager->dlSortModel = sortModel; manager->qmlWindow = qqWindowObject; manager->screenChanged(screen); qDebug() << "qqwindow screen has ldpi/pdpi" << screen->logicalDotsPerInch() << screen->physicalDotsPerInch(); #if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS) qml_window->setHeight(1200); qml_window->setWidth(800); #endif // not Q_OS_ANDROID and not Q_OS_IOS qml_window->show(); LOG_STP("run_ui running exec"); #else MainWindow::instance()->show(); #endif // SUBSURFACE_MOBILE qApp->exec(); }
void MarSystemView::createItem( MarSystem *system, QQmlComponent * delegate, QQuickItem * parent ) { int level = -1; MarSystem *s = system; while(s) { s = s->getParent(); ++level; } QQmlPropertyMap *data = new QQmlPropertyMap; data->insert("level", level); // Get controls QQmlPropertyMap *defaultControls = new QQmlPropertyMap; defaultControls->insert("inSamples", variantFromControl(system->getControl("mrs_natural/inSamples"))); defaultControls->insert("onSamples", variantFromControl(system->getControl("mrs_natural/onSamples"))); defaultControls->insert("inObservations", variantFromControl(system->getControl("mrs_natural/inObservations"))); defaultControls->insert("onObservations", variantFromControl(system->getControl("mrs_natural/onObservations"))); defaultControls->insert("israte", variantFromControl(system->getControl("mrs_real/israte"))); defaultControls->insert("osrate", variantFromControl(system->getControl("mrs_real/osrate"))); defaultControls->insert("inStabilizingDelay", variantFromControl(system->getControl("mrs_natural/inStabilizingDelay"))); defaultControls->insert("onStabilizingDelay", variantFromControl(system->getControl("mrs_natural/onStabilizingDelay"))); defaultControls->insert("inObsNames", variantFromControl(system->getControl("mrs_string/inObsNames"))); defaultControls->insert("onObsNames", variantFromControl(system->getControl("mrs_string/onObsNames"))); defaultControls->insert("active", variantFromControl(system->getControl("mrs_bool/active"))); defaultControls->insert("mute", variantFromControl(system->getControl("mrs_bool/mute"))); defaultControls->insert("debug", variantFromControl(system->getControl("mrs_bool/debug"))); defaultControls->insert("verbose", variantFromControl(system->getControl("mrs_bool/verbose"))); defaultControls->insert("processedData", variantFromControl(system->getControl("mrs_realvec/processedData"))); QQmlPropertyMap *customControls = new QQmlPropertyMap; control_map_t controls = system->controls(); control_map_t::iterator it; for (it = controls.begin(); it != controls.end(); ++it) { const MarControlPtr & control = it->second; QString name = QString::fromStdString( control->getName() ); name = name.split('/').last(); if (defaultControls->contains(name)) continue; customControls->insert(name, variantFromControl(control)); } data->insert("defaultControls", QVariant::fromValue<QObject*>(defaultControls)); data->insert("controls", QVariant::fromValue<QObject*>(customControls)); data->insert("absolutePath", QString::fromStdString(system->getAbsPath())); data->insert("path", QString::fromStdString(system->getPrefix())); // Set context QQmlContext *context = new QQmlContext( delegate->creationContext() ); context->setContextProperty("system", data); QObject *object = delegate->create(context); object->setParent(parent); m_items.append(object); QQuickItem *item = qobject_cast<QQuickItem*>(object); if (!item) return; QString path = QString::fromStdString(system->getPrefix()); std::vector<MarSystem*> children = system->getChildren(); int children_count = children.size(); bool has_children = children_count > 0; bool create_if_not_existent = true; MarSystemViewAttached *attached = qobject_cast<MarSystemViewAttached*>(qmlAttachedPropertiesObject<MarSystemView>(item, create_if_not_existent) ); Q_ASSERT(attached); attached->setPath(path); attached->setHasChildren(has_children); attached->setSystem(system); QQuickItem *children_area = attached->childrenArea(); if (!children_area) children_area = item; for (int child_idx = 0; child_idx < children_count; ++child_idx) { MarSystem *child_system = children[child_idx]; createItem(child_system, delegate, children_area); } item->setParentItem(parent); }
/*! Disables QRC reading on a given QObject (usually a Loader or Repeater). Very important, enables loading of non-qrc paths in an app that uses QRC. Usually, if you load any QML code through QRC, all subsequent loads will also be performed through resource system - even when you specify a path that is not present in any resource file. This method counters this by clearing the "qrc mode". */ void CcfMain::disableQrc(QObject *object) { QQmlContext *context = engine()->contextForObject(object); context->setBaseUrl(QUrl::fromLocalFile("")); }
/** * We use the creation function merely to set up the * user interface and make the connections between the * gui elements and the handling agents. All real action * is embedded in actions, initiated by gui buttons */ RadioInterface::RadioInterface (QSettings *Si, QQmlApplicationEngine *engine, QObject *parent): QObject (parent) { int16_t latency; dabSettings = Si; this->engine = engine; // // Before printing anything, we set setlocale (LC_ALL, ""); /// The default, most likely to be overruled // // One can imagine that a particular version is created // for a specific device. In that case the class // handling the device can be instantiated here inputDevice = new virtualInput (); running = false; /** threshold is used in the phaseReference class * as threshold for checking the validity of the correlation result */ threshold = dabSettings -> value ("threshold", 3). toInt (); isSynced = UNSYNCED; // // latency is used to allow different settings for different // situations wrt the output buffering latency = dabSettings -> value ("latency", 1). toInt (); /** * The current setup of the audio output is that * you have a choice, take one of (soundcard, tcp streamer or rtp streamer) */ audioBuffer = new RingBuffer<int16_t>(2 * 32768); ipAddress = dabSettings -> value ("ipAddress", "127.0.0.1"). toString (); port = dabSettings -> value ("port", 8888). toInt (); // // show_crcErrors can be ignored in other GUI's, the // value is passed on though show_crcErrors = dabSettings -> value ("show_crcErrors", 0). toInt () != 0; autoStart = dabSettings -> value ("autoStart", 0). toInt () != 0; // // In this version, the default is sending the resulting PCM samples to the // soundcard. However, defining either TCP_STREAMER or RTP_STREAMER will // cause the PCM samples to be send through a different medium QStringList AudioInterfaces; soundOut = new audioSink (latency, &AudioInterfaces, audioBuffer); /** * By default we select Band III and Mode 1 or whatever the use * has specified */ dabBand = dabSettings -> value ("dabBand", BAND_III). toInt (); //setupChannels (channelSelector, dabBand); uint8_t dabMode = dabSettings -> value ("dabMode", 1). toInt (); setModeParameters (dabMode); /** * The actual work is done elsewhere: in ofdmProcessor * and ofdmDecoder for the ofdm related part, ficHandler * for the FIC's and mscHandler for the MSC. * The ficHandler shares information with the mscHandler * but the handlers do not change each others modes. */ my_mscHandler = new mscHandler (this, &dabModeParameters, audioBuffer, show_crcErrors); my_ficHandler = new ficHandler (this); // /** * The default for the ofdmProcessor depends on * the input device, so changing the selection for an input device * requires changing the ofdmProcessor. */ my_ofdmProcessor = new ofdmProcessor (inputDevice, &dabModeParameters, this, my_mscHandler, my_ficHandler, threshold); init_your_gui (); // gui specific stuff if (autoStart) setStart (); // Read channels from the settings dabSettings->beginGroup("channels"); int channelcount = dabSettings->value("channelcout").toInt(); for(int i=1;i<=channelcount;i++) { QStringList SaveChannel = dabSettings->value("channel/"+QString::number(i)).toStringList(); stationList.append(SaveChannel.first(), SaveChannel.last()); } dabSettings->endGroup(); // Sort stations stationList.sort(); // Set timer connect(&CheckFICTimer, SIGNAL(timeout()),this, SLOT(CheckFICTimerTimeout())); connect(&ScanChannelTimer, SIGNAL(timeout()),this, SLOT(scanChannelTimerTimeout())); // Reset isSignalPresent = false; isFICCRC = false; // Main entry to the QML GUI QQmlContext *rootContext = engine->rootContext(); // Set the stations rootContext->setContextProperty("stationModel", QVariant::fromValue(stationList.getList())); rootContext->setContextProperty("cppGUI", this); // Set working directory QString workingDir = QDir::currentPath() + "/"; rootContext->setContextProperty("workingDir", workingDir); // Take the root object QObject *rootObject = engine->rootObjects().first(); // Restore windows properties int WindowHeight = dabSettings -> value ("WindowHeight", 0).toInt(); if(WindowHeight) rootObject->setProperty("height", WindowHeight); int WindowWidth = dabSettings -> value ("WindowWidth", 0).toInt(); if(WindowWidth) rootObject->setProperty("width", WindowWidth); // Restore the full screen property bool isFullscreen = dabSettings -> value ("StartInFullScreen", false).toBool(); QObject *enableFullScreenObject = rootObject->findChild<QObject*>("enableFullScreen"); if(enableFullScreenObject) enableFullScreenObject->setProperty("checked", isFullscreen); // Restore the show channel names property bool isShowChannelNames = dabSettings-> value ("ShowChannelNames", false).toBool(); QObject *showChannelObject = rootObject->findChild<QObject*>("showChannel"); if(showChannelObject) showChannelObject->setProperty("checked", isShowChannelNames); // Restore expert mode bool isExpertMode = dabSettings-> value ("EnableExpertMode", false).toBool(); QObject *expertModeObject = rootObject->findChild<QObject*>("enableExpertMode"); if(expertModeObject) expertModeObject->setProperty("checked", isExpertMode); // Connect signals connect(rootObject, SIGNAL(stationClicked(QString,QString)),this, SLOT(channelClick(QString,QString))); connect(rootObject, SIGNAL(startChannelScanClicked()),this, SLOT(startChannelScanClick())); connect(rootObject, SIGNAL(stopChannelScanClicked()),this, SLOT(stopChannelScanClick())); connect(rootObject, SIGNAL(exitApplicationClicked()),this, SLOT(TerminateProcess())); connect(rootObject, SIGNAL(exitSettingsClicked()),this, SLOT(saveSettings())); }
void RadioInterface::scanChannelTimerTimeout(void) { static int Timeout = 0; // **** The channel scan is done by a simple state machine *** // State ScanStart if(ScanChannelState == ScanStart) { //fprintf(stderr,"State: ScanStart\n"); // Open and start the radio setStart (); // Reset the station list stationList.reset(); ScanChannelState = ScanTunetoChannel; } // State ScanTunetoChannel if(ScanChannelState == ScanTunetoChannel) { //fprintf(stderr,"State: ScanTunetoChannel\n"); // Select channel if(BandIIIChannelIt < 38) // 38 band III frequencies { CurrentChannel = bandIII_frequencies [BandIIIChannelIt]. key; dabBand = BAND_III; fprintf(stderr,"Scan channel: %s, %d kHz\n", bandIII_frequencies [BandIIIChannelIt]. key, bandIII_frequencies [BandIIIChannelIt].fKHz); emit channelScanProgress(BandIIIChannelIt + 1); // Tune to channel set_channelSelect (CurrentChannel); /*if(BandIIIChannelIt == 0) BandIIIChannelIt = 1; if(BandIIIChannelIt == 2) BandIIIChannelIt = 26;*/ BandIIIChannelIt ++; Timeout = 0; ScanChannelState = ScanCheckSignal; } /*else if(BandLChannelIt < 16) // 16 L band frequencies { CurrentChannel = Lband_frequencies [BandLChannelIt]. key; dabBand = L_BAND; fprintf(stderr,"Scan channel: %s, %d kHz\n", Lband_frequencies [BandLChannelIt]. key, Lband_frequencies [BandLChannelIt].fKHz); BandLChannelIt++; emit channelScanProgress(BandIIIChannelIt + BandLChannelIt); // Tune to channel set_channelSelect (CurrentChannel); Timeout = 0; ScanChannelState = ScanCheckSignal; }*/ else { ScanChannelState = ScanDone; } emit currentStation("Scanning " + CurrentChannel + " ..."); } // State ScanCheckSignal if(ScanChannelState == ScanCheckSignal) { //fprintf(stderr,"State: ScanCheckSignal\n"); if(isSignalPresent) { Timeout = 0; ScanChannelState = ScanWaitForFIC; } else { Timeout++; } // 2 s timeout if(Timeout >= 2) { //fprintf(stderr,"ScanCheckSignal Timeout\n"); ScanChannelState = ScanTunetoChannel; } } // State ScanWaitForFIC if(ScanChannelState == ScanWaitForFIC) { //fprintf(stderr,"State: ScanWaitForFIC\n"); if(isFICCRC) { fprintf(stderr,"Found channel %s\n", CurrentChannel.toStdString().c_str()); Timeout = 0; ScanChannelState = ScanWaitForChannelNames; } else { Timeout++; } // 30 s timeout if(Timeout >= 30) { //fprintf(stderr,"ScanWaitForFIC Timeout\n"); ScanChannelState = ScanTunetoChannel; } } // State ScanWaitForChannelNames if(ScanChannelState == ScanWaitForChannelNames) { Timeout++; // 30 s timeout if(Timeout >= 30) ScanChannelState = ScanTunetoChannel; } // State ScanDone if(ScanChannelState == ScanDone) { //fprintf(stderr,"Stop channel scan\n"); ScanChannelTimer.stop(); emit channelScanStopped(); emit currentStation("No Station"); /*StationList.sort(); for(int i=0;i<StationList.count();i++) { QString Station = StationList.at(i); fprintf(stderr,"Station: %s\n",Station.toStdString().c_str()); }*/ // Sort stations stationList.sort(); // Load stations into GUI QQmlContext *rootContext = engine->rootContext(); rootContext->setContextProperty("stationModel", QVariant::fromValue(stationList.getList())); } }
//============================================================================== // Load File //============================================================================== bool ViewerWindow::loadFile(const QString& aFileName, const QString& aPanelName) { // Init Mime Database QMimeDatabase mimeDatabase; // Get Mime Tpye mime = mimeDatabase.mimeTypeForFile(aFileName).name(); // Reset File Is New fileIsNew = false; qDebug() << "ViewerWindow::loadFile - aFileName: " << aFileName << " - mime: " << mime; // Set File Name fileName = aFileName; // Emit Content Source Changed emit contentSourceChanged(fileName); // Set Context Properties QQmlContext* ctx = ui->quickWidget->rootContext(); // Set Context Properties - Viewer Content ctx->setContextProperty(DEFAULT_IMAGE_VIEWER_CONTENT, fileName); // Edit Mode & Check Mime Type - Load All Files As Text in Edit Mode if (isSupportedTextMime(editMode, mime)) { // Quick Widget Set Visible ui->quickWidget->setVisible(false); // Text Edit Set Visible ui->textEdit->setVisible(true); // Set Active Widget activeWidget = ui->textEdit; // Init File QFile file(aFileName); // Open File if (file.open(QIODevice::ReadOnly)) { // Init Text Stream QTextStream textStream(&file); // Check Mime Again if (mime.startsWith(QString(DEFAULT_MIME_PREFIX_APP) + QString(DEFAULT_MIME_XML)) || mime.startsWith(QString(DEFAULT_MIME_PREFIX_APP) + QString(DEFAULT_MIME_SHELLSCRIPT))) { // Load From File ui->textEdit->setPlainText(textStream.readAll()); } else { // Load From File ui->textEdit->setText(textStream.readAll()); } // Reset Dirty Flag dirty = false; // Close File file.close(); // Update Window Title updateWindowTitle(); } } else if (!editMode && mime.startsWith(DEFAULT_MIME_PREFIX_IMAGE)) { // Text Edit Set Visible ui->textEdit->setVisible(false); // Quick Widget Set Visible ui->quickWidget->setVisible(true); // Set Active Widget activeWidget = ui->quickWidget; // Set Source ui->quickWidget->setSource(QUrl("qrc:/qml/ImageViewer.qml")); // Check Image Browser if (!imageBrowser) { // Create Image Browser imageBrowser = new ImageBrowser(fileName, aPanelName); // Connect Signals connect(imageBrowser, SIGNAL(currentIndexChanged(int)), this, SLOT(imageBrowserCurrentIndexChanged(int))); connect(imageBrowser, SIGNAL(currentFileChanged(QString)), this, SLOT(imageBrowserCurrentFileChanged(QString))); connect(imageBrowser, SIGNAL(currentFileChanged(QString)), this, SIGNAL(currentImageFileChanged(QString))); connect(imageBrowser, SIGNAL(selectCurrent()), this, SLOT(handleImageBrowserSelection())); // Set Context Properties QQmlContext* ctx = ui->quickWidget->rootContext(); // Set Context Properties - Image Browser ctx->setContextProperty(DEFAULT_IMAGE_BROWSER, imageBrowser); }
/** * @brief main main method to create application * @param argc count of elements in argv * @param argv include all commando line parameter * @return Return 0 if ok otherwise a error code not equal 0 */ int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("GUI-Frameworks"); QCoreApplication::setApplicationName("HeartRate"); QApplication app(argc, argv); app.setWindowIcon(QIcon(":/Images/heart_icon.png")); //multiple language QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load(":/Language_Files/app_" + QLocale::system().name() + ".qm"); app.installTranslator(&myappTranslator); Settings& settings = Settings::getInstance(); if (!settings) { qDebug("FATAL error while instanciating Settings!!"); return 1; } /****************************************** * instanciate dataStorage * has to be referenced to the model * which need the data *******************************************/ ImportExport dataStorage; if (!dataStorage) { qDebug("FATAL error while creating Database instance"); return 1; } BroadcastReceiver bcReceiver; // run broadcast receiver thread loop: bcReceiver.start(); TcpServer server; // listen for incoming data connections: server.startServer(); // create sensorInactiveData Model SensorModel inactiveSensorModel; // create inactiveCalcSensorModel InactiveSensorCalcModel inactiveCalcSensorModel(inactiveSensorModel); // create sensorActiveModel SensorModel activeSensorModel; // create sensorActiveTable Model SensorModel activeSensorTableModel; // create activeCalcSensorModel ActiveSensorCalcModel activeCalcSensorModel(activeSensorModel); // create selectionValue models SelectionModel activeYearModel, activeMonthModel; qmlRegisterType<CustomPlotBarChart>("CostumPlot", 1, 0, "CustomPlotBarChart"); qmlRegisterType<CustomPlotLineChart>("CostumPlot", 1, 0, "CustomPlotLineChart"); QQmlApplicationEngine engine; QQmlContext* contex = engine.rootContext(); if(contex) { // set Model to view contex->setContextProperty("inactiveSensorDataModel", &inactiveSensorModel); contex->setContextProperty("activeSensorDataModel", &activeSensorModel); contex->setContextProperty("inactiveSensorCalcModel", &inactiveCalcSensorModel); contex->setContextProperty("activeSensorCalcModel", &activeCalcSensorModel); contex->setContextProperty("activeSelectionYearModel", &activeYearModel); contex->setContextProperty("activeSelectionMonthModel", &activeMonthModel); contex->setContextProperty("activeSensorTableModel", &activeSensorTableModel); } else qDebug() << "Error no contex is set"; // load qml file to engine engine.load(QUrl(MAIN_VIEW)); QObject* root = engine.rootObjects().at(0); if(root) { // initate tabs QObject* tabView = root->findChild<QObject*>("TabViewName"); if(tabView) { const int countTabs = tabView->property("count").toInt(); for(int i = countTabs-1 ; i >= 0; i--) { tabView->setProperty("currentIndex",i); } } else qDebug() << "No tabview object found"; } else qDebug() << "No root object available"; // set controler FilterController filterController(root, inactiveSensorModel, inactiveCalcSensorModel, dataStorage); SelectionController selectionController(root, activeYearModel, activeMonthModel, activeSensorModel,activeSensorTableModel, activeCalcSensorModel, dataStorage); TableSelectionController tableController(root, activeSensorTableModel, activeSensorModel, activeCalcSensorModel, dataStorage); PrintController printController(root, inactiveSensorModel, activeSensorModel); InitDiagramsController initController(root, inactiveSensorModel, activeSensorModel); int ret = app.exec(); bcReceiver.exit(); return ret; }
Q_DECL_EXPORT int main(int argc, char *argv[]) { QApplication::setAttribute(Qt::AA_X11InitThreads, true); QApplication app(argc, argv); app.setOrganizationName("Qtness"); app.setOrganizationDomain("qtness.com"); app.setApplicationName("Sachesi"); app.setApplicationVersion("2.0.0"); // Use system proxy except where not possible QNetworkProxyFactory::setUseSystemConfiguration(true); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); // Do we have a suitable place to store files that the user will be able to find? if (!checkCurPath()) { QMessageBox::critical(NULL, "Error", "Could not find a suitable storage path.\nPlease report this."); return 0; } // *** Static QML Variables that describe the environment // Useful as QML is unable to detect this natively // Send the version across. Preferably via the .pro context->setContextProperty("version", QVariant::fromValue(QApplication::applicationVersion())); // Check if we have at least Qt 5.3 available. If not, do some workarounds for bugs. context->setContextProperty("qt_new", QVariant::fromValue(QT_VERSION > QT_VERSION_CHECK(5, 3, 0))); // Check if this is a mobile device as they often do not have enough space. context->setContextProperty("mobile", QVariant::fromValue( #if defined(BLACKBERRY) || defined(ANDROID) 1 #else 0 #endif )); // *** C++ Classes that are passed to the QML pages. // Heavy lifting to be done by the compiled and feature-packed language. InstallNet i; context->setContextProperty("i", &i); MainNet p(&i); Scanner scanner; Translator translator; #ifdef BOOTLOADER_ACCESS Boot b; QObject::connect(&b, SIGNAL(started()), &b, SLOT(search())); QObject::connect(&b, SIGNAL(finished()), &b, SLOT(exit())); QObject::connect(&i, SIGNAL(newPassword(QString)), &b, SLOT(newPassword(QString))); b.start(); context->setContextProperty("b", &b); // Boot #endif CarrierInfo info; // Set contexts for the classes context->setContextProperty("p", &p); // MainNet context->setContextProperty("scanner", &scanner); context->setContextProperty("download", p.currentDownload); context->setContextProperty("carrierinfo", &info); context->setContextProperty("translator", &translator); // *** Register types for the QML language to understand types used by C++, when passed #ifndef BLACKBERRY qmlRegisterType<BackupInfo>("BackupTools", 1, 0, "BackupInfo"); #endif qmlRegisterType<Apps>(); qmlRegisterType<DeviceInfo>(); qmlRegisterType<DiscoveredRelease>(); #if defined(_WIN32) && defined(STATIC) engine.addImportPath("qrc:/qml/"); #endif // *** Now let's try to show the QML file and check for errors QScopedPointer<QQmlComponent> comp(new QQmlComponent(&engine)); comp->loadUrl(QUrl("qrc:/qml/generic/Title.qml")); if (comp->status() == QQmlComponent::Error) { QMessageBox::information(nullptr, "Error", qPrintable(comp->errorString()), QMessageBox::Ok); return 0; } QQuickWindow *window = qobject_cast<QQuickWindow *>(comp->create()); window->show(); int ret = app.exec(); #ifdef BOOTLOADER_ACCESS b.quit(); b.wait(1000); #endif delete window; return ret; }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); //Создание структуры объектов //CanDevice* canDevice = SocketCanDevice::instance(); CanDevice* canDevice = EmulationCanDevice::instance(); canDevice->registerCanUnit(CanUnitCapno1::instance()); canDevice->registerCanUnit(CanUnitCapno2::instance()); canDevice->registerCanUnit(CanUnitPower::instance()); canDevice->registerCanUnit(CanUnitSPO::instance()); canDevice->registerCanUnit(CanUnitKIVL::instance()); canDevice->registerCanUnit(CanUnitMix::instance()); RegimeManager::instance(); CanManager::instance(); EventManager::instance(); GraphicManager::instance(); OptionsManager::instance(); VentModeManager::instance(); TranslationManager::instance(); QObject::connect(canDevice,SIGNAL(canDeviceModeChanged(CanDevice::canDeviceModes)), RegimeManager::instance(), SLOT(slotCanDeviceMode(CanDevice::canDeviceModes))); //Регистрация перечислений для QML qmlRegisterUncreatableType<CanUnitMix>("CppImport", 1, 0, "CanUnitMix", "NOT MAY CREATE"); qmlRegisterUncreatableType<CanUnitKIVL>("CppImport", 1, 0, "CanUnitKIVL", "NOT MAY CREATE"); qmlRegisterUncreatableType<MeasureParameter>("CppImport", 1, 0, "MeasureParameter", "NOT MAY CREATE"); qmlRegisterUncreatableType<TunningParameter>("CppImport", 1, 0, "TunningParameter", "NOT MAY CREATE"); qmlRegisterUncreatableType<AssociatedParameter>("CppImport", 1, 0, "AssociatedParameter", "NOT MAY CREATE"); qmlRegisterUncreatableType<EventIDs>("CppImport", 1, 0, "EventIDs", "NOT MAY CREATE"); qmlRegisterUncreatableType<EventTypes>("CppImport", 1, 0, "EventTypes", "NOT MAY CREATE"); qmlRegisterUncreatableType<CanUnitPower>("CppImport", 1, 0, "CanUnitPower", "NOT MAY CREATE"); qmlRegisterUncreatableType<CanUnit>("CppImport", 1, 0, "CanUnit", "NOT MAY CREATE"); qmlRegisterUncreatableType<RegimeManager>("CppImport", 1, 0, "RegimeManager", "NOT MAY CREATE"); qmlRegisterUncreatableType<VentModeManager>("CppImport", 1, 0, "VentModeManager", "NOT MAY CREATE"); //Создание представления и контекста QML QtQuick2ApplicationViewer viewer; QQmlContext* ctx = viewer.rootContext(); //регистрация объектов для QML ctx->setContextProperty("keySim", new KeyboardSimulator()); ctx->setContextProperty("tm", TranslationManager::instance()); ctx->setContextProperty("regimeManager", RegimeManager::instance()); ctx->setContextProperty("canUnitMix", CanUnitMix::instance()); ctx->setContextProperty("canUnitKIVL", CanUnitKIVL::instance()); ctx->setContextProperty("canUnitPower", CanUnitPower::instance()); ctx->setContextProperty("eventManager", EventManager::instance()); ctx->setContextProperty("ventModeManager",VentModeManager::instance()); ctx->setContextProperty("graphicManager", GraphicManager::instance()); ctx->setContextProperty("canManager", CanManager::instance()); CanUnitKIVL::instance()->bindContext(ctx); CanUnitCapno1::instance()->bindContext(ctx); VentModeManager::instance()->bindContext(ctx); GraphicManager::instance()->bindContext(ctx); OptionsManager::instance()->bindContext(ctx); viewer.setMainQmlFile(QStringLiteral("qml/BaseIVL2/main.qml")); viewer.setWidth(1024); viewer.setHeight(768); viewer.setColor(QColor::fromRgb(0,0,0,0)/*Qt::transparent*/); viewer.showExpanded(); canDevice->startInit(); return app.exec(); }
Q_DECL_EXPORT int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setOrganizationName("MusiKloud2"); app.setApplicationName("MusiKloud2"); app.setApplicationVersion(VERSION_NUMBER); app.setWindowIcon(QIcon::fromTheme("musikloud2")); Settings settings; Clipboard clipboard; DBusService dbus; Resources resources; ResourcesPlugins plugins; SoundCloud soundcloud; Transfers transfers; Utils utils; initDatabase(); registerTypes(); plugins.load(); settings.setNetworkProxy(); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); context->setContextProperty("Clipboard", &clipboard); context->setContextProperty("DBus", &dbus); context->setContextProperty("Plugins", &plugins); context->setContextProperty("Resources", &resources); context->setContextProperty("Settings", &settings); context->setContextProperty("SoundCloud", &soundcloud); context->setContextProperty("Transfers", &transfers); context->setContextProperty("Utils", &utils); context->setContextProperty("MAX_RESULTS", MAX_RESULTS); context->setContextProperty("VERSION_NUMBER", VERSION_NUMBER); engine.load("/opt/musikloud2/qml/main.qml"); return app.exec(); }