Loading multiple images on a page for Blackberry 10 - qt

I am working on BB10 cascades. I am trying to load multiple images from network. I have referred following example and I have modified it to load a single image. Sample code is as follows:
main.qml
import bb.cascades 1.2
Page {
Container {
id: outer
Container {
preferredHeight: 500
preferredWidth: 768
layout: DockLayout {}
onCreationCompleted: {}
// The ActivityIndicator that is only active and visible while the image is loading
ActivityIndicator {
id: activity
horizontalAlignment: HorizontalAlignment.Center
verticalAlignment: VerticalAlignment.Center
preferredHeight: 300
visible: _loader.loading
running: _loader.loading
}
// The ImageView that shows the loaded image after loading has finished without error
ImageView {
id: image
horizontalAlignment: HorizontalAlignment.Fill
verticalAlignment: VerticalAlignment.Fill
image: _loader.image
visible: !_loader.loading && _loader.label == ""
}
// The Label that shows a possible error message after loading has finished
Label {
id: lable
horizontalAlignment: HorizontalAlignment.Center
verticalAlignment: VerticalAlignment.Center
preferredWidth: 500
visible: !_loader.loading && !_loader.label == ""
text: _loader.label
multiline: true
}
}
Button {
text: "load Image"
onClicked: {
_loader.load();
console.log("loading:::"+_loader.loading);
}
}
}
}
applicatioui.hpp
#ifndef ApplicationUI_HPP_
#define ApplicationUI_HPP_
#include "imageloader.hpp"
#include
namespace bb
{
namespace cascades
{
class LocaleHandler;
}
}
class QTranslator;
class ApplicationUI : public QObject
{
Q_OBJECT
public:
ApplicationUI();
virtual ~ApplicationUI() {}
Q_INVOKABLE void prepareImage();
Q_INVOKABLE void loadImage();
Q_INVOKABLE ImageLoader* getImageloadderInstance();
private slots:
void onSystemLanguageChanged();
private:
ImageLoader* image;
QTranslator* m_pTranslator;
bb::cascades::LocaleHandler* m_pLocaleHandler;
};
#endif /* ApplicationUI_HPP_ */
applicatioui.cpp
#include "applicationui.hpp"
#include
#include
#include
#include
using namespace bb::cascades;
ApplicationUI::ApplicationUI() :
QObject()
{
// prepare the localization
m_pTranslator = new QTranslator(this);
m_pLocaleHandler = new LocaleHandler(this);
image =new ImageLoader("http://uat2.thomascook.in/bpmapp-upload/download/fstore/7f00000105a3d7bf_eb1af9_1485f184f7b_-52f0/GIT_banner.jpg",this);
bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
// This is only available in Debug builds
Q_ASSERT(res);
// Since the variable is not used in the app, this is added to avoid a
// compiler warning
Q_UNUSED(res);
// initial load
onSystemLanguageChanged();
// Create scene document from main.qml asset, the parent is set
// to ensure the document gets destroyed properly at shut down.
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
qml->setContextProperty("_loader",this);
// Create root object for the UI
AbstractPane *root = qml->createRootObject();
if(root)
{
}
// Set created root object as the application scene
Application::instance()->setScene(root);
}
void ApplicationUI::onSystemLanguageChanged()
{
QCoreApplication::instance()->removeTranslator(m_pTranslator);
// Initiate, load and install the application translation files.
QString locale_string = QLocale().name();
QString file_name = QString("loading_Image_%1").arg(locale_string);
if (m_pTranslator->load(file_name, "app/native/qm")) {
QCoreApplication::instance()->installTranslator(m_pTranslator);
}
}
ImageLoader* ApplicationUI::getImageloadderInstance()
{
image =new ImageLoader("http://uat2.thomascook.in/bpmapp-upload/download/fstore/7f00000105a3d7bf_eb1af9_1485f184f7b_-52f0/GIT_banner.jpg",this);
return (image);
}
void ApplicationUI::prepareImage()
{
image =new ImageLoader("http://uat2.thomascook.in/bpmapp-upload/download/fstore/7f00000105a3d7bf_eb1af9_1485f184f7b_-52f0/GIT_banner.jpg",this);
}
void ApplicationUI::loadImage()
{
image->load();
}
Now I want to load multiple images. I tried to create QList<QObject*>* image;
and add instances of the ImageLoader class, but I don't know how to access it in main.qml.
Any ideas how to do so?

https://github.com/RileyGB/BlackBerry10-Samples/tree/master/WebImageViewSample
follow this link there is a control called "WebImageView". you just have to set the url of image and its done. int main.qml coder have shown user friendly UI.
thanks to #Bojan Kogoj

Related

How to implement a list depending on the elements of a different QAbstractListModel in QML?

