Ejemplo n.º 1
1
QQmlComponent_ *newComponent(QQmlEngine_ *engine, QObject_ *parent)
{
    QQmlEngine *qengine = reinterpret_cast<QQmlEngine *>(engine);
    //QObject *qparent = reinterpret_cast<QObject *>(parent);
    QQmlComponent *qcomponent = new QQmlComponent(qengine);
    // Qt 5.2.0 returns NULL on qmlEngine(qcomponent) without this.
    QQmlEngine::setContextForObject(qcomponent, qengine->rootContext());
    return qcomponent;
}
Ejemplo n.º 2
0
//==============================================================================
// Init
//==============================================================================
void ViewerWindow::init()
{
    qDebug() << "ViewerWindow::init";

    // Set Read Only Mode
    ui->textEdit->setReadOnly(!editMode);

    // Connect Signal
    connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(textChanged()));

    // Quick Widget Set Visible
    ui->quickWidget->setVisible(true);
    // Text Edit Set Visible
    ui->textEdit->setVisible(false);

    // Set Context Properties
    QQmlContext* ctx = ui->quickWidget->rootContext();
    // Set Context Properties - Viewer Content
    ctx->setContextProperty(DEFAULT_IMAGE_VIEWER_CONTENT, fileName);

    // Get Engine
    QQmlEngine* engine = ui->quickWidget->engine();
    // Add Image Provider
    engine->addImageProvider(QLatin1String(DEFAULT_AUDIO_TAG_PROVIDER_ID), new AudioTagImageProvider());

    // Set Resize Mode
    ui->quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);

    // Set Focus Policy
    setFocusPolicy(Qt::StrongFocus);

    // ...
}
Ejemplo n.º 3
0
void Editor::init()
{
    if(m_initialized){
        return;
    }
    Engine* engine = Engine::getInstance();
    QQmlEngine* qmlEngine = engine->getQmlEngine();

    QQmlContext* context = qmlEngine->rootContext();
    context->setContextProperty("editor",this);

    editorUiComponent = new QQmlComponent(qmlEngine,Util::getUrlPathToAsset("qml/editor/EditorUi.qml"));

    for(QQmlError error :editorUiComponent->errors()){
        qDebug() << "Error on Line" << error.line() << ":" << error.description();
    }

    if(editorUiComponent->isReady()){
        initUi();
    }else {
        connect(editorUiComponent,SIGNAL(statusChanged(QQmlComponent::Status)),
                this,SLOT(onLoadingUiChanged(QQmlComponent::Status)));
    }

    m_initialized = true;
}
Ejemplo n.º 4
0
void engineAddImageProvider(QQmlEngine_ *engine, QString_ *providerId, void *imageFunc)
{
    QQmlEngine *qengine = reinterpret_cast<QQmlEngine *>(engine);
    QString *qproviderId = reinterpret_cast<QString *>(providerId);

    qengine->addImageProvider(*qproviderId, new GoImageProvider(imageFunc));
}
Ejemplo n.º 5
0
void engineSetContextForObject(QQmlEngine_ *engine, QObject_ *object)
{
    QQmlEngine *qengine = reinterpret_cast<QQmlEngine *>(engine);
    QObject *qobject = reinterpret_cast<QObject *>(object);

    QQmlEngine::setContextForObject(qobject, qengine->rootContext());
}
Ejemplo n.º 6
0
QQuickItem *GlobalFunctions::itemAt(QQuickItem* parent, int x, int y, QJSValue matcher)
{
    if (!parent) return nullptr;
    QList<QQuickItem *> children = QQuickItemPrivate::get(parent)->paintOrderChildItems();

    for (int i = children.count() - 1; i >= 0; --i) {
        QQuickItem *child = children.at(i);

        // Map coordinates to the child element's coordinate space
        QPointF point = parent->mapToItem(child, QPointF(x, y));
        if (child->isVisible() && point.x() >= 0
                && child->width() >= point.x()
                && point.y() >= 0
                && child->height() >= point.y()) {
            if (!matcher.isCallable()) return child;

            QQmlEngine* engine = qmlEngine(child);
            if (!engine) return child;

            QJSValue newObj = engine->newQObject(child);
            if (matcher.call(QJSValueList() << newObj).toBool()) {
                return child;
            }
        }
    }
    return nullptr;
}
Ejemplo n.º 7
0
void TestSimpleQmlLoad::compileAndLoadSignal2()
{
    const QString TEST_FILE(":/testqml/testsignal2.qml");

    QQmlEngine *engine = new QQmlEngine;
    QQmlComponent* component = compileAndLoad(engine, TEST_FILE);
    QVERIFY(component);

    SignalTester st;

    engine->rootContext()->setContextProperty("st", &st);

    QObject *myObject = component->create();
    QVERIFY(myObject != NULL);

    QVariant var = myObject->property("sigReceived");
    QVERIFY(!var.isNull());
    QVERIFY(var.toBool() == false);

    st.sendSig();
    var = myObject->property("sigReceived");
    QVERIFY(!var.isNull());
    QVERIFY(var.toBool() == true);

    delete component;
    delete engine;
}
Ejemplo n.º 8
0
int main(int argc, char ** argv)
{
	QApplication app(argc, argv);

	qmlRegisterType<Hider>("com.ics.demo", 1, 0, "Hider");

	int rc = 0;

	QQmlEngine engine;
	QQmlComponent *component = new QQmlComponent(&engine);

	QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));

    component->loadUrl(QUrl("../../Source/main.qml"));

	Hider::image_provider = new ImageProvider;
	engine.addImageProvider("images", Hider::image_provider);

	if (!component->isReady() ) {
		qWarning("%s", qPrintable(component->errorString()));
		return -1;
	}

	QObject *topLevel = component->create();
	QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);

	QSurfaceFormat surfaceFormat = window->requestedFormat();
	window->setFormat(surfaceFormat);
	window->show();

	rc = app.exec();

	delete component;
	return rc;
}
// QTBUG-21310 - crash test
void tst_qqmlexpression::syntaxError()
{
    QQmlEngine engine;
    QQmlExpression expression(engine.rootContext(), 0, "asd asd");
    QVariant v = expression.evaluate();
    QCOMPARE(v, QVariant());
}
Ejemplo n.º 10
0
void WelcomeMode::addPages(const QList<IWelcomePage *> &pages)
{
    QList<IWelcomePage *> addedPages = pages;
    Utils::sort(addedPages, [](const IWelcomePage *l, const IWelcomePage *r) {
        return l->priority() < r->priority();
    });
    // insert into m_pluginList, keeping m_pluginList sorted by priority
    QQmlEngine *engine = m_welcomePage->engine();
    auto addIt = addedPages.begin();
    auto currentIt = m_pluginList.begin();
    while (addIt != addedPages.end()) {
        IWelcomePage *page = *addIt;
        QTC_ASSERT(!m_idPageMap.contains(page->id()), ++addIt; continue);
        while (currentIt != m_pluginList.end() && (*currentIt)->priority() <= page->priority())
            ++currentIt;
        // currentIt is now either end() or a page with higher value
        currentIt = m_pluginList.insert(currentIt, page);
        m_idPageMap.insert(page->id(), page);
        page->facilitateQml(engine);
        ++currentIt;
        ++addIt;
    }
    // update model through reset
    QQmlContext *ctx = engine->rootContext();
    ctx->setContextProperty(QLatin1String("pagesModel"), QVariant::fromValue(
                                Utils::transform(m_pluginList, // transform into QList<QObject *>
                                                 [](IWelcomePage *page) -> QObject * {
                                    return page;
                                })));
}
Ejemplo n.º 11
0
void tst_QQmlPropertyMap::changed()
{
    QQmlPropertyMap map;
    QSignalSpy spy(&map, SIGNAL(valueChanged(const QString&, const QVariant&)));
    map.insert(QLatin1String("key1"),100);
    map.insert(QLatin1String("key2"),200);
    QCOMPARE(spy.count(), 0);

    map.clear(QLatin1String("key1"));
    QCOMPARE(spy.count(), 0);

    //make changes in QML
    QQmlEngine engine;
    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty(QLatin1String("testdata"), &map);
    QQmlComponent component(&engine);
    component.setData("import QtQuick 2.0\nText { text: { testdata.key1 = 'Hello World'; 'X' } }",
            QUrl::fromLocalFile(""));
    QVERIFY(component.isReady());
    QQuickText *txt = qobject_cast<QQuickText*>(component.create());
    QVERIFY(txt);
    QCOMPARE(txt->text(), QString('X'));
    QCOMPARE(spy.count(), 1);
    QList<QVariant> arguments = spy.takeFirst();
    QCOMPARE(arguments.count(), 2);
    QCOMPARE(arguments.at(0).toString(),QLatin1String("key1"));
    QCOMPARE(arguments.at(1).value<QVariant>(),QVariant("Hello World"));
    QCOMPARE(map.value(QLatin1String("key1")), QVariant("Hello World"));
}
Ejemplo n.º 12
0
void tst_QQmlPropertyMap::controlledWrite()
{
    MyPropertyMap map;
    QCOMPARE(map.isEmpty(), true);

    //make changes in QML
    QQmlEngine engine;
    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty(QLatin1String("testdata"), &map);

    const char *qmlSource =
        "import QtQuick 2.0\n"
        "Item { Component.onCompleted: { testdata.key1 = 'Hello World'; testdata.key2 = 'Goodbye' } }";

    QQmlComponent component(&engine);
    component.setData(qmlSource, QUrl::fromLocalFile(""));
    QVERIFY(component.isReady());

    QObject *obj = component.create();
    QVERIFY(obj);
    delete obj;

    QCOMPARE(map.value(QLatin1String("key1")), QVariant("HELLO WORLD"));
    QCOMPARE(map.value(QLatin1String("key2")), QVariant("Goodbye"));
}
Ejemplo n.º 13
0
void TestSimpleQmlLoad::loadSignal3()
{
    QQmlEngine *engine = new QQmlEngine;
    const QString TEST_FILE(":/testqml/testsignal3.qml");
    QQmlComponent* component = load(engine, TEST_FILE);
    QVERIFY(component);

    SignalTester st;

    engine->rootContext()->setContextProperty("st", &st);

    QObject *myObject = component->create();
    QVERIFY(myObject != NULL);

    st.sendSig();

    QVariant ret;
    QMetaObject::invokeMethod(myObject, "getSubWidth1", Q_RETURN_ARG(QVariant, ret));
    QVERIFY(ret.toInt() == 10);

    st.sendSig();

    QMetaObject::invokeMethod(myObject, "getSubWidth1", Q_RETURN_ARG(QVariant, ret));
    QVERIFY(ret.toInt() == 20);

    delete component;
    delete engine;
}
Ejemplo n.º 14
0
void tst_qqmlengine::offlineStoragePath()
{
    // Without these set, QDesktopServices::storageLocation returns
    // strings with extra "//" at the end. We set them to ignore this problem.
    qApp->setApplicationName("tst_qqmlengine");
    qApp->setOrganizationName("QtProject");
    qApp->setOrganizationDomain("www.qt-project.org");

    QQmlEngine engine;

    QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation);

    QCOMPARE(dataLocation.isEmpty(), engine.offlineStoragePath().isEmpty());

    QDir dir(dataLocation);
    dir.mkpath("QML");
    dir.cd("QML");
    dir.mkpath("OfflineStorage");
    dir.cd("OfflineStorage");

    QCOMPARE(QDir::fromNativeSeparators(engine.offlineStoragePath()), dir.path());

    engine.setOfflineStoragePath(QDir::homePath());
    QCOMPARE(engine.offlineStoragePath(), QDir::homePath());
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlEngine engine;
    QMLBattleStationContext* context = new QMLBattleStationContext();
    engine.rootContext()->setContextProperty(QString("context"), context);
    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));
    component.create();
    //  Init/create subsystems
    if (SDL_Init(SDL_INIT_JOYSTICK)) {
        QString* err = new QString(SDL_GetError());
        qWarning() << LOG_ERROR << "SDL init error:" << err;
        //  TODO UI notification
    } else {
        qDebug() << LOG_OK << "SDL init";
    }
    Serial* serial = new Serial();
    InputHandler* inputHandler = new InputHandler();

    //  Connect Serial and BSC
    QObject::connect(context, SIGNAL(SelectedSerialDeviceChanged(QString)),
                     serial, SLOT(SetActiveSerialDevice(QString)));
    //  Connect Input and BSC
    QObject::connect(context, SIGNAL(SelectedJoystickAChanged(QString)),
                     inputHandler, SLOT(SetMainJoystick(QString*)));
    //  Connect Input to Serial
    QObject::connect(inputHandler, SIGNAL(MotorValuesChanged(quint8[])),
                     serial, SLOT(SetMotorValues(quint8[])));
    QObject::connect(inputHandler, SIGNAL(PostToolUpdate(quint16,quint16)),
                     serial, SLOT(EnqueueToolEvent(quint16,quint16)));


    return app.exec();
}
Ejemplo n.º 16
0
void engineSetOwnershipJS(QQmlEngine_ *engine, QObject_ *object)
{
    QQmlEngine *qengine = reinterpret_cast<QQmlEngine *>(engine);
    QObject *qobject = reinterpret_cast<QObject *>(object);

    qengine->setObjectOwnership(qobject, QQmlEngine::JavaScriptOwnership);
}
Ejemplo n.º 17
0
int main(int argc, char **argv)
{
  QApplication app(argc, argv);

  const QUrl documentUrl = QUrl("qrc:///main.qml");

  QQmlEngine engine;
#ifdef Q_OS_MACOS
  engine.addImportPath(QStringLiteral("%1/../PlugIns").arg(QCoreApplication::applicationDirPath()));
#else
  engine.addImportPath(PLUGIN_IMPORT_PATH);
#endif
  Editor editor;
  engine.rootContext()->setContextProperty("_editor", &editor);
  QObject::connect(&engine, &QQmlEngine::quit, QCoreApplication::instance(), &QCoreApplication::quit);

  QQmlComponent component(&engine, documentUrl);
  QWidget *widget = qobject_cast<QWidget*>(component.create());
  if (!widget)
    qFatal("Failed to create widget from QML");
    
  widget->show();

  return app.exec();
}
Ejemplo n.º 18
0
void tst_qqmlexpression::exception()
{
    QQmlEngine engine;
    QQmlExpression expression(engine.rootContext(), 0, "abc=123");
    QVariant v = expression.evaluate();
    QCOMPARE(v, QVariant());
    QVERIFY(expression.hasError());
}
Ejemplo n.º 19
0
void MainView::newPacket() {
    QQmlEngine *engine = new QQmlEngine;
    QQmlComponent component(engine);
    engine->rootContext()->setContextProperty("__packet__", new EthernetDisplay());
    component.loadUrl(QUrl(QStringLiteral("qrc:/views/ethernet.qml")));
    if (component.isReady())
        component.create();
}
Ejemplo n.º 20
0
void tst_qqmlengine::rootContext()
{
    QQmlEngine engine;

    QVERIFY(engine.rootContext());

    QCOMPARE(engine.rootContext()->engine(), &engine);
    QVERIFY(!engine.rootContext()->parentContext());
}
Ejemplo n.º 21
0
void tst_qqmlengine::synchronousNetworkAccessManager()
{
    ImmediateFactory factory;
    QQmlEngine engine;
    engine.setNetworkAccessManagerFactory(&factory);
    QQmlComponent c(&engine, QUrl("myScheme://test.qml"));
    // reply is finished, so should not be in loading state.
    QVERIFY(!c.isLoading());
}
Ejemplo n.º 22
0
int main(int argc, char* argv[])
{
	QGuiApplication app(argc, argv);

	// Use QCommandLineParser to parse arguments (see documentation)

	QQmlEngine engine;

	// Register needed types
	registerQmlTypes();

	// Add image provider
	engine.addImageProvider(QStringLiteral("svgelement"), new qtouch::SvgElementProvider(QQmlImageProviderBase::Image,
	                        QUrl(QStringLiteral("qrc:///images/"))));

	qtouch::DataModel dataModel;
	try
	{
		dataModel.init();
	}
	catch (qtouch::Exception& e)
	{
		qCritical() << e.message();
		return EXIT_FAILURE;
	}

	qtouch::CourseModel* courseModel = new qtouch::CourseModel(&dataModel, &app);
	qtouch::ProfileModel* profileModel = new qtouch::ProfileModel(&dataModel, &app);
	// Embed view models
	engine.rootContext()->setContextProperty("$courseModel", courseModel);
	engine.rootContext()->setContextProperty("$profileModel", profileModel);

	// Create root component
	QQmlComponent component(&engine);
	QQuickWindow::setDefaultAlphaBuffer(true);
	component.loadUrl(QUrl(QStringLiteral("qrc:/qml/MainWindow.qml")));

	if (componentError(&component))
		return EXIT_FAILURE;

	if (component.isReady())
	{
		component.create();
		if (componentError(&component))
			return EXIT_FAILURE;
	}
	else
	{
		qWarning() << component.errorString();
		return EXIT_FAILURE;
	}

	// FIXME: Not nice but fixes initialization problem
	courseModel->selectCourse(0);

	return app.exec();
}
Ejemplo n.º 23
0
void QQmlVMEMetaObject::allocateVarPropertiesArray()
{
    QQmlEngine *qml = qmlEngine(object);
    assert(qml);
    QV4::ExecutionEngine *v4 = QV8Engine::getV4(qml->handle());
    QV4::Scope scope(v4);
    varProperties = QV4::ScopedValue(scope, v4->newArrayObject(metaData->varPropertyCount));
    varPropertiesInitialized = true;
}
Ejemplo n.º 24
0
void Reloader::reload()
{
    qDebug() << "reloading";
    //The engines has a internal cache that prevents reloading.
    QQmlEngine *engine = m_viewer->engine();
    engine->trimComponentCache();
    engine->clearComponentCache();
    m_viewer->setSource(m_mainFile);
}
Ejemplo n.º 25
0
Archivo: main.cpp Proyecto: xjohncz/qt5
    int callerLine(int frameIndex = 0) const
    {
        QQmlEngine *engine = qmlEngine(this);
        QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle());

        QVector<QV4::StackFrame> stack = v4->stackTrace(frameIndex + 2);
        if (stack.size() > frameIndex + 1)
            return stack.at(frameIndex + 1).line;
        return -1;
    }
