int main(int argc, char *argv[]) { Logger::Init("Tombola.log.txt"); qInfo() << "\n\n" << "========== Startup =========="; CrashHandler crashHandler; QApplication app(argc, argv); QCoreApplication::setApplicationName("Tombola"); // QSettings init early enough QCoreApplication::setOrganizationName("Kúr Attila"); // QSettings init early enough DynamicTranslation dynamicTranslation(app); TombolaDocument document; // qmlRegisterType<BlockColorsSet_ViewModel>("com.quatso.tombola", 1, 0, "BlockColorSetListModel"); TicketDrawExecutor ticketDrawExecutor( document , new SingleTicketDraw_ViewModel() , new SingleTicketDraw_ViewModel()); Controller controller(document, ticketDrawExecutor); controller.OnAppStartup(); TicketsSellingPoint_ViewModel ticketsSellingPoint_ViewModel(document); ticketsSellingPoint_ViewModel.Init(ticketDrawExecutor.IsPrizeDrawingRunning()); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("ticketsSellingPoint", QVariant::fromValue(&ticketsSellingPoint_ViewModel)); engine.rootContext()->setContextProperty("ticketDrawExecutor", QVariant::fromValue(&ticketDrawExecutor)); engine.rootContext()->setContextProperty("dynamicTranslation", &dynamicTranslation); engine.rootContext()->setContextProperty("crashHandler", &crashHandler); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QIcon appIcon(":///Images/TombolaAppIcon.png"); app.setWindowIcon(appIcon); int appRetVal = app.exec(); controller.OnAppExit(); return appRetVal; }
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(); }
int main( int argc, char *argv[] ) { // Init controller db file for backend Q_INIT_RESOURCE( controllerdb ); // Uncomment this to enable the message handler for debugging and stack tracing // qInstallMessageHandler( phoenixDebugMessageHandler ); // Handles stuff with the windowing system QGuiApplication app( argc, argv ); // The engine that runs our QML-based UI QQmlApplicationEngine engine; // Set application metadata QGuiApplication::setApplicationDisplayName( QStringLiteral( "Phoenix" ) ); QGuiApplication::setApplicationName( QStringLiteral( "Phoenix" ) ); QGuiApplication::setApplicationVersion( QStringLiteral( "0.0.1" ) ); QGuiApplication::setOrganizationName( QStringLiteral( "Team Phoenix" ) ); QGuiApplication::setOrganizationDomain( QStringLiteral( "phoenix.vg" ) ); // Figure out the right paths for the environment, and create user storage folders if not already there Library::PhxPaths::initPaths(); // For release builds, write to a log file along with the console #ifdef QT_NO_DEBUG QFile logFile( Library::PhxPaths::userDataLocation() % '/' % QStringLiteral( "Logs" ) % '/' % QDateTime::currentDateTime().toString( QStringLiteral( "ddd MMM d yyyy - h mm ss AP" ) ) % QStringLiteral( ".log" ) ); // If this fails... how would we know? :) logFile.open( QIODevice::WriteOnly | QIODevice::Text ); int logFD = logFile.handle(); logFP = fdopen( dup( logFD ), "w" ); qInstallMessageHandler( phoenixDebugMessageLog ); #endif // Open connections to the SQL databases. Library::LibretroDatabase::open(); Library::MetaDataDatabase::open(); // Necessary to quit properly QObject::connect( &engine, &QQmlApplicationEngine::quit, &app, &QGuiApplication::quit ); // Register our custom types for use within QML VideoItem::registerTypes(); InputManager::registerTypes(); // Register our custom QML-accessable/instantiable objects qmlRegisterType<Library::PlatformsModel>( "vg.phoenix.models", 1, 0, "PlatformsModel" ); qmlRegisterType<Library::CollectionsModel>( "vg.phoenix.models", 1, 0, "CollectionsModel" ); qmlRegisterType<Library::LibraryModel>( "vg.phoenix.models", 1, 0, "LibraryModel" ); qmlRegisterType<Library::CoreModel>( "vg.phoenix.models", 1, 0, "CoreModel" ); qmlRegisterType<Library::ImageCacher>( "vg.phoenix.cache", 1, 0, "ImageCacher" ); qmlRegisterType<GameLauncher>( "vg.phoenix.launcher", 1, 0, "GameLauncher" ); // Register our custom QML-accessable objects and instantiate them here qmlRegisterSingletonType( QUrl( "qrc:/PhxTheme.qml" ), "vg.phoenix.themes", 1, 0, "PhxTheme" ); qmlRegisterSingletonType<Library::PhxPaths>( "vg.phoenix.paths", 1, 0, "PhxPaths", PhxPathsSingletonProviderCallback ); qRegisterMetaType<Library::GameData>( "GameData" ); // Load the root QML object and everything under it engine.load( QUrl( QStringLiteral( "qrc:/main.qml" ) ) ); // Ensure custom controller DB file exists QFile gameControllerDBFile( Library::PhxPaths::userDataLocation() % '/' % QStringLiteral( "gamecontrollerdb.txt" ) ); if( !gameControllerDBFile.exists() ) { gameControllerDBFile.open( QIODevice::ReadWrite ); QTextStream stream( &gameControllerDBFile ); stream << "# Insert your custom definitions here" << endl; gameControllerDBFile.close(); } // Set InputManager's custom controller DB file QQmlProperty prop( engine.rootObjects().first(), "inputManager.controllerDBFile" ); Q_ASSERT( prop.isValid() ); QString path = Library::PhxPaths::userDataLocation() % QStringLiteral( "/gamecontrollerdb.txt" ); QVariant pathVar( path ); prop.write( pathVar ); // Run the app and write return code to the log file if in release mode #ifdef QT_NO_DEBUG int ret = app.exec(); fprintf( logFP, "Returned %d", ret ); fclose( logFP ); return ret; #else // Otherwise, just run it normally return app.exec(); #endif }
int main(int argc, char *argv[]) { try { QCommandLineParser parser; parser.setApplicationDescription("Plex Media Player"); parser.addHelpOption(); parser.addVersionOption(); parser.addOptions({{{"l", "licenses"}, "Show license information"}}); parser.addOptions({{{"a", "from-auto-update"}, "When invoked from auto-update"}}); char **newArgv = appendCommandLineArguments(argc, argv, g_qtFlags); argc += g_qtFlags.size(); // Suppress SSL related warnings on OSX // See https://bugreports.qt.io/browse/QTBUG-43173 for more info // #ifdef Q_OS_MAC qputenv("QT_LOGGING_RULES", "qt.network.ssl.warning=false"); #endif // Qt calls setlocale(LC_ALL, "") in a bunch of places, which breaks // float/string processing in mpv and ffmpeg. #ifdef Q_OS_UNIX qputenv("LC_ALL", "C"); qputenv("LC_NUMERIC", "C"); #endif detectOpenGLEarly(); preinitQt(); QGuiApplication app(argc, newArgv); app.setWindowIcon(QIcon(":/images/icon.png")); // Get the arguments from the app, this is the parsed version of newArgc and newArgv QStringList args = app.arguments(); // Remove the qt flags above so that our command line parser doesn't get cranky. for (auto flag : g_qtFlags) args.removeAll(flag); // Now parse the command line. parser.process(args); if (parser.isSet("licenses")) { ShowLicenseInfo(); return EXIT_SUCCESS; } // init breakpad. setupCrashDumper(); UniqueApplication* uniqueApp = new UniqueApplication(); if (!uniqueApp->ensureUnique()) return EXIT_SUCCESS; #ifdef Q_OS_UNIX // install signals handlers for proper app closing. SignalManager signalManager(&app); Q_UNUSED(signalManager); #endif Log::Init(); // Quit app and apply update if we find one. if (UpdateManager::CheckForUpdates()) { app.quit(); return 0; } detectOpenGLLate(); #ifdef Q_OS_WIN32 initD3DDevice(); #endif Codecs::preinitCodecs(); // Initialize all the components. This needs to be done // early since most everything else relies on it // ComponentManager::Get().initialize(); // enable remote inspection if we have the correct setting for it. if (SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "remoteInspector").toBool()) qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "0.0.0.0:9992"); QtWebEngine::initialize(); // start our helper HelperLauncher::Get().connectToHelper(); // load QtWebChannel so that we can register our components with it. QQmlApplicationEngine *engine = Globals::Engine(); KonvergoWindow::RegisterClass(); Globals::SetContextProperty("components", &ComponentManager::Get().getQmlPropertyMap()); // the only way to detect if QML parsing fails is to hook to this signal and then see // if we get a valid object passed to it. Any error messages will be reported on stderr // but since no normal user should ever see this it should be fine // QObject::connect(engine, &QQmlApplicationEngine::objectCreated, [=](QObject* object, const QUrl& url) { Q_UNUSED(url); if (object == nullptr) throw FatalException(QObject::tr("Failed to parse application engine script.")); KonvergoWindow* window = Globals::MainWindow(); QObject* webChannel = qvariant_cast<QObject*>(window->property("webChannel")); Q_ASSERT(webChannel); ComponentManager::Get().setWebChannel(qobject_cast<QWebChannel*>(webChannel)); QObject::connect(uniqueApp, &UniqueApplication::otherApplicationStarted, window, &KonvergoWindow::otherAppFocus); }); engine->load(QUrl(QStringLiteral("qrc:/ui/webview.qml"))); Log::UpdateLogLevel(); // run our application int ret = app.exec(); delete uniqueApp; Globals::EngineDestroy(); Log::Uninit(); return ret; } catch (FatalException& e) { QLOG_FATAL() << "Unhandled FatalException:" << qPrintable(e.message()); QApplication errApp(argc, argv); auto msg = new ErrorMessage(e.message(), true); msg->show(); errApp.exec(); Log::Uninit(); return 1; } }
int main(int argc, char** argv) { srand(time(NULL)); // init rand; #if PORTAL Portal p(Segment(10, 40, 10, 20), Segment(40, 10, 20, 10)); std::vector<Segment> lines(p.deviateLine(Segment(20, 40, 0, 30))); for (const Segment& line: lines) std::cerr << line << std::endl; #endif #if Thumbnail QApplication app(argc, argv); PolygonList polygonList; //polygonList << poc::Polygon(30, 250, 21, 260, 5); poc::Polygon polygon; polygon << Point2d(55, 55) << Point2d(455, 55) << Point2d(455, 455) << Point2d(155, 455) << Point2d(155, 255) << Point2d(255, 255) << Point2d(255, 355) << Point2d(355, 355) << Point2d(355, 155) << Point2d(55, 155); polygonList << polygon; qDebug() << polygonList; ThumbnailCreator thumbnailCreator(polygonList); QImage thumbnail = thumbnailCreator.makeThumbnail(); QLabel* label = new QLabel; label->setPixmap(QPixmap::fromImage(thumbnail)); label->show(); return app.exec(); #endif #if TESTPOINT Test::test<< Point2d(); #endif #if TESTVECTOR Test::testVector2d(); #endif #if TESTPOLYGON Test::testPolygon(); #endif #if GUI QApplication app(argc, argv); // QFontDatabase::addApplicationFont("../PieceOfCake/fonts/edosz.ttf"); // QFontDatabase::addApplicationFont("../PieceOfCake/fonts/watermark.ttf"); qmlRegisterType<GameInfo>("gameinfo", 1, 0, "GameInfo"); qmlRegisterType<LevelInfo>("levelinfo", 1, 0, "LevelInfo"); MainWindow window; window.show(); return app.exec(); #endif #if QML QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); #endif #if GNUPLOT // poc::Polygon polygon; // polygon << << Point2d() << << Point2d(0, 1) << << Point2d(1, 1) << << Point2d(1); poc::Polygon polygon(0, 100, 0, 100, 7); // std::vector<Point2d> vertices = polygon.getVertices(); // for (unsigned int k = 0; k < vertices.size(); ++k) // std::cerr << vertices.at(k).getX() << " " << vertices.at(k).getY() << " " << -10 << std::endl; float size = 300; float delta = 10; int max = size/delta; float** matrix = polygon.surface(size, delta); for (int i = 0; i < max; ++i) { for (int j = 0; j < max; ++j) { std::cerr << i << " " << j << " " << matrix[i][j] << std::endl; } delete[] matrix[i]; } delete[] matrix; #endif #if XML Test::testXML(); #else return EXIT_SUCCESS; #endif }
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[]) { 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[]){ QTime t; t.start(); //START APP QApplication app(argc,argv); app.setWindowIcon(QIcon(":/data/img/11412394_407750046078820_6932822019341529347_n.jpg")); QApplication::setApplicationName("Huffman"); QApplication::setApplicationVersion("ÚNICO"); QQmlApplicationEngine engine; QQmlContext *interpreter = engine.rootContext(); Huffman huff; DHuffman deHuff; QCommandLineParser parser; //Parser parser.addHelpOption(); parser.addVersionOption(); parser.setApplicationDescription("Huffman Parsers"); parser.addPositionalArgument("in-file.x", QCoreApplication::translate("main", "File being compressed.")); parser.addPositionalArgument("out-name.huff", QCoreApplication::translate("main", "Name to save archive.")); //parser.addPositionalArgument("dir", QCoreApplication::translate("main", "Dir being compressed")); parser.addPositionalArgument("local", QCoreApplication::translate("main", "Local to save archive.")); QCommandLineOption compress("c",QApplication::translate("main","Compress <in-file.x>."), QApplication::translate("main","in-file.x")); parser.addOption(compress); QCommandLineOption outName("o",QApplication::translate("main","Save as <out-name.huff>."), QApplication::translate("main","out-file.huff")); parser.addOption(outName); QCommandLineOption local("d",QApplication::translate("main","Decompress in <local>."), QApplication::translate("main","local")); parser.addOption(local); QCommandLineOption startGui({"g", "gui"},QApplication::translate("main","Start gui.")); parser.addOption(startGui); parser.process(app); //ARGUMENTS if(parser.isSet(startGui)){ interpreter->setContextProperty("_huff",&huff); interpreter->setContextProperty("_dehuff",&deHuff); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); } else if(parser.isSet(compress) && parser.isSet(outName)) { cout << "case 1" << endl; huff.Huff(parser.value(compress),parser.value(outName)); } else if(parser.isSet(compress)) { cout << "case 2" << endl; huff.Huff(parser.value(compress),parser.value(compress)); } else{ if(app.arguments().size() == 1) qDebug() << qPrintable(parser.helpText()); else if(parser.isSet(local)) deHuff.DHuff(app.arguments().at(1),parser.value(local)); else deHuff.DHuff(app.arguments().at(1),app.arguments().at(1)); } //END APP qDebug("%s <> Tempo de execução: %d ms",Q_FUNC_INFO,t.elapsed()); return app.exec(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QTextStream out(stdout); out << "Hello world!" << endl; QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("basic.sqlite"); bool ok = db.open(); out << "What is the database name? " << db.databaseName() << endl; out << "Did I connect to " << db.databaseName() << "? " << ok << endl; out << "Is the connection valid? " << db.isValid() << endl; out << "Is the connection open? " << db.isOpen() << endl; out << "What is the driver name? " << db.driverName() << endl; out << "What is the host name? " << db.hostName() << endl; out << "What is the connection name? " << db.connectionName() << endl; out << "What are the connection options? " << db.connectOptions() << endl; bool hasQuerySize = db.driver()->hasFeature(QSqlDriver::QuerySize); out << "Does sqlite support querying the result set size? " << hasQuerySize << endl; out << "Tables:"; QStringList tables = db.tables(); foreach (QString table, tables) { out << " " << table; } out << endl; QSqlQuery query; query.setForwardOnly(true); query.exec("SELECT * from advances"); if (hasQuerySize) { out << "Querying advances (" << query.size() << " results):" << endl; } else { out << "Querying advances:" << endl; } QStringList columns; QSqlRecord record = query.record(); out << "Number of columns: " << record.count() << endl; for (int i = 0; i < record.count(); i++) { out << "column " << i << ": " << record.fieldName(i) << endl; columns.append(record.fieldName(i)); } QList<QObject*> advances; while(query.next()) { Civilization::Advance *advance = new Civilization::Advance(); out << "advance " << advances.size() << ":"; for (int i = 0; i < columns.size(); i++) { out << " " << columns[i] << ": " << query.value(i).toString(); QVariant v(query.value(i).toString()); advance->setProperty(columns[i].toLatin1().data(), v); } out << endl; advances.append(advance); } out << advances.size() << " results." << endl; db.close(); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("advanceListModel", QVariant::fromValue(advances)); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
Q_DECL_EXPORT int main(int argc, char *argv[]) { #ifdef Q_OS_SYMBIAN QApplication::setAttribute((Qt::ApplicationAttribute)11); //Qt::AA_CaptureMultimediaKeys #endif QApplication app(argc, argv); app.setApplicationName("QVideo"); app.setOrganizationName("QShen"); app.setApplicationVersion(VER); QString locale = QLocale::system().name(); QTranslator translator; if(!translator.load(QString("QVideo_") + locale,":/i18n")){ qDebug()<<"translator load erro"; } app.installTranslator(&translator); Utility utility; Settings settings; #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QmlApplicationViewer viewer; //viewer.setAttribute(Qt::WA_OpaquePaintEvent); //viewer.setAttribute(Qt::WA_NoSystemBackground); //viewer.viewport()->setAttribute(Qt::WA_OpaquePaintEvent); //viewer.viewport()->setAttribute(Qt::WA_NoSystemBackground); viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait); viewer.rootContext()->setContextProperty("utility", &utility); viewer.rootContext()->setContextProperty("settings", &settings); viewer.rootContext()->setContextProperty("appVersion", app.applicationVersion()); #ifdef Q_OS_SYMBIAN QSplashScreen *splash = new QSplashScreen(QPixmap(":/qml/pic/splash_symbian.png")); splash->show(); splash->raise(); viewer.setSource(QUrl("qrc:/qml/Symbian/main.qml")); #elif defined(Q_OS_HARMATTAN) //QApplication::setGraphicsSystem("native"); viewer.setSource(QUrl("qrc:/qml/Meego/main.qml")); #elif defined(Q_WS_SIMULATOR) viewer.setSource(QUrl("qrc:/qml/Symbian/main.qml")); #endif viewer.showExpanded(); #else QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("utility",&utility); #ifdef Q_OS_WIN32 engine.load(QUrl(QStringLiteral("qrc:/qml/Win32/main.qml"))); #endif #endif #ifdef Q_OS_SYMBIAN splash->finish(&viewer); splash->deleteLater(); #endif return app.exec(); }
void addImportPath(QQmlApplicationEngine& engine, const QString& relativePath, bool insert = false) { QString resolvedPath = getRelativeDir(relativePath); qDebug() << "adding import path: " << QDir::toNativeSeparators(resolvedPath); engine.addImportPath(resolvedPath); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setApplicationName ("QQStars"); app.setApplicationVersion ("1.0.0"); app.setOrganizationName ("雨后星辰"); app.setApplicationDisplayName ("星辰QQ"); QTranslator *translator = new QTranslator; translator->load (":/qt_zh_CN.qm"); QApplication::installTranslator (translator); QQmlApplicationEngine *engine = new QQmlApplicationEngine; engine->setNetworkAccessManagerFactory (new MyNetworkAccessManagerFactory());//给qml设置网络请求所用的类 qmlRegisterType<TextEditPlayGif>("MyTextEditPlugin", 1, 0, "TextEditPlayGif"); qmlRegisterType<MyWindow>("mywindow", 1,0, "MyQuickWindow"); qmlRegisterType<SystemTrayIcon>("mywindow", 1,0, "MySystemTrayIcon"); qmlRegisterType<MyMenu>("mywindow", 1,0, "MyMenu"); qmlRegisterType<MenuSeparator>("mywindow", 1,0, "MenuSeparator"); qmlRegisterType<MyMenuItem>("mywindow", 1,0, "MyMenuItem"); qmlRegisterType<MyShortcut>("utility", 1,0, "MyShortcut"); qmlRegisterType<DownloadImage>("utility", 1, 0, "DownloadImage"); qmlRegisterType<QQCommand>("qqstars", 1,0, "QQ"); qmlRegisterType<FriendInfo>("QQItemInfo", 1,0, "FriendInfo"); qmlRegisterType<GroupInfo>("QQItemInfo", 1,0, "GroupInfo"); qmlRegisterType<DiscuInfo>("QQItemInfo", 1,0, "DiscuInfo"); qmlRegisterType<QQItemInfo>("QQItemInfo", 1,0, "QQItemInfo"); qmlRegisterType<ChatMessageInfo>("QQItemInfo", 1, 0, "ChatMessageInfo"); qmlRegisterType<ChatMessageInfoList>("QQItemInfo", 1, 0, "ChatMessageInfoList"); qmlRegisterType<MyImage>("mywindow", 1,0, "MyImage"); qmlRegisterType<MySvgView>("mywindow", 1, 0, "SvgView"); qmlRegisterType<MyMessageBox>("mywindow", 1, 0, "MessageBox"); Utility *utility=Utility::createUtilityClass (); QNetworkRequest* request = utility->getHttpRequest ()->getNetworkRequest (); request->setRawHeader ("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");//和腾讯服务器打交道需要设置这个 request->setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); request = utility->getDownloadImage ()->getHttpRequest ()->getNetworkRequest (); request->setRawHeader ("Referer", "http://web2.qq.com/webqq.html");//需要设置这个,不然腾讯服务器不响应你的请求 request->setRawHeader ("Accept", "image/webp,*/*;q=0.8"); utility->initUtility (new QSettings, engine); QQmlComponent component0(engine, QUrl("qrc:/qml/Api/QQApi.qml")); QQCommand *qqapi = qobject_cast<QQCommand *>(component0.create ()); engine->rootContext ()->setContextProperty ("myqq", qqapi); QQmlComponent component(engine, QUrl("qrc:/qml/Utility/SystemTray.qml")); SystemTrayIcon *systemTray = qobject_cast<SystemTrayIcon *>(component.create ()); #ifdef Q_OS_WIN systemTray->setParent (Utility::createUtilityClass ());//不设置父对象会导致程序退出后托盘还存在的问题 #endif engine->rootContext ()->setContextProperty ("systemTray", systemTray);//将程序托盘注册过去 qqapi->loadLoginWindow ();//加载登录窗口 return app.exec(); }
int main(int argc, char *argv[]) { try { QApplication app(argc, argv); QString commands; //Mac specific Terminal command commands = "system_profiler SPHardwareDataType"; //commands = "cat abc"; /* Wrong cat file -- testing */ //commands = " abc"; /* Wrong Terminal command -- testing */ /* For Linux and Ubuntu we use -- cat /proc/cpuinfo*/ QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QProcess *process = new QProcess(0); process->setProcessChannelMode(QProcess::MergedChannels); //process->start("system_profiler SPHardwareDataType"); process->start(commands); QByteArray arrSysInfo; process->write(arrSysInfo); process->closeWriteChannel(); if(!process->waitForStarted()){ qDebug() << "Could not wait to start..." << process->error() << process->errorString(); } if(!process->waitForFinished()) { qDebug() << "Could not wait to finish..." << process->error() << process->errorString(); } else{ mySysInfo output; /* interface */ output.setData( process->readAll()); QObject *rootObject = engine.rootObjects().first(); QObject* lstview = rootObject->findChild<QObject*>("lstview"); if (lstview) lstview->setProperty("placeholderText", output.getData());//quick fix } return app.exec(); } catch(std::exception e) {\ qDebug() << "Exception caught in main()" << e.what(); } }
int main(int argc, char *argv[]) { try { for (int n = 1; n < argc; n++) { if (strcmp(argv[n], "--licenses") == 0) { QFile licenses(":/misc/licenses.txt"); licenses.open(QIODevice::ReadOnly | QIODevice::Text); QByteArray contents = licenses.readAll(); printf("%.*s\n", (int)contents.size(), contents.data()); return 0; } } int newArgc = argc; char **newArgv = appendCommandLineArguments(&newArgc, argv); // Supress SSL related warnings on OSX // See https://bugreports.qt.io/browse/QTBUG-43173 for more info // #ifdef Q_OS_MAC qputenv("QT_LOGGING_RULES", "qt.network.ssl.warning=false"); // Request OpenGL 4.1 if possible on OSX, otherwise it defaults to 2.0 // This needs to be done before we create the QGuiApplication // QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setMajorVersion(3); format.setMinorVersion(2); format.setProfile(QSurfaceFormat::CoreProfile); QSurfaceFormat::setDefaultFormat(format); #endif QGuiApplication app(newArgc, newArgv); initQt(&app); // init breakpad. setupCrashDumper(); UniqueApplication* uniqueApp = new UniqueApplication(); if (!uniqueApp->ensureUnique()) return EXIT_SUCCESS; #ifdef Q_OS_UNIX // install signals handlers for proper app closing. SignalManager signalManager(&app); Q_UNUSED(signalManager); #endif initLogger(); QLOG_INFO() << "Starting Plex Media Player version:" << qPrintable(Version::GetVersionString()) << "build date:" << qPrintable(Version::GetBuildDate()); QLOG_INFO() << qPrintable(QString(" Running on: %1 [%2] arch %3").arg(QSysInfo::prettyProductName()).arg(QSysInfo::kernelVersion()).arg(QSysInfo::currentCpuArchitecture())); QLOG_INFO() << " Qt Version:" << QT_VERSION_STR << qPrintable(QString("[%1]").arg(QSysInfo::buildAbi())); // Quit app and apply update if we find one. if (UpdateManager::CheckForUpdates()) { app.quit(); return 0; } #ifdef Q_OS_WIN32 initD3DDevice(); #endif #ifdef Q_OS_UNIX setlocale(LC_NUMERIC, "C"); #endif // Initialize all the components. This needs to be done // early since most everything else relies on it // ComponentManager::Get().initialize(); // enable remote inspection if we have the correct setting for it. if (SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "remoteInspector").toBool()) qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "0.0.0.0:9992"); QtWebEngine::initialize(); // Qt and QWebEngineProfile set the locale, which breaks parsing and // formatting float numbers in a few countries. #ifdef Q_OS_UNIX setlocale(LC_NUMERIC, "C"); #endif // start our helper HelperLauncher::Get().connectToHelper(); // load QtWebChannel so that we can register our components with it. QQmlApplicationEngine *engine = KonvergoEngine::Get(); KonvergoWindow::RegisterClass(); engine->rootContext()->setContextProperty("components", &ComponentManager::Get().getQmlPropertyMap()); // This controls how big the web view will zoom using semantic zoom // over a specific number of pixels and we run out of space for on screen // tiles in chromium. This only happens on OSX since on other platforms // we can use the GPU to transfer tiles directly but we set the limit on all platforms // to keep it consistent. // // See more discussion in: https://github.com/plexinc/plex-media-player/issues/10 // The number of pixels here are REAL pixels, the code in webview.qml will compensate // for a higher DevicePixelRatio // engine->rootContext()->setContextProperty("webMaxHeight", 1440); // the only way to detect if QML parsing fails is to hook to this signal and then see // if we get a valid object passed to it. Any error messages will be reported on stderr // but since no normal user should ever see this it should be fine // QObject::connect(engine, &QQmlApplicationEngine::objectCreated, [=](QObject* object, const QUrl& url) { Q_UNUSED(url); if (object == 0) throw FatalException(QObject::tr("Failed to parse application engine script.")); QObject* rootObject = engine->rootObjects().first(); QObject* webChannel = qvariant_cast<QObject*>(rootObject->property("webChannel")); Q_ASSERT(webChannel); ComponentManager::Get().setWebChannel(qobject_cast<QWebChannel*>(webChannel)); KonvergoWindow* window = qobject_cast<KonvergoWindow*>(rootObject); Q_ASSERT(window); QObject::connect(uniqueApp, &UniqueApplication::otherApplicationStarted, window, &KonvergoWindow::otherAppFocus); }); engine->load(QUrl(QStringLiteral("qrc:/ui/webview.qml"))); updateLogLevel(); // run our application int ret = app.exec(); delete KonvergoEngine::Get(); delete uniqueApp; return ret; } catch (FatalException& e) { QLOG_FATAL() << "Unhandled FatalException:" << qPrintable(e.message()); QGuiApplication app(argc, argv); QString text = e.message() + "<br>" + QObject::tr("Please visit Plex support forums for support."); QQmlApplicationEngine* engine = new QQmlApplicationEngine(NULL); engine->rootContext()->setContextProperty("errorTitle", QObject::tr("A critical error occurred.")); engine->rootContext()->setContextProperty("errorText", text); engine->load(QUrl(QStringLiteral("qrc:/ui/errormessage.qml"))); app.exec(); return 1; } }
int main( int argc, char* argv[] ) { QApplication app(argc, argv); LOGGER.setLevel( 3 ); LOGGER.setOutput( Logger::Console ); LOG( 1, "Pixout ArtNet Viewer" ); LOG( 1, "viewer Version: %s ", VERSION ); const QString settings_path = QDir::fromNativeSeparators( QStandardPaths::writableLocation( QStandardPaths::AppLocalDataLocation ) + QDir::separator() ); // create settings location if not exists QDir ().mkdir( settings_path ); AppSettings settings; if( argc < 3 ) { if( !settings.load( settings_path + "app.data") ) { WARN("Can't open or empty fixture file: %s", qPrintable(settings_path + "app.data") ); } } else { settings.setProperty("port", atoi( argv[1] )); settings.setProperty("fixturePath", argv[2]); settings.setProperty("position", argv[3]); } QQmlApplicationEngine engine; app.setWindowIcon(QIcon(":favicon.png")); engine.addImportPath( QStringLiteral("qrc:/")); qmlRegisterType<PainterOutput>("Painter", 1, 0, "PainterItem"); qmlRegisterUncreatableType<AppSettings,1>("AppSettings",1,0,"AppSettings","AppSettings couldn't be created from QML"); engine.rootContext()->setContextProperty("settings", &settings); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QObject *rootObject = engine.rootObjects().first(); Q_ASSERT( rootObject ); PainterOutput *output( rootObject->findChild<PainterOutput*>( "painter" ) ); Q_ASSERT( output ); Painter painter( output, &settings ); PixelMapperWithError mapper( &settings ); painter.SetPixelMapper( &mapper ); Receiver receiver( &settings ); QObject::connect( &receiver, &Receiver::Received, &painter, &Painter::Draw ); QObject::connect( &painter, &Painter::ReadyToOutput, output, &PainterOutput::Process ); QObject::connect( &mapper, &PixelMapper::OnResize, &painter, &Painter::Resize ); QObject::connect( &mapper, &PixelMapper::OnResize, output, &PainterOutput::setCellSize ); QObject::connect( &settings, &AppSettings::fixturePathChanged, &mapper, &PixelMapperWithError::Reload ); QObject::connect( &settings, &AppSettings::portChanged, &receiver, &Receiver::Reconnect ); QObject::connect( &settings, &AppSettings::positionChanged, &painter, &Painter::RePosition ); if( !settings.fixturePath().isEmpty() ) mapper.Reload(); else WARN("Pixel mapping empty, skip" ); LOG(1, "Listening on port %u with pixel-mapping file %s and orientation %s", settings.port(), qPrintable(settings.fixturePath()), painter.Orientation() == Painter::Vertical ? "vertical" : "horizontal" ); QQuickWindow *window = qobject_cast<QQuickWindow *>(rootObject); Q_ASSERT( window ); window->show(); const int res = app.exec(); settings.Save( settings_path + "app.data" ); return res; }
int main(int argc, char *argv[]) { QApplication app(argc, argv); //WmnDriver * drv = new WmnDriver(); TestClass * tst1 = new TestClass(10); TestClass * tst2 = new TestClass(20); //drv->Sleep(); int tmp = 0; //drv->setTestCallback(tst1, TestClass::onRxCallback); //tmp = drv->runTestCallback(1); //drv->setTestCallback(tst2, TestClass::onRxCallback); //tmp = drv->runTestCallback(3); //drv->setTestCallback(tst1, TestClass::onRxCallback); //tmp = drv->runTestCallback(5); //drv->setTestCallback(tst2, TestClass::onRxCallback); //tmp = drv->runTestCallback(7); WmnCipher * cph = new WmnCipher(); uint8_t key[] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; uint8_t in[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a}; uint8_t out[] = {0x3a, 0xd7, 0x7b, 0xb4, 0x0d, 0x7a, 0x36, 0x60, 0xa8, 0x9e, 0xca, 0xf3, 0x24, 0x66, 0xef, 0x97}; uint8_t buffer[16]; //AES128_ECB_encrypt(in, key, buffer); printf("ECB decrypt: "); //AES128_CBC_encrypt_buffer(buffer, in, 64, key, iv); cph->encryptBuffer(in,buffer,key); if(0 == strncmp((char*) out, (char*) buffer, 16)) { printf("SUCCESS!\n"); } else { printf("FAILURE!\n"); } memcpy(out,buffer,16); cph->decryptBuffer(out,buffer,key); if(0 == strncmp((char*) in, (char*) buffer, 16)) { printf("SUCCESS!\n"); } else { printf("FAILURE!\n"); } QTranslator translator; translator.load("wmn_tester_ru.qm", app.applicationDirPath()+"/lang"); app.installTranslator(&translator); // Register our component type with QML. qmlRegisterType<Transceiver>("com.ics.demo", 1, 0, "Transceiver"); QQmlApplicationEngine engine; // WmnDriverUsb * drvusb = new WmnDriverUsb(0x2345, 0x0000); // drvusb->start(); // engine.rootContext()->setContextProperty("drvusb", drvusb); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); app.exec(); // drvusb->quit(); // drvusb->wait(); return 0; }
/** * @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; }
int main(int argc, char **argv){ QApplication app(argc, argv, true); #ifdef Q_OS_WIN32 app.setFont(QFont("Microsoft YaHei")); #endif #ifdef Q_OS_LINUX app.setFont(QFont("WenQuanYi Micro Hei")); #endif //just for debug //qInstallMessageHandler(crashMessageOutput); loadTranslate(app); #ifdef Q_OS_UNIX bool disabledrootcheck = false; //disabledrootcheck = true; QStringList allappargs = app.arguments(); if (!disabledrootcheck) { QProcess whoamip; whoamip.start("whoami"); whoamip.waitForFinished(); if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root") { QString argsconc = ""; QString argsconcSingleQuote = ""; for (int i = 1; i < allappargs.size(); ++i) { argsconc += QString("\"%1\" ").arg(allappargs.at(i)); argsconcSingleQuote += QString("'%1' ").arg(allappargs.at(i)); } argsconc += "\"rootcheck=no\""; argsconcSingleQuote += "'rootcheck=no'"; #ifdef Q_OS_LINUX QString gksulocation = checkforgraphicalsu("gksu"); if (gksulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesulocation = checkforgraphicalsu("kdesu"); if (kdesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString gnomesulocation = checkforgraphicalsu("gnomesu"); if (gnomesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesudolocation = checkforgraphicalsu("kdesudo"); if (kdesudolocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QMessageBox rootmsgb; rootmsgb.setIcon(QMessageBox::Warning); rootmsgb.setWindowTitle(uninstaller::tr("Must run as root")); rootmsgb.setTextFormat(Qt::RichText); rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su - -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB)); rootmsgb.setStandardButtons(QMessageBox::Ok); switch (rootmsgb.exec()) { case QMessageBox::Ok: break; default: break; } #endif #ifdef Q_OS_MAC /* QProcess osascriptProc; osascriptProc.start("osascript"); osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data()); osascriptProc.closeWriteChannel(); osascriptProc.waitForFinished(-1); */ //qDebug() << QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc); //QProcess::startDetached(QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc)); QProcess::startDetached("osascript", QStringList() << "-e" << QString("do shell script \"'%1' %2\" with administrator privileges").arg(app.applicationFilePath()).arg(argsconcSingleQuote)); return 0; #endif } } #endif qmlRegisterType<BootMaker>("com.deepin.bootmaker", 1, 0, "BootMaker"); qmlRegisterType<DOverrideWindow>("com.deepin.usbcreator", 1, 0, "DOverrideWindow"); qmlRegisterType<DWindow>("com.deepin.usbcreator", 1, 0, "DWindow"); qmlRegisterType<DIcon>("com.deepin.usbcreator", 1, 0, "DIcon"); qmlRegisterType<DDropArea>("com.deepin.usbcreator", 1, 0, "DDropArea"); QQmlApplicationEngine engine; engine.addImportPath("qrc:/qml/"); #ifdef Q_OS_WIN32 if (CheckIsXP()){ app.setFont(QFont("SimHei", 12)); engine.load(QUrl("qrc:/qml/xp-fix-mainui.qml")); } else{ engine.load(QUrl("qrc:/qml/mainui.qml")); } #else engine.load(QUrl("qrc:/qml/mainui.qml")); #endif app.setOverrideCursor( QCursor( Qt::ArrowCursor ) ); QList<QObject *> roots = engine.rootObjects(); QObject *topLevel = roots.value(0); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); if (!window) { qCritical("load qrc:/qml/mainui.qml error!!"); } QIcon icon; icon.addFile(":/image/deepin-boot-maker.png"); window->setIcon(icon); window->show(); window->setTitle(QApplication::tr("Deepin Boot Maker")); return app.exec(); }
int main(int argc, char *argv[]) { QStringList imports, plugins; QGuiApplication app(argc, argv); app.setApplicationName("Terrarium"); app.setOrganizationName("terrariumapp"); app.setOrganizationDomain("terrariumapp.com"); #if defined(Q_OS_MACX) int platformId = 0; #elif defined(Q_OS_IOS) int platformId = 1; #elif defined(Q_OS_ANDROID) int platformId = 2; #elif defined(Q_OS_LINUX) int platformId = 3; #else int platformId = 4; #endif qmlRegisterType<QHttpServer>("HttpServer", 1, 0, "HttpServer"); qmlRegisterType<DocumentHandler>("DocumentHandler", 1, 0, "DocumentHandler"); qmlRegisterUncreatableType<QHttpRequest>("HttpServer", 1, 0, "HttpRequest", "Do not create HttpRequest directly"); qmlRegisterUncreatableType<QHttpResponse>("HttpServer", 1, 0, "HttpResponse", "Do not create HttpResponse directly"); QString platformIP; foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) platformIP = address.toString(); } // Handle command line arguments const QStringList arguments = QCoreApplication::arguments(); for (int i = 1, size = arguments.size(); i < size; ++i) { const QString lowerArgument = arguments.at(i).toLower(); if (lowerArgument == QLatin1String("-i") && i + 1 < size) { imports.append(arguments.at(++i)); } else if (lowerArgument == QLatin1String("-p") && i + 1 < size) { plugins.append(arguments.at(++i)); } } #if USE_WEBENGINE QtWebEngine::initialize(); #endif #if QT_VERSION > QT_VERSION_CHECK(5, 1, 0) QQmlApplicationEngine engine; for(int i = 0; i < imports.size(); ++i) { engine.addImportPath(imports[i]); } for(int i = 0; i < plugins.size(); ++i) { engine.addPluginPath(plugins[i]); } engine.rootContext()->setContextProperty("platform", QVariant::fromValue(platformId)); engine.rootContext()->setContextProperty("platformIP", QVariant::fromValue(platformIP)); engine.rootContext()->setContextProperty("Grabber",new QuickItemGrabber(&app)); engine.load(QUrl("qrc:///main.qml")); #else QQuickView view; view.engine()->rootContext()->setContextProperty("platform", QVariant::fromValue(platformId)); view.engine()->rootContext()->setContextProperty("platformIP", QVariant::fromValue(platformIP)); view.setSource(QUrl("qrc:///main.qml")); view.show(); #endif return app.exec(); }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qmlRegisterType<Graph>("Graph", 1, 0, "Graph"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); app.setWindowIcon(QIcon(":/content/icon.png")); QMLHandlerCppSide alertLamp(engine.rootObjects()[0], "alertLamp"); QMLHandlerCppSide lineSens(engine.rootObjects()[0], "lineSens"); QMLHandlerCppSide textAccelX(engine.rootObjects()[0], "textAccelX"); QMLHandlerCppSide textAccelY(engine.rootObjects()[0], "textAccelY"); QMLHandlerCppSide textAccelZ(engine.rootObjects()[0], "textAccelZ"); QMLHandlerCppSide textGyroX(engine.rootObjects()[0], "textGyroX"); QMLHandlerCppSide textGyroY(engine.rootObjects()[0], "textGyroY"); QMLHandlerCppSide textGyroZ(engine.rootObjects()[0], "textGyroZ"); QMLHandlerCppSide textCurStatus(engine.rootObjects()[0], "textCurStatus"); QMLHandlerCppSide comboSetStatus(engine.rootObjects()[0], "comboSetStatus"); QMLHandlerCppSide textCurSpeed(engine.rootObjects()[0], "textCurSpeed"); QMLHandlerCppSide editSetSpeed(engine.rootObjects()[0], "editSetSpeed"); QMLHandlerCppSide wheels(engine.rootObjects()[0], "wheels"); QMLHandlerCppSide carAccelY(engine.rootObjects()[0], "carAccelY"); QMLHandlerCppSide carGyroX(engine.rootObjects()[0], "carGyroX"); QMLHandlerCppSide carGyroY(engine.rootObjects()[0], "carGyroY"); QMLHandlerCppSide carGyroZ(engine.rootObjects()[0], "carGyroZ"); QMLHandlerCppSide statusHistory(engine.rootObjects()[0], "statusHistory"); QMLHandlerCppSide speedGraph(engine.rootObjects()[0], "speedGraph"); QMLHandlerCppSide buttonConDiscon(engine.rootObjects()[0], "buttonConDiscon"); QMLHandlerCppSide buttonSendStatus(engine.rootObjects()[0], "buttonSendStatus"); QMLHandlerCppSide buttonSendSpeed(engine.rootObjects()[0], "buttonSendSpeed"); QMLHandlerCppSide buttonCarSelfTest(engine.rootObjects()[0], "buttonCarSelfTest"); GuiHandler guihandle(&alertLamp, &lineSens, &textAccelX, &textAccelY, &textAccelZ, &textGyroX, &textGyroY, &textGyroZ, &textCurStatus, &comboSetStatus, &textCurSpeed, &editSetSpeed, &wheels, &carAccelY, &carGyroX, &carGyroY, &carGyroZ, &statusHistory, &speedGraph, &buttonConDiscon, &buttonSendStatus, &buttonSendSpeed, &buttonCarSelfTest); Robot mikrobi; QObject::connect(&guihandle, SIGNAL(buttonConClicked()), &mikrobi, SLOT(connect())); QObject::connect(&guihandle, SIGNAL(buttonDisClicked()), &mikrobi, SLOT(disconnect())); QObject::connect(&guihandle, SIGNAL(buttonCarSelfTestClicked()), &mikrobi, SLOT(selfTest())); QObject::connect(&guihandle, SIGNAL(buttonSendStatusClicked(QString)), &mikrobi, SLOT(status(QString))); QObject::connect(&guihandle, SIGNAL(buttonSendSpeedClicked(float)), &mikrobi, SLOT(speed(float))); QObject::connect(&mikrobi, SIGNAL(connected()), &guihandle, SLOT(robotConnected())); QObject::connect(&mikrobi, SIGNAL(setAlert(int)), &guihandle, SLOT(setAlert(int))); QObject::connect(&mikrobi, SIGNAL(disconnected()), &guihandle, SLOT(robotDisconnected())); QObject::connect(&mikrobi, SIGNAL(setLedStrip(QVarLengthArray<bool>)), &guihandle, SLOT(setLedStrip(QVarLengthArray<bool>))); QObject::connect(&mikrobi, SIGNAL(setTextAccelX(float)), &guihandle, SLOT(setTextAccelX(float))); QObject::connect(&mikrobi, SIGNAL(setTextAccelY(float)), &guihandle, SLOT(setTextAccelY(float))); QObject::connect(&mikrobi, SIGNAL(setTextAccelZ(float)), &guihandle, SLOT(setTextAccelZ(float))); QObject::connect(&mikrobi, SIGNAL(setTextGyroX(float)), &guihandle, SLOT(setTextGyroX(float))); QObject::connect(&mikrobi, SIGNAL(setTextGyroY(float)), &guihandle, SLOT(setTextGyroY(float))); QObject::connect(&mikrobi, SIGNAL(setTextGyroZ(float)), &guihandle, SLOT(setTextGyroZ(float))); QObject::connect(&mikrobi, SIGNAL(setTextStatus(QString)), &guihandle, SLOT(setTextStatus(QString))); QObject::connect(&mikrobi, SIGNAL(setTextSpeed(float)), &guihandle, SLOT(setTextSpeed(float))); QObject::connect(&mikrobi, SIGNAL(setWheels(QVarLengthArray<float>, const float)), &guihandle, SLOT(setWheels(QVarLengthArray<float>, const float))); QObject::connect(&mikrobi, SIGNAL(setCarAccelY(QVarLengthArray<float>, float)), &guihandle, SLOT(setCarAccelY(QVarLengthArray<float>, float))); QObject::connect(&mikrobi, SIGNAL(setCarGyroX(float)), &guihandle, SLOT(setCarGyroX(float))); QObject::connect(&mikrobi, SIGNAL(setCarGyroY(float)), &guihandle, SLOT(setCarGyroY(float))); QObject::connect(&mikrobi, SIGNAL(setCarGyroZ(float)), &guihandle, SLOT(setCarGyroZ(float))); QObject::connect(&mikrobi, SIGNAL(drawSpeedGraph(float)), &guihandle, SLOT(drawSpeedGraph(float))); QObject::connect(&mikrobi, SIGNAL(setTextStatus(QString)), &guihandle, SLOT(addStatusHistory(QString))); return app.exec(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); //-------------------------------------- // 注册qml新组件(供QML中调用) // 参见示例:qml/Extension/TestPieChart.qml //-------------------------------------- //qmlRegisterType<PieChart>("Charts", 1, 0, "PieChart"); //qmlRegisterType<GradientEx>("Charts", 1, 0, "GradientEx"); //qmlRegisterType<Gradiente>("MisComponentes", 1, 0, "Gradiente"); //qmlRegisterType<FileIO, 1>("FileIO", 1, 0, "FileIO"); //qmlRegisterType<ImageProcessor>("an.qt.ImageProcessor", 1, 0,"ImageProcessor"); //qmlRegisterType<MyPushButton>("QWidgets", 1, 0, "MyPushButton"); //-------------------------------------- // 注册上下文对象(供QML中调用) // 参见示例:qml/Extension/TestCallQml.qml //-------------------------------------- QQmlEngine engine; QQmlContext *ctx = engine.rootContext(); Utils u; //ctx->setContextProperty("Utils", new Utils(0)); //ctx->setContextProperty("fonts", QVariant::fromValue(Utils::getFonts())); //ctx->setContextProperty("lists", QVariant::fromValue(Utils::getStringList())); //-------------------------------------- // 创建QML对象,并操作QML中暴露的方法和属性 // 参见示例:qml/Extension/TestCallQml.qml //-------------------------------------- // 调用qml对象中的方法 //QQmlComponent component(&engine, QUrl("qml/Extension/TestCallQml.qml")); //QObject *object = component.create(ctx); // 调用方法 //QString retVal; //QMetaObject::invokeMethod(object, "say", Qt::DirectConnection, // Q_RETURN_ARG(QString, retVal), // Q_ARG(QString, "hello world") // ); // 操作属性 //int n = QMetaObject::indexOfProperty("name"); //QMetaProperty property = QMetaObject::property(n); //QMetaObject::SetProperty(object, "setName", "you name"); //QVariant v = QMetaObject::ReadProperty(object, "getName"); //-------------------------------------- // main //-------------------------------------- QQmlApplicationEngine e; e.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QGuiApplication::setApplicationName("Presentao"); QGuiApplication::setOrganizationName("Embedded_Multimedia"); QSettings settings; QString style = QQuickStyle::name(); if (!style.isEmpty()) settings.setValue("style", style); else QQuickStyle::setStyle(settings.value("style").toString()); web_socket_client websocketclient; audioWindow audioengine; QQmlApplicationEngine engine; engine.load(QUrl(QLatin1String("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; PdfRenderer myPdfRenderer; handcontrol myhandcontrol; engine.addImageProvider(QLatin1String("pdfrenderer"), &myPdfRenderer); QObject *root = engine.rootObjects()[0]; //QObject::connect(root, SIGNAL(nextpage()),&myPdfRenderer, SLOT(nextPage())); //QObject::connect(root, SIGNAL(prevpage()),&myPdfRenderer, SLOT(prevPage())); QObject::connect(root, SIGNAL(openfile(QUrl)),&myPdfRenderer, SLOT(OpenPDF(QUrl))); QObject::connect(&myPdfRenderer, SIGNAL(sendTotalPageCount(QVariant)),root, SLOT(setTotalPageCount(QVariant))); /* * signals from web_socket_client * void OpenPDF(QString) * void signal_setPage(int) * void connection_success() */ QObject::connect(&websocketclient, SIGNAL(OpenPDF(QUrl)), &myPdfRenderer, SLOT(OpenPDF(QUrl))); QObject::connect(&websocketclient, SIGNAL(signal_setPage(QVariant)), root, SLOT(setCurrentPageNr(QVariant))); QObject::connect(&websocketclient, SIGNAL(connection_success()), root, SLOT(connection_success())); /* * slots of web_socket_client * void connect(QString) * void onConnected() * void onBinaryMessage(QByteArray) * void onTextMessage(QString) * void sendFile(QString filename) * void registerMaster(QString) * void download_pdf(QString filename) * void getPage() * void setPage(QString) */ QObject::connect(root, SIGNAL(connect(QString)), &websocketclient, SLOT(connect(QString))); QObject::connect(root, SIGNAL(registerMaster(QString)), &websocketclient, SLOT(registerMaster(QString))); QObject::connect(root, SIGNAL(sendFile(QUrl)), &websocketclient, SLOT(sendFile(QUrl))); QObject::connect(root, SIGNAL(download_pdf(QString)), &websocketclient, SLOT(download_pdf(QString))); QObject::connect(root, SIGNAL(setPage(QString)), &websocketclient, SLOT(setPage(QString))); QObject::connect(root, SIGNAL(getPage()), &websocketclient, SLOT(getPage())); //AUDIO QObject::connect(root, SIGNAL(startstopKlopfen()),&audioengine, SLOT(startStopRecording())); QObject::connect(&audioengine, SIGNAL(knock()),root, SLOT(klopf_weiter())); QObject::connect(&audioengine, SIGNAL(double_knock()),root,SLOT(klopf_zurück())); // Gestensteuerng QObject *cameraComponent = root->findChild<QObject*>("camera"); QCamera *camera = qvariant_cast<QCamera*>(cameraComponent->property("mediaObject")); myhandcontrol.setCamera(camera); QObject::connect(root, SIGNAL(handcontrol_enable(int)),&myhandcontrol, SLOT(enable(int))); QObject::connect(&myhandcontrol, SIGNAL(debugMessage(QVariant)),root, SLOT(handcontrol_debugOut(QVariant))); QObject::connect(&myhandcontrol, SIGNAL(errorMessage(QVariant)),root, SLOT(handcontrol_debugOut(QVariant))); QObject::connect(&myhandcontrol, SIGNAL(change_page(QVariant)),root, SLOT(handcontrol_change_page(QVariant))); qDebug()<<"From main thread: "<<QThread::currentThreadId(); return app.exec(); }
/*! \brief Main method for the YARPView container. * * \param argc * \param argv */ int main(int argc, char *argv[]) { bool minimal=false; bool compact=false; bool keepabove=false; // Pack the argc and argv to a QStringList so we can pass them easily to // the plugin. // This list must be packed before creating the QApplication, because // QApplication will remove the known arguments, and this includes the // "--name <name>" argument on linux. QStringList params; for(int i=1;i<argc;i++){ params.append(argv[i]); if (std::string(argv[i]) == "--compact") { compact=true; } if (std::string(argv[i]) == "--minimal") { minimal=true; } if (std::string(argv[i]) == "--keep-above") { keepabove=true; } } QApplication app(argc, argv); QVariant retVal; // De-comment this to trace all imports /*QByteArray data = "1"; qputenv("QML_IMPORT_TRACE", data);*/ QQmlApplicationEngine engine; engine.addImportPath(QDir::cleanPath(QCoreApplication::applicationDirPath() + QDir::separator() + PLUGINS_RELATIVE_PATH)); #ifdef CMAKE_INTDIR engine.addImportPath(QDir::cleanPath(QCoreApplication::applicationDirPath() + QDir::separator() + ".." + QDir::separator() + PLUGINS_RELATIVE_PATH + QDir::separator() + CMAKE_INTDIR)); #endif if (compact || minimal) { engine.load(QUrl("qrc:/qml/QtYARPView/mainCompact.qml")); } else { engine.load(QUrl("qrc:/qml/QtYARPView/main.qml")); } QObject *topLevel = engine.rootObjects().value(0); if(!topLevel){ return 0; } QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); if (minimal) { window->setFlags(Qt::FramelessWindowHint); } if (keepabove) { window->setFlags(Qt::WindowStaysOnTopHint); } // Call the parseParameters of the qml object called YARPVideoSurface QObject *yarpVideoSurface = topLevel->findChild<QObject*>("YARPVideoSurface"); QMetaObject::invokeMethod(yarpVideoSurface,"parseParameters", Qt::DirectConnection, Q_RETURN_ARG(QVariant, retVal), Q_ARG(QVariant,params)); if(!retVal.toBool()){ return 0; } window->show(); window->setIcon(QIcon(":/logo.png")); // window->setIcon(QIcon(":/logo.svg")); return app.exec(); }
int main(int argc, char *argv[]) { //It cannot properly fall back to Qt Widgets versions of the dialogs if // we use a QGuiApplication, which only supports QML stuff. //QGuiApplication app(argc, argv); QApplication app(argc, argv); //This is for the QSettings defaults from things like the qt file dialog and stuff... app.setApplicationName("Filmulator"); app.setOrganizationName("Filmulator"); QFont sansFont("Sans Serif",9); app.setFont(sansFont); QQmlApplicationEngine engine; QTranslator translator; translator.load("filmulatortr_la"); app.installTranslator(&translator); //Prepare database connection. //This should create a new db file if there was none. QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); setupDB(&db); //Create the object for communicating between SQL classes. SignalSwitchboard *switchboard = new SignalSwitchboard; //Create a settings object for persistent settings. Settings *settingsObj = new Settings; engine.rootContext()->setContextProperty("settings", settingsObj); //Prepare an object for managing the processing parameters. ParameterManager *paramManager = new ParameterManager; engine.rootContext()->setContextProperty("paramManager",paramManager); QObject::connect(paramManager, SIGNAL(updateTableOut(QString, int)), switchboard, SLOT(updateTableIn(QString, int))); //Prepare an image provider object. FilmImageProvider *filmProvider = new FilmImageProvider(paramManager); //Connect it as an image provider so that qml can get the photos engine.addImageProvider(QLatin1String("filmy"), filmProvider); //Connect it as a Q_OBJECT so that qml can run methods engine.rootContext()->setContextProperty("filmProvider",filmProvider); qRegisterMetaType<QFileInfo>(); //Prepare a model for importing. ImportModel *importModel = new ImportModel; engine.rootContext()->setContextProperty("importModel", importModel); //Prepare a model for the organize view. OrganizeModel *organizeModel = new OrganizeModel; engine.rootContext()->setContextProperty("organizeModel", organizeModel); engine.rootContext()->setContextProperty("dateHistoModel", organizeModel->dateHistogram); QObject::connect(switchboard, SIGNAL(updateTableOut(QString,int)), organizeModel, SLOT(updateTable(QString,int))); QObject::connect(organizeModel, SIGNAL(updateTableOut(QString,int)), switchboard, SLOT(updateTableIn(QString,int))); //Prepare a model for the queue view. QueueModel *queueModel = new QueueModel; queueModel->setQueueQuery(); QObject::connect(switchboard, SIGNAL(updateTableOut(QString, int)), queueModel, SLOT(updateTable(QString, int))); QObject::connect(importModel, SIGNAL(enqueueThis(QString)), queueModel, SLOT(enQueue(QString))); engine.rootContext()->setContextProperty("queueModel", queueModel); if (QFile("qml/filmulator-gui/main.qml").exists()) { cout << "loading UI from copy in directory" << endl; engine.load(QUrl::fromLocalFile("qml/filmulator-gui/main.qml")); } else if (QFile("/usr/lib/filmulator-gui/qml/filmulator-gui/main.qml").exists()) { cout << "loading UI from /usr/lib/" << endl; engine.load(QUrl::fromLocalFile("/usr/lib/filmulator-gui/qml/filmulator-gui/main.qml")); } else { qWarning("QML UI file missing"); return -1; } QObject *topLevel = engine.rootObjects().value(0); QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel); if (!window) { qWarning("Error: your root item has to be a Window"); return -1; } window->setIcon(QIcon(":/icons/filmulator64icon.svg")); window->show(); return app.exec(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); const QString app_name("timecop"); const QString app_version("1.1"); const QString app_settings_dir(QDir::home().filePath(".timecop")); app.setOrganizationName("Daimler AG RD-DDA"); app.setApplicationName(app_name); QSettings::setDefaultFormat(QSettings::IniFormat); QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, app_settings_dir); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QObject *root = 0; QWidget *rootWindow = 0; SystrayHelper systrayHelper; engine.rootContext()->setContextProperty("systrayHelper", &systrayHelper); engine.rootContext()->setContextProperty("app_name", app_name); engine.rootContext()->setContextProperty("app_version", app_version); engine.rootContext()->setContextProperty("app_settings_dir", app_settings_dir); if (engine.rootObjects().size() > 0) { root = engine.rootObjects().at(0); systrayHelper.setRootWindow(root); if(root->isWindowType()){ rootWindow = qobject_cast<QWidget*>(root); QApplication::setQuitOnLastWindowClosed(false); QAction *minimizeAction = new QAction(QObject::tr("Mi&nimize"), rootWindow); rootWindow->connect(minimizeAction, SIGNAL(triggered()), root, SLOT(hide())); QAction *maximizeAction = new QAction(QObject::tr("Ma&ximize"), rootWindow); rootWindow->connect(maximizeAction, SIGNAL(triggered()), root, SLOT(showMaximized())); QAction *restoreAction = new QAction(QObject::tr("&Restore"), rootWindow); rootWindow->connect(restoreAction, SIGNAL(triggered()), root, SLOT(showNormal())); QAction *quitAction = new QAction(QObject::tr("&Quit"), rootWindow); rootWindow->connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); QMenu *trayIconMenu = new QMenu(rootWindow); trayIconMenu->addAction(minimizeAction); trayIconMenu->addAction(maximizeAction); trayIconMenu->addAction(restoreAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); QSystemTrayIcon *trayIcon = new QSystemTrayIcon(rootWindow); QIcon icon(":/trayicon.png"); icon.setIsMask(true); //trayIcon->setContextMenu(trayIconMenu); trayIcon->setIcon(icon); trayIcon->setToolTip("Click to open"); trayIcon->setVisible(true); systrayHelper.setTrayIcon(trayIcon); QObject::connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), &systrayHelper, SLOT(activatedSystray(QSystemTrayIcon::ActivationReason))); trayIcon->show(); } } 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(); }
int main(int argc, char *argv[]) { qDebug() << "Initializing application"; QGuiApplication app(argc, argv); QCoreApplication::setApplicationName(kApplicationName); QCoreApplication::setApplicationVersion(kApplicationVersion); QCoreApplication::setOrganizationName(kOrganizationName); #ifdef Q_OS_MAC QCoreApplication::setOrganizationDomain(kOrganizationName); #else QCoreApplication::setOrganizationDomain(kOrganizationDomain); #endif QSettings::setDefaultFormat(kSettingsFormat); #ifdef Q_OS_WIN // Force usage of OpenGL ES through ANGLE on Windows QCoreApplication::setAttribute(Qt::AA_UseOpenGLES); #endif // Initialize license #ifdef kLicense QCoreApplication::instance()->setProperty("Esri.ArcGISRuntime.license", kLicense); #endif // Intialize application window QQmlApplicationEngine appEngine; appEngine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH); QString arcGISToolkitImportPath = QUOTE(ARCGIS_TOOLKIT_IMPORT_PATH); #if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive); arcGISToolkitImportPath = arcGISToolkitImportPath.replace(replaceString, "linux", Qt::CaseSensitive); #endif // Add the Runtime and Extras path appEngine.addImportPath(arcGISRuntimeImportPath); // Add the Toolkit path appEngine.addImportPath(arcGISToolkitImportPath); appEngine.load(QUrl(kApplicationSourceUrl)); auto topLevelObject = appEngine.rootObjects().value(0); qDebug() << Q_FUNC_INFO << topLevelObject; auto window = qobject_cast<QQuickWindow *>(topLevelObject); if (!window) { qCritical("Error: Your root item has to be a Window."); return -1; } #if !defined(Q_OS_IOS) && !defined(Q_OS_ANDROID) // Process command line QCommandLineOption showOption(kArgShowName, kArgShowDescription, kArgShowValueName, kArgShowDefault); QCommandLineParser commandLineParser; commandLineParser.setApplicationDescription(kApplicationDescription); commandLineParser.addOption(showOption); commandLineParser.addHelpOption(); commandLineParser.addVersionOption(); commandLineParser.process(app); // Show app window auto showValue = commandLineParser.value(kArgShowName).toLower(); if (showValue.compare(kShowMaximized) == 0) { window->showMaximized(); } else if (showValue.compare(kShowMinimized) == 0) { window->showMinimized(); } else if (showValue.compare(kShowFullScreen) == 0) { window->showFullScreen(); } else if (showValue.compare(kShowNormal) == 0) { window->showNormal(); } else { window->show(); } #else window->show(); #endif return app.exec(); }
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(); }
/* TODO: Fix the append bug Fix segmentation fault in FileHeaderData Finish and polish graphic interface */ int main(int argc, char *argv[]) { QGuiApplication app(argc,argv); QGuiApplication::setApplicationName("huffman"); QCommandLineParser cliParser; cliParser.setApplicationDescription( QStringLiteral("huffman") ); cliParser.addHelpOption(); cliParser.addPositionalArgument("<file>", QCoreApplication::translate("main","Source file to compress.") ); cliParser.addPositionalArgument("<path>", QCoreApplication::translate("main","Destination for output file.") ); QCommandLineOption compress("c",QCoreApplication::translate("main", "huffman -c <file>. Compresses <file> and saves as <file>.huff.") ); QCommandLineOption compressOutput("o",QCoreApplication::translate("main", "huffman -c <file> -o <name>. Compresses <file> and saves as <name>.")); QCommandLineOption decompressAtPath("d",QCoreApplication::translate("main", "huffman <file> -d <path>. Decompresses <file> and saves at <path>.")); QCommandLineOption goGui("gui",QCoreApplication::translate("main", "huffman --gui. Runs huffman in gui mode.")); QCommandLineOption dbg("dbg",QCoreApplication::translate("main", "huffman --dbg. Debug.")); cliParser.addOption(compress); cliParser.addOption(compressOutput); cliParser.addOption(decompressAtPath); cliParser.addOption(goGui); cliParser.addOption(dbg); cliParser.process(app); bool ccompress = cliParser.isSet(compress), showGui = cliParser.isSet(goGui), ocompress = cliParser.isSet(compressOutput), ddecompress = cliParser.isSet(decompressAtPath); if ( cliParser.isSet (dbg) ) { QFile file( cliParser.positionalArguments ().at(0) ); if ( file.open (QIODevice::ReadOnly) ) { FileHeaderData h; h.readFromFile (file); qDebug() << ( h.getStatus () == HeaderStatus::READY ? "Ok!" : "Not Ok." ); file.close (); } return 0; } if ( showGui ) {// [GUI] // QGuiApplication guiapp(argc,argv); QQmlApplicationEngine engine; FileUtils fileUtils; engine.rootContext ()->setContextProperty ("FileUtils",&fileUtils); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec (); } if ( ccompress ) { if( ocompress ) { //Compress to path or file if ( cliParser.positionalArguments().count() == 2) { QString file = cliParser.positionalArguments().at(0); QString filename = cliParser.positionalArguments().at(1); Compress cfile; cfile.compressFile (file,filename); } else { qDebug() << "Invalid use. Check -h for help."; } } else { // Compress file and save as filename QString file = cliParser.positionalArguments().at(0); Compress cfile; QString gambiarra; cfile.compressFile (file,gambiarra); } // c compress is not set, so we decompress } else { //if -d is set, decompress to "thing" if ( ddecompress ) { if ( cliParser.positionalArguments().count() == 2) { QString file = cliParser.positionalArguments().at(0); QString path = cliParser.positionalArguments().at(1); QDir test(path); if ( test.exists () ) { Decompress srcfile; srcfile.decompressFile (file,path); } else { qDebug() << test.absolutePath () << "\n doesn't exists"; } } else { qDebug() << "Invalid use. Check -h for help."; } // -d is not set, decompress to current path } else { if ( cliParser.positionalArguments().count() == 1 ) { QString file = cliParser.positionalArguments().at(0); Decompress srcfile; srcfile.decompressFile (file); } else { qDebug () << "Invalid use. huffman -h for help."; } } } return 0; }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); app.setOrganizationName("ITI"); app.setOrganizationDomain("myaircoach.eu"); app.setApplicationName("myAirCoach"); //--------- //QTranslator qtTranslator; // qtTranslator.load("myAirCoach_" + QLocale::system().name(), ":/"); //app.installTranslator(&qtTranslator); //--------- qmlRegisterType<MyAdmob>("myadmob", 1, 0, "MyAdmob"); qmlRegisterType<MyDevice>("mydevice", 1, 0, "MyDevice"); qmlRegisterType<QMLObjectStore>("QMLObjectStore", 1, 0, "QMLObjectStore"); qmlRegisterType<WaterfallItem>("hu.timur", 1, 0, "Waterfall"); qmlRegisterType<Graph>("Graph", 1, 0, "Graph"); //QQmlApplicationEngine engine; qmlRegisterType<WeatherData>("WeatherInfo", 1, 0, "WeatherData"); qmlRegisterType<AppModel>("WeatherInfo", 1, 0, "AppModel"); qmlRegisterType<AudioRecorder>("AudioRecorder", 1, 0, "AudioRecorder"); qmlRegisterType<FPSText>("FPSText", 1, 0, "FPSText"); //! [0] qRegisterMetaType<WeatherData>(); //AudioRecorder recorder; QQmlApplicationEngine* engine = new QQmlApplicationEngine(); //engine->rootContext()->setContextProperty("recorder", &recorder); engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); //main1 QQmlContext * rootContext = engine->rootContext(); /*const QStringList & musicPaths = QStandardPaths::standardLocations(QStandardPaths::MusicLocation); const QUrl musicUrl = QUrl::fromLocalFile(musicPaths.isEmpty() ? QDir::homePath() : musicPaths.first()); rootContext->setContextProperty(QStringLiteral("musicUrl"), musicUrl); const QStringList arguments = QCoreApplication::arguments(); const QUrl commandLineUrl = arguments.size() > 1 ? QUrl::fromLocalFile(arguments.at(1)) : QUrl(); rootContext->setContextProperty(QStringLiteral("url"), commandLineUrl); */ // NotificationClient *notificationClient; // rootContext->setContextProperty(QLatin1String("notificationClient"), // notificationClient); //view.setResizeMode(QQuickView::SizeRootObjectToView); QObject * root = engine->rootObjects().first(); #ifdef Q_OS_ANDROID QString hash = QString("myAirCoach"); QString dirStorageString = QString("/sdcard/Android/data/com.qtproject.qtangled/"); QDir dir; if( dir.mkpath(dirStorageString) ) { engine->setOfflineStoragePath( dirStorageString ); engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); QString dbFileString = dirStorageString + hash + QString(".sqlite"); QFile dbFile(dbFileString); if (dbFile.exists()) { QFile::setPermissions(dbFileString, QFile::WriteOwner | QFile::ReadOwner); } QFile iniFile( dir.path() + hash + QString(".ini") ); iniFile.open( QIODevice::WriteOnly ); iniFile.write( "[General]\nDescription=Catalog\nDriver=QSQLITE\nName=Catalog\nVersion=1.0" ); iniFile.close(); } else { #endif //engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); //sos prosoxh velos h teleia #ifdef Q_OS_ANDROID } #endif return app.exec(); }