In QML, I want to specify a list of options (strings) that the user can choose to insert into my backend. But I don't want the list to contain strings that are already in the backend. And if the backend is updated, then the list of options should also update.
First I wrote a subclass QAbstractListModel which exposes a list of QString interface for my backend. It follows the guidelines from the docs, and exposes two custom functions push_back and indexOf.
class MyModel: public QAbstractListModel {
Q_OBJECT
public:
MyModel() { ... } // connect to the backend
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override {
Q_UNUSED(role);
if (!hasIndex(index.row(), index.column())) {
return {};
}
return ... // retreive backend object at index.row() and convert to QString
}
Q_INVOKABLE void push_back(const QString& item) {
beginInsertRows(QModelIndex(), int(_data->size()), int(_data->size()));
... // convert QString to backend data type and insert into backend
endInsertRows();
}
Q_INVOKABLE int indexOf(const QString& item) {
return ... // convert QString to backend type, and search backend for this object. return -1 if not found
}
private:
// pointer to backend object
};
I was thinking something like this in my QML. First a view of the strings that are already in the backend. This part works fine.
ListView {
anchors.fill: parent
spacing: 5
model: backend // an instance MyModel interface, passed in from main.cpp
delegate: Rectangle {
height: 25
width: 200
Text { text: model.display}
}
}
And then the list of options that can be added to the backend, which are not already part of the backend. This part doesn't work.
ListView {
anchors.fill: parent
spacing: 5
model: ["option1", "option2", "option3"]
delegate: Rectangle {
visible: backend.indexOf(model.modelData) >= 0
height: 25
width: 200
MouseArea {
id: mouseArea1
anchors.fill: parent
onClicked: {
backend.push_back(model.modelData)
}
}
Text { text: model.modelData }
}
}
The problem is, when strings are added to the backend, this list does not refresh. I don't think Qt understands that backend.indexOf needs to be recomputed whenever its modified.
You are correct about the problem. There's no binding that will re-call indexOf. One way to fix it is you could add a Connections object so you can listen for a specific signal and then manually update the visible property:
delegate: Rectangle {
visible: backend.indexOf(model.modelData) >= 0
height: 25
width: 200
MouseArea {
id: mouseArea1
anchors.fill: parent
onClicked: {
backend.push_back(model.modelData)
}
}
Text { text: model.modelData }
Connections {
target: backend
onCountChanged: visible = (backend.indexOf(model.modelData) >= 0)
}
}

How to refresh a combo-box in qml after sending a signal

Basically, I have a combo-box in qml that I populate using a QStringList. However, I'm not able to refresh the combo-box (reload) to show the list has changed. I looked into doing that using the Loader but I couldn't figure it out. Can someone guide me in how to do it.
network.qml
Popup{
contentItem: Rectangle{
LabelValueList {
id: list1
row1: LabelValue {
id: row1
row2: LabelValue {
id: row2
value: ComboBox {
id: combobox
model: ListModel {
id: comboModel
Component.onCompleted: {
//..
}
}
}
}
}
}
}
}
network.h
class Network : public QObject{
Q_OBJECT
Q_PROPERTY(QStringList listOfNetworks READ m_listOfNetworks NOTIFY updateNetworks)
private:
QStringList m_listOfNetworks;
public:
explicit Network(QObject *parent = 0);
QStringList listOfNetworks() const;
public slots:
void slot_scanNetworks();
signals:
void updateNetworks();
};
network.cpp
Network::Network(QObject *parent) : QObject (parent){
}
void Network::slot_scanNetworks(){
QFile SSIDsFile("/home/root/networking/listOfWifiNetworks.txt");
m_listOfNetworks.clear();
if (!SSIDsFile.open(QIODevice::ReadOnly | QIODevice::Text)){
//
}
else{
QTextStream scanNetworkStream(&SSIDsFile);
while (!scanNetworkStream.atEnd()){
QString line = scanNetworkStream.readLine();
if (line.size() != 0){
QStringList lineSplit = line.split(' ');
m_listOfNetworks.append(lineSplit[1]);
}
}
}
SSIDsFile.close();
emit updateNetworks();
}
How do I reload the combo-box of row2 to refresh the list? It only get's the list at the beginning but i want to update the drop-down (combo-box) when I emit the signal updateNetworks(). I tried using the Loader and setting the source.Component of it to the id of row2 but I kept getting the error "Error: Cannot assign QObject* to QQmlComponent". Any help?
I am not pro but maybe help u this post .
you can use a timer on ur application and set 1s to refresh this and make a variable and when call signal call this variable
example :
// make a variable type of bool by value = false
property bool refreshMyBoxNow : false
//add this timer to ur project
Timer
{
id: timeToRefreshBox
//interval = time to tick . (1000) = 1sec
interval: 1; running: true; repeat: true
onTriggered:
{
//your code here for refresh box
}
}

How can I reset a timer every time I receive a touch event from a qml page