Ejemplo n.º 26
0
MainWindow::MainWindow(QWindow *parent)
    : QQuickView(parent)
{
    setSource(QUrl::fromLocalFile("H:/VK/main.qml").toString());

    photoSize = "130";


    // !!! SET QNAM AND CACHE
    manager = new QNetworkAccessManager(this);
    cache = new QNetworkDiskCache(this);
    // 500 Mb
    cache->setMaximumCacheSize(500*1024*1024);
    cache->setCacheDirectory("cacheDir");
    manager->setCache(cache);

    // SET CACHED NAM TO QMLENGINE TO
    MyNetworkAccessManagerFactory* namFactory = new MyNetworkAccessManagerFactory();
    QQmlEngine* eng =  engine();
    eng->setNetworkAccessManagerFactory(namFactory);


    QQmlProperty((QObject*)rootObject(), "color").write("#F5F5F5");
    QQmlProperty((QObject*)rootObject(), "height").write(height());


    wallObj = rootObject();
    //wallObj->setProperty("color", "#F5F5F5");
    //wallObj->setProperty("height",height());

    connect((QObject*)wallObj, SIGNAL(login()),this,SLOT(login()));
    connect((QObject*)wallObj, SIGNAL(getGroups()),this, SLOT(getGroups()));
    connect((QObject*)wallObj, SIGNAL(getWall(QString)),this, SLOT(getWall(QString)));
    connect((QObject*)wallObj, SIGNAL(morePosts()), this, SLOT(morePosts()));
    connect((QObject*)wallObj, SIGNAL(setPhotoSize(QString)), this, SLOT(setPhotoSize(QString)));


    LoadIni("H:/VK/config.ini");
    // do we have token
    if( settings->contains("token")){
        // its a unlimit token
        qDebug() << " HAVE TOKEN ";
        if(ReadConfig("expires").toInt()==0){
            Token = ReadConfig("token").toString();
        }
        // if no doesnt it token expire
        else if(ReadConfig("expDate").toDate()<=QDate::currentDate()){
            Token = ReadConfig("token").toString();
        }
    // if havent token login
    }else{
        login();
        qDebug() << " NEED LOGIN ";
    }
}
Ejemplo n.º 27
0
Archivo: main.cpp Proyecto: xjohncz/qt5
    QQmlV4Handle callerFile(int frameIndex = 0) const
    {
        QQmlEngine *engine = qmlEngine(this);
        QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle());
        QV4::Scope scope(v4);

        QVector<QV4::StackFrame> stack = v4->stackTrace(frameIndex + 2);
        if (stack.size() > frameIndex + 1) {
            QV4::ScopedValue s(scope, v4->newString(stack.at(frameIndex + 1).source));
            return QQmlV4Handle(s);
        }
        return QQmlV4Handle();
    }