import QtQuick 2.6;
import QtQuick.Controls 2.1 ;
import QtQuick.Layouts 1.3 ;
Page{
id: page
width: 800
height: 1024
background: Rectangle {
color: "black" ;
anchors.fill:parent ;
}
Rectangle {
id:rect1
x: 0
y:10
width: 100
height: 100
color : "red"
MouseArea {
anchors.fill: parent
onClicked: tmr.restart()
}
}
Rectangle {
id:rect2
x: 0
y:110
width: 100
height: 100
color : "blue"
MouseArea {
anchors.fill: parent
onClicked: tmr.restart()
}
}
Timer {
id : tmr
interval : 30000
repeat : true
running: true
onTriggered: {
console.log ("hello world ")
}
}
}
I develop a software for embedded imx6 freescale device using qt framework.
Basically I just want to restart my timer every time I click and every time I get a touch event on my screen whether the click/touch happen inside the mouse area of my rectangles or outside of them.
The idea is similar to a screensaver.
There are multiple ways, and the right way depends on your requirements.
If you don't need to guarantee that the timer triggers during a input you can just layer a MouseArea on top of everything. In this MouseArea you handle the pressed-signals, but dont accept them.
This allows you to handle the mouse input in the lower layers later. However you only realize whenever a new press happens, and the Timer might trigger e.g. during a half-an-hour finger-move input.
The second way is to have all MouseAreas report uppon their handled signals, that the signal happend, to reset the Timer. For all unhandled signals, you layer a MouseArea beneath everything else, handle all signals there to catch what has been falling through.
Resorting to C++ you might create a Item at the root of your Item-tree, and override the childMouseEventFitler
See my answer here for more on this.
In this case you should add a MouseArea right inside this Item, so it has something to filter at any place.
Note! This method will be triggered for each MouseArea that might be under your click. But in your scenario, this would be fine, I guess.
Thanks to GrecKo I looked into the general eventFilter again, and indeed it is really easy.
you create a simple QObject following the singleton pattern, in which you reimplement the eventFilter-method, so that it will emit a signal
mouseeventspy.h
#pragma once
#include <QObject>
#include <QtQml>
#include <QQmlEngine>
#include <QJSEngine>
class MouseEventSpy : public QObject
{
Q_OBJECT
public:
explicit MouseEventSpy(QObject *parent = 0);
static MouseEventSpy* instance();
static QObject* singletonProvider(QQmlEngine* engine, QJSEngine* script);
protected:
bool eventFilter(QObject* watched, QEvent* event);
signals:
void mouseEventDetected(/*Pass meaningfull information to QML?*/);
};
mouseeventspy.cpp
#include "mouseeventspy.h"
#include <QQmlEngine>
#include <QJSEngine>
#include <QEvent>
MouseEventSpy::MouseEventSpy(QObject *parent) : QObject(parent)
{
qDebug() << "created Instance";
}
// This implements the SINGLETON PATTERN (*usually evil*)
// so you can get the instance in C++
MouseEventSpy* MouseEventSpy::instance()
{
static MouseEventSpy* inst;
if (inst == nullptr)
{
// If no instance has been created yet, creat a new and install it as event filter.
// Uppon first use of the instance, it will automatically
// install itself in the QGuiApplication
inst = new MouseEventSpy();
QGuiApplication* app = qGuiApp;
app->installEventFilter(inst);
}
return inst;
}
// This is the method to fullfill the signature required by
// qmlRegisterSingletonType.
QObject* MouseEventSpy::singletonProvider(QQmlEngine *, QJSEngine *)
{
return MouseEventSpy::instance();
}
// This is the method is necessary for 'installEventFilter'
bool MouseEventSpy::eventFilter(QObject* watched, QEvent* event)
{
QEvent::Type t = event->type();
if ((t == QEvent::MouseButtonDblClick
|| t == QEvent::MouseButtonPress
|| t == QEvent::MouseButtonRelease
|| t == QEvent::MouseMove)
&& event->spontaneous() // Take only mouse events from outside of Qt
)
emit mouseEventDetected();
return QObject::eventFilter(watched, event);
}
Than you register it as singleton type to QML like this:
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "mouseeventspy.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterSingletonType<MouseEventSpy>("MouseEventSpy", 1, 0, "MouseEventSpy", MouseEventSpy::singletonProvider);
// We do this now uppon creation of the first instance.
// app.installEventFilter(MouseEventSpy::instance());
engine.load(QUrl(QStringLiteral("main.qml")));
return app.exec();
}
Now in QML you can import the instance of the singleton in the necessary files and use the signal, e.g. to reset a Timer
main.qml
import QtQuick 2.6
import QtQuick.Window 2.2
import MouseEventSpy 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Connections {
target: MouseEventSpy
onMouseEventDetected: myTimer.restart()
}
Timer {
id: myTimer
interval: 1000
onTriggered: console.log('It has been 1 seconds since the last mouse event')
}
Text {
anchors.center: parent
text: myTimer.running ? 'Timer is Running\nMove the mouse to reset'
: 'Move the Mouse to make the timer run again.'
}
}

QSignalBlocker in Qml/QtQuick2?

I want to set the currentIndex of a ComboBox dynamically without triggering my attached signal.
I am currently using a bool property to set a flag that gets cleared when my signal gets called.
Item {
property bool ignoreNextChanged: false
CustomCppItem {
id: customItem
onSomethingHappened: {
ignoreNextChanged = true
comboBox.currentIndex = 42
}
}
ComboBox {
id: comboBox
currentIndex: -1
onCurrentIndexChanged: {
if(ignoreNextChanged) {
ignoreNextChanged = false
return
}
// Removed code here
}
}
}
Coming from Qt/C++, I would like to use some sort of QSignalBlocker here instead of my own property.
Is there some equivalent in Qml/QtQuick2?
For this I would implement an attached type in c++ :
signalblockerattachedtype.h :
#ifndef SIGNALBLOCKERATTACHEDTYPE_H
#define SIGNALBLOCKERATTACHEDTYPE_H
#include <QObject>
#include <qqml.h>
class SignalBlockerAttachedType : public QObject
{
Q_OBJECT
Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
public:
explicit SignalBlockerAttachedType(QObject *object = nullptr) : QObject(object), m_object(object)
{
}
~SignalBlockerAttachedType() {
if (m_object)
m_object->blockSignals(false);
}
bool enabled() const
{
return m_enabled;
}
void setEnabled(bool enabled)
{
if (m_enabled == enabled)
return;
if (m_object)
m_object->blockSignals(enabled);
m_enabled = enabled;
emit enabledChanged();
}
static SignalBlockerAttachedType *qmlAttachedProperties(QObject *object) {
return new SignalBlockerAttachedType(object);
}
signals:
void enabledChanged();
private:
bool m_enabled = false;
QObject *m_object;
};
QML_DECLARE_TYPEINFO(SignalBlockerAttachedType, QML_HAS_ATTACHED_PROPERTIES)
#endif // SIGNALBLOCKERATTACHEDTYPE_H
main.cpp :
#include "signalblockerattachedtype.h"
// ...
qmlRegisterUncreatableType<SignalBlockerAttachedType>("fr.grecko.SignalBlocker", 1, 0, "SignalBlocker", "SignalBlocker is only available as an attached type.");
// ...
engine.load(QUrl(QLatin1String("qrc:/usage.qml")));
usage.qml :
import fr.grecko.SignalBlocker 1.0
// ...
Item {
id: rootItem
property alias currentIndex: comboBox.currentIndex
onCurrentIndexChanged: {
// this won't get called from a change in onSomethingHappened
}
CustomCppItem {
id: customItem
onSomethingHappened: {
rootItem.SignalBlocker.enabled = true;
rootItem.currentIndex = 42
rootItem.SignalBlocker.enabled = false;
}
}
ComboBox {
id: comboBox
currentIndex: -1
}
}
Even though the SignalBlocker works on the ComboBox, you don't want to put it on the ComboBox. Doing so will prevent it to update its display when the index changes.
In your situation, I don't think this solution is better than using a simple flag.

saving QML image

How can I save QML Image into phone memory ??
also if saving the image was applicable , I have this case which I need to add some text to the image (we can imagine it as we have a transparent image[that hold the text] and put it over the second image , so finally we have one image that we can save it into phone memory)
Not from Image directly. QDeclarativeImage has pixmap, setPixmap and pixmapChange methods, but for some reason there is no property declared. So you cannot use it fom qml. Unfortunately it cannot be used from C++ either - it is a private calsss.
What you can do is paint graphics item to your pixmap and save it to file.
class Capturer : public QObject
{
Q_OBJECT
public:
explicit Capturer(QObject *parent = 0);
Q_INVOKABLE void save(QDeclarativeItem *obj);
};
void Capturer::save(QDeclarativeItem *item)
{
QPixmap pix(item->width(), item->height());
QPainter painter(&pix);
QStyleOptionGraphicsItem option;
item->paint(&painter, &option, NULL);
pix.save("/path/to/output.png");
}
Register "capturer" context variable:
int main()
{
// ...
Capturer capturer;
QmlApplicationViewer viewer;
viewer.rootContext()->setContextProperty("capturer", &capturer);
// ...
}
And use it in your qml:
Rectangle {
// ...
Image {
id: img
source: "/path/to/your/source"
}
MouseArea {
anchors.fill: parent
onClicked: {
capturer.save(img)
}
}
}
With Qt 5.4+ you can do it straight from your Qml with:
grabToImage

Resources