Ejemplo n.º 28
0
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags) :
	QMainWindow(parent, flags), IPersistentSettings(this)
{
	qfLogFuncFrame();
	Q_ASSERT(self == nullptr);
	self = this;

	m_pluginLoader = nullptr;

	Application *app = Application::instance();
	app->m_frameWork = this;
	QQmlEngine *qe = app->qmlEngine();
	qe->rootContext()->setContextProperty("FrameWork", this);
}
void QuickAndroidTests::loading()
{
    QStringList res;
    QQueue<QString> queue;
    queue.enqueue(":/QuickAndroid");

    QQmlEngine engine;
    engine.addImportPath("qrc:///");

    while (queue.size()) {
        QString path = queue.dequeue();
        QDir dir(path);
        QFileInfoList infos = dir.entryInfoList(QStringList());
        for (int i = 0 ; i < infos.size();i++) {
            QFileInfo info = infos.at(i);
            if (info.fileName() == "." || info.fileName() == "..")
                continue;
            if (info.isDir()) {
                queue.enqueue(info.absoluteFilePath());
                continue;
            }
            QUrl url = info.absoluteFilePath().remove(0,1);
            url.setScheme("qrc");

            if (info.suffix() != "qml") {
                continue;
            }

            QFile file(":" + url.path());
            QVERIFY(file.open(QIODevice::ReadOnly));
            QString content = file.readAll();
            content = content.toLower();

            // Skip singleton module as it can not be loaded directly
            if (content.indexOf("pragma singleton") != -1) {
                qDebug() << QString("%1 : Skipped (singleton)").arg(url.toString());
                continue;
            }

            QQmlComponent comp(&engine);
            comp.loadUrl(url);
            if (comp.isError()) {
                qDebug() << QString("%1 : Load Failed. Reason :  %2").arg(info.absoluteFilePath()).arg(comp.errorString());
            }
            QVERIFY(!comp.isError());

            qDebug() << QString("%1 : Passed").arg(info.absoluteFilePath());
        }
    }
}
Ejemplo n.º 30
0
void tst_qrcqml::qrcImport()
{
    QFETCH(QString, importPath);
    QFETCH(QString, token);

    QQmlEngine e;
    e.addImportPath(importPath);
    QQmlComponent c(&e, QUrl("qrc:///importtest.qml"));
    QVERIFY(c.isReady());
    QObject *o = c.create();
    QVERIFY(o);
    QCOMPARE(o->property("tokenProperty").toString(), token);
    delete o;
}