在ImageView Blackberry 10中动态设置imageSource [英] Dynamically set imageSource in ImageView Blackberry 10

查看:229
本文介绍了在ImageView Blackberry 10中动态设置imageSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我,我卡住了这一个多星期。我发出一个信号与图像从我的cpp文件。我需要替换我放置在imageView在QMl使用这个发射的图像的默认图像。
这是我的完整代码。



PostHttp.hpp

  / *版权所有(c)2012 Research In Motion Limited。 
*
*根据Apache许可证2.0版(许可证)授权;
*您不得使用此文件,除非符合许可证。
*您可以通过以下方式获取许可证的副本:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或以书面形式同意,软件
*根据许可证分发的软件按原样基础,
*分发,不附有任何明示或暗示的担保或条件。
*请参阅许可证管理权限的特定语言和
*许可证下的限制。
* /

#ifndef POSTHTTP_HPP
#define POSTHTTP_HPP
#includeqvariant.h
#include< bb / ImageData>
#include< bb / cascades / GroupDataModel>
#include< QtCore / QObject>
#include< bb / data / JsonDataAccess>
#include< bb / cascades / QListDataModel>
#include< bb / cascades / Image>
#include< bb / cascades / ImageView>
#include< bb / cascades / CustomControl>
namespace bb {
命名空间cascades {
class Container;
}
}
使用命名空间bb :: cascades;

class QNetworkAccessManager;

类PostHttp:public QObject {
Q_OBJECT
public:
PostHttp(QObject * parent = 0);
bb :: cascades :: Image m_image;
ImageView * imageView;
Container * mRootContainer;
bool createFolder(QString path);
bool openAndSaveFile(QString filePathWithName,QNetworkReply * reply);
public Q_SLOTS:
void loginWebService(const QString& body,const QString& pass,
bool istoken);
void newsFeedWebService(const qint16 num);
void logoutWebService();
void imageFetcher();
void get(const QUrl& url);
void post(const QVariantMap& body,const QUrl& url);


Q_SIGNALS:
void complete(const QVariantList& info);
void newsfeedComplete(const QVariantList& info);
void imageLoaded(const QVariant& image);

private Q_SLOTS:
void onGetReply();
void onNewsFeedReply();
void onImageReply();

Q_INVOKABLE void generatePage();
Q_INVOKABLE void loadImages();
private:
bb :: cascades :: QListDataModel< QObject *> * m_model;
QImage setImage(const QImage& image);
bb :: cascades :: DataModel * model()const;
QNetworkAccessManager * m_networkAccessManager;
bb :: data :: JsonDataAccess * dataAccess;

public:
QString token;

};

#endif

PostHttp.cpp

  #includePostHttp.hpp
#include< QDebug>
#include< QNetworkAccessManager>
#include< QNetworkReply>
#include< QNetworkRequest>
#include< QSslConfiguration>
#include< QUrl>
#include< bb / data / JsonDataAccess>
#include< QDateTime>
#include< bb / cascades / AbstractPane>
#include< bb / cascades / Application>
#include< bb / cascades / QmlDocument>
#include< bb / cascades / Page>
#include< bb / cascades / StandardListItem>
#include< QFile>
#include< bb / ImageData>
#include< QNetworkReply>
#include< QNetworkDiskCache>
#include< QDesktopServices>
#include< bb / cascades / Image>
#include< bb / cascades / Container>
#include< bb / cascades / ImageView>
#include< bb / cascades / ScalingMethod>
#include< bb / cascades / DockLayout>
#include< bb / cascades / controls / activityindicator.h>
#include< bb / cascades / controls / scrollview.h>
#include< bb / cascades / controls / page.h>
#include< bb / cascades / NavigationPaneProperties>
#include< bb / cascades / Color>
using namespace bb :: data;
using namespace bb :: cascades;
using namespace bb :: utility;
QString globalTokenValue;
int globalUserId;
bool flag = true;
bool flag1 = true;
QVariantList data;

PostHttp :: PostHttp(QObject * parent):
QObject(parent),m_networkAccessManager(
new QNetworkAccessManager(this)),m_model(
new QListDataModel& *>()){

}

//! [0]

/ **
* PostHttp :: post
*
*使用POST数据向httpbin.org/post发出网络请求,并获取
*响应
* /
//! [1]
void PostHttp :: post(const QVariantMap& body,const QUrl& url){
JsonDataAccess jda;
QByteArray jsonData
jda.saveToBuffer(*(& body),& jsonData);

QByteArray postDataSize = QByteArray :: number(jsonData.size());
QNetworkRequest request(*(& url));

request.setHeader(QNetworkRequest :: ContentTypeHeader,application / json);
request.setHeader(QNetworkRequest :: ContentLengthHeader,
QString(postDataSize).toUtf8());
// QNetworkReply * reply = m_networkAccessManager-> post(request,body.toAscii());
qDebug()<< json< jsonData;
QNetworkReply * reply = m_networkAccessManager-> post(request,jsonData);
qDebug()<< strdgfyusujnm kjh< (& url) - > toString();
if((& url) - > toString()
==http:/// GetNewsFeed){
connect(reply,SIGNAL(finished SLOT(onNewsFeedReply()));
} else {
connect(reply,SIGNAL(finished()),this,SLOT(onGetReply()));
}
}

void PostHttp :: loginWebService(const QString& body,const QString& pass,
bool istoken){

qint64 date = QDateTime :: currentMSecsSinceEpoch();
QString time = QString :: number(date);
QVariantMap data;
QVariantMap loginData;
QVariantMap devicedata;
devicedata.insert(OS,BlackBerry OS 6.0.0.706);
devicedata.insert(deviceId,232BC441);
devicedata.insert(deviceModel,9800);
devicedata.insert(screenSize,480x360);
loginData.insert(device,devicedata);
loginData.insert(email,*(& body));
loginData.insert(password,*(& pass));
loginData.insert(requestDate,/ Date(+ time ++200)/);
data.insert(apiKey,4f74721be9b51f24f065b044);
data.insert(data,loginData);
data.insert(requestDate,/ Date(+ time ++200)/);
if(istoken){

} else {
data.insert(token,);
}
const QUrl url(
http:/// LoginRequest);
post(data,url);
}

void PostHttp :: newsFeedWebService(const qint16 num){

qint64 date = QDateTime :: currentMSecsSinceEpoch();
QString time = QString :: number(date);
QVariantMap data;
QVariantMap newsfeedData;
newsfeedData.insert(postId,0);
newsfeedData.insert(requestType,2);
newsfeedData.insert(requestedCount,num);
newsfeedData.insert(userId,globalUserId);
data.insert(apiKey,4f74721be9b51f24f065b044);
data.insert(data,newsfeedData);
data.insert(requestDate,/ Date(+ time ++200)/);
data.insert(token,globalTokenValue);
const QUrl url(
http:/// GetNewsFeed);
if(flag == true){
post(data,url);
}

}

void PostHttp :: logoutWebService(){
qint64 date = QDateTime :: currentMSecsSinceEpoch();
QString time = QString :: number(date);
QVariantMap data;
QVariantMap logoutData;
logoutData.insert(logoutRequestType,1);
logoutData.insert(userId,globalUserId);
data.insert(apiKey,4f74721be9b51f24f065b044);
data.insert(data,logoutData);
data.insert(requestDate,/ Date(+ time ++200)/);
data.insert(token,globalTokenValue);
const QUrl url(
http:/// LogoutUser);
post(data,url);
}

void PostHttp :: imageFetcher(){
const QUrl url(
http://upload.wikimedia.org/wikipedia/commons/e/ e7 / Nuvola_filesystems_services.png);
if(flag1 == true){
get(url);
}
}

void PostHttp :: get(const QUrl& url){
QNetworkRequest request(*(& url));
QNetworkReply * reply = m_networkAccessManager-> get(request);
connect(reply,SIGNAL(finished()),this,SLOT(onImageReply()));
}
/ **
* PostHttp :: onGetReply()
*
* SLOT
*从我们的http post请求中读取并返回http响应
* /
void PostHttp :: onGetReply(){
QNetworkReply * reply = qobject_cast< QNetworkReply *>(sender());
QString response;
if(reply){
if(reply-> error()== QNetworkReply :: NoError){
const int available = reply-> bytesAvailable();
if(available> 0){
const QByteArray buffer(reply-> readAll());
response = QString :: fromUtf8(buffer);
JsonDataAccess dataAccess;
QVariantMap results =
dataAccess.loadFromBuffer(response).toMap();
QString token =(results [Token])。value< QString>();
int userId =(results [userId])。value< int>();
if(globalTokenValue ==){
globalTokenValue = token;
globalUserId = userId;
} else
flag = false;
QString success =(results [Success])。value< QString>();

}
} else {
response =
tr(Error:%1 status:%2)arg(reply-> errorString
reply-> attribute(
QNetworkRequest :: HttpStatusCodeAttribute).toString());
qDebug()<<响应;
}

reply-> deleteLater();
}

if(response.trimmed()。isEmpty()){
response = tr(无法检索回复);
}
qDebug()<< response<<响应;

}

void PostHttp :: onNewsFeedReply(){

QNetworkReply * reply = qobject_cast< QNetworkReply *>(sender
QString response;
if(reply){
if(reply-> error()== QNetworkReply :: NoError){
flag = false;
const int available = reply-> bytesAvailable();
if(available> 0){
const QByteArray buffer(reply-> readAll());
response = QString :: fromUtf8(buffer);
JsonDataAccess dataAccess;
QVariantMap results =
dataAccess.loadFromBuffer(response).toMap();
data = results.value(Data)。toList();
qDebug()<< 第一元素是< data.first()。toString();
emit newsfeedComplete(data);

}
}
}

}
void PostHttp :: onImageReply(){
QNetworkReply * reply = qobject_cast< QNetworkReply *>(sender())
QString response;
QImage img;
QString filePathWithName =data / img /;
QString imageName;

if(reply){
if(reply-> error()== QNetworkReply :: NoError){
flag1 = false;
const int available = reply-> bytesAvailable();
if(available> 0){
const QByteArray buffer(reply-> readAll());
response = QString :: fromUtf8(buffer);
img.loadFromData(buffer);
img = img.scaled(40,40,Qt :: KeepAspectRatioByExpanding);
const QImage swappedImage = img.rgbSwapped();
const bb :: ImageData imageData = bb :: ImageData :: fromPixels(
swappedImage.bits(),bb :: PixelFormat :: RGBX,
swappedImage.width(),swappedImage.height (),
swappedImage.bytesPerLine());
QByteArray byteArray = bb :: utility :: ImageConverter :: encode(
image / png,imageData,75);
qDebug()<< bytearray is< byteArray;
// QVariant image(byteArray);
QVariant realImage(byteArray);

qDebug()<< image of image is< realImage;
emit imageLoaded(realImage);
}
}
}
}
//! [1]

最后,我的QML档案是



NewsFeed.qml

  import bb.cascades 1.0 
import Network.PostHttp 1.0
import bb .cascades 1.0
importcontrols
import my.library 1.0

页面{
操作:[
ActionItem {
title:注销
onTriggered:{
netpost.logoutWebService();
Application.quit();
}
ActionBar.placement:ActionBarPlacement.OnBar
}
]
id:mainpage
onCreationCompleted:{
Qt.mainImageview = imageviewid;
}
容器{

布局:DockLayout {
}

//背景图片
ImageView {
horizo​​ntalAlignment:Horizo​​ntalAlignment.Fill
verticalAlignment:VerticalAlignment.Fill
imageSource:asset:///images/background.png
}
//! [0]

容器{
id:innercontainer

ActivityIndi​​cator {
id:progressIndicator

horizo​​ntalAlignment:Horizo​​ntalAlignment.Fill
verticalAlignment:VerticalAlignment.Fill
onStarted:{

}
onCreationCompleted:{
progressIndicator.running = true;

}

}

ListView {
id:listView
objectName:listView

dataModel:ArrayDataModel {
id:myListModel

}

//覆盖默认GroupDataModel :: itemType()行为,
listItemComponents:ListItemComponent {
id:listcomponent
// StandardListItem是具有默认级联外观的列表的欢迎组件
StandardListItem {
title:ListItemData.postText
description:ListItemData.postDate
status:ListItemData.filePath
imageSource:asset:///images/4.png
}

}
layoutProperties:StackLayoutProperties {
spaceQuota:1.0
}
horizo​​ntalAlignment:Horizo​​ntalAlignment.Fill
verticalAlignment:VerticalAlignment.Fill

}


容器{
id:root
布局:StackLayout {
}
标签{
text:ListItemData.postText
horizo​​ntalAlignment:Horizo​​ntalAlignment.Left
verticalAlignment:VerticalAlignment.Bottom
}
标签{
text:ListItemData.postDate
// textStyle.fontSize:5
horizo​​ntalAlignment :Horizo​​ntalAlignment.Right
verticalAlignment:VerticalAlignment.Bottom
}

attachedObjects:[
QTimer {
id:timer
property int f: 0
interval:5000
onTimeout:{
progressIndicator.running = false;
netpost.imageFetcher();
netpost.newsFeedWebService(10);
}

},
PostHttp {

id:netpost
onComplete:{
progressIndicator.running = false;
progressIndicator.visible = false;
console.log(dsfdsafs+ netpost.model)
timer.stop();
}

onImageLoaded:{
console.log(value is image from cpp jhgsdh+ image)
imageviewid.setImageSource(image)
}
onNewsfeedComplete:{
console.log(newsfeed的回复为+ info)
myListModel.append(info)

}
}

]
}

onCreationCompleted:{
//创建声明场景时调用此槽
//在此创建初始化
console.log(Page-onCreationCompleted())

//启用布局以适应设备旋转
//不要忘记在bar- bescriptor.xml(Application-> Orientation-> Auto-orient)
OrientationSupport.supportedDisplayOrientation = SupportedDisplayOrientation.All;

//使用示例数据填充列表视图模型
timer.start();
// myListModel.load(app / native / assets / mydata.json)

}
ImageView {
ID:imageviewid
imageSource: asset:///images/4.png
enabled:true
loadEffect:ImageViewLoadEffect.FadeZoom

}
}
}
}

请帮助我。

QVariant 参数定义了你的槽,但是试图使用 QByteArray code> ImageConverter :: encode()调用返回的类型。



尝试更改你的代码的一部分,并给它一个去:

  QByteArray byteArray = bb :: utility :: ImageConverter :: encode QUrl(QDir :: currentPath()+/shared/camera/img.png),imageData,75); 
QVariant image(byteArray);
emit imageLoaded(image);

此外,请仔细检查您声明/定义此对信号/完全相同的参数表示法(即 imageLoaded()信号等情况下 const QVariant& >

Please help me.,i m stuck with this for more than a week.I am emitting a signal with image from my cpp file.I need to replace the default image that i placed in the imageView at QMl using this emitted image. Here is my full code.

PostHttp.hpp

/* Copyright (c) 2012 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 #ifndef POSTHTTP_HPP
 #define POSTHTTP_HPP
 #include "qvariant.h"
 #include <bb/ImageData>
 #include <bb/cascades/GroupDataModel>
 #include <QtCore/QObject>
 #include <bb/data/JsonDataAccess>
 #include <bb/cascades/QListDataModel>
 #include <bb/cascades/Image>
 #include <bb/cascades/ImageView>
 #include <bb/cascades/CustomControl>
 namespace bb {
namespace cascades {
    class Container;
}
 }
  using namespace bb::cascades;

 class QNetworkAccessManager;

class PostHttp: public QObject {
Q_OBJECT
public:
PostHttp(QObject* parent = 0);
 bb::cascades::Image m_image;
 ImageView* imageView;
 Container* mRootContainer;
 bool createFolder(QString path);
 bool openAndSaveFile(QString filePathWithName, QNetworkReply* reply);
public Q_SLOTS:
void loginWebService(const QString &body, const QString &pass,
        bool istoken);
void newsFeedWebService(const qint16 num);
void logoutWebService();
void imageFetcher();
void get(const QUrl &url);
void post(const QVariantMap &body, const QUrl &url);


Q_SIGNALS:
void complete(const QVariantList &info);
void newsfeedComplete(const QVariantList &info);
void imageLoaded(const QVariant &image);

private Q_SLOTS:
void onGetReply();
void onNewsFeedReply();
void onImageReply();

Q_INVOKABLE void generatePage();
 Q_INVOKABLE void loadImages();
private:
bb::cascades::QListDataModel<QObject*>* m_model;
QImage setImage(const QImage &image);
bb::cascades::DataModel* model() const;
QNetworkAccessManager* m_networkAccessManager;
bb::data::JsonDataAccess* dataAccess;

public:
QString token;

};

#endif

PostHttp.cpp

#include "PostHttp.hpp"
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslConfiguration>
#include <QUrl>
#include <bb/data/JsonDataAccess>
#include <QDateTime>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/Page>
#include <bb/cascades/StandardListItem>
#include <QFile>
#include <bb/ImageData>
#include <QNetworkReply>
#include <QNetworkDiskCache>
#include <QDesktopServices>
#include <bb/cascades/Image>
#include <bb/cascades/Container>
#include <bb/cascades/ImageView>
#include <bb/cascades/ScalingMethod>
#include <bb/cascades/DockLayout>
#include <bb/cascades/controls/activityindicator.h>
#include <bb/cascades/controls/scrollview.h>
#include <bb/cascades/controls/page.h>
#include <bb/cascades/NavigationPaneProperties>
#include <bb/cascades/Color>
using namespace bb::data;
using namespace bb::cascades;
using namespace bb::utility;
QString globalTokenValue;
int globalUserId;
bool flag = true;
bool flag1 = true;
QVariantList data;

PostHttp::PostHttp(QObject* parent) :
    QObject(parent), m_networkAccessManager(
            new QNetworkAccessManager(this)), m_model(
            new QListDataModel<QObject*>()) {

}

//! [0]

/**
 * PostHttp::post
 *
 * Make a network request to httpbin.org/post with POST data and get
 * the response
 */
//! [1]
void PostHttp::post(const QVariantMap &body, const QUrl &url) {
JsonDataAccess jda;
QByteArray jsonData;
jda.saveToBuffer(*(&body), &jsonData);

QByteArray postDataSize = QByteArray::number(jsonData.size());
QNetworkRequest request(*(&url));

request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setHeader(QNetworkRequest::ContentLengthHeader,
        QString(postDataSize).toUtf8());
//QNetworkReply* reply = m_networkAccessManager->post(request, body.toAscii());
qDebug() << "json" << jsonData;
QNetworkReply* reply = m_networkAccessManager->post(request, jsonData);
qDebug() << "strdgfyusujnm kjh " << (&url)->toString();
if ((&url)->toString()
        ==    "http:///GetNewsFeed") {
    connect(reply, SIGNAL(finished()), this, SLOT(onNewsFeedReply()));
} else {
    connect(reply, SIGNAL(finished()), this, SLOT(onGetReply()));
}
}

void PostHttp::loginWebService(const QString &body, const QString &pass,
    bool istoken) {

qint64 date = QDateTime::currentMSecsSinceEpoch();
QString time = QString::number(date);
QVariantMap data;
QVariantMap loginData;
QVariantMap devicedata;
devicedata.insert("OS", "BlackBerry OS 6.0.0.706");
devicedata.insert("deviceId", "232BC441");
devicedata.insert("deviceModel", "9800");
devicedata.insert("screenSize", "480x360");
loginData.insert("device", devicedata);
loginData.insert("email", *(&body));
loginData.insert("password", *(&pass));
loginData.insert("requestDate", "/Date(" + time + "+200)/");
data.insert("apiKey", "4f74721be9b51f24f065b044");
data.insert("data", loginData);
data.insert("requestDate", "/Date(" + time + "+200)/");
if (istoken) {

} else {
    data.insert("token", "");
}
const QUrl url(
         "http:///LoginRequest");
post(data, url);
}

void PostHttp::newsFeedWebService(const qint16 num) {

qint64 date = QDateTime::currentMSecsSinceEpoch();
QString time = QString::number(date);
QVariantMap data;
QVariantMap newsfeedData;
newsfeedData.insert("postId", 0);
newsfeedData.insert("requestType", 2);
newsfeedData.insert("requestedCount", num);
newsfeedData.insert("userId", globalUserId);
data.insert("apiKey", "4f74721be9b51f24f065b044");
data.insert("data", newsfeedData);
data.insert("requestDate", "/Date(" + time + "+200)/");
data.insert("token", globalTokenValue);
const QUrl url(
        "http:///GetNewsFeed");
if (flag == true) {
    post(data, url);
}

}

void PostHttp::logoutWebService() {
qint64 date = QDateTime::currentMSecsSinceEpoch();
QString time = QString::number(date);
QVariantMap data;
QVariantMap logoutData;
logoutData.insert("logoutRequestType", 1);
logoutData.insert("userId", globalUserId);
data.insert("apiKey", "4f74721be9b51f24f065b044");
data.insert("data", logoutData);
data.insert("requestDate", "/Date(" + time + "+200)/");
data.insert("token", globalTokenValue);
const QUrl url(
        "http:///LogoutUser");
post(data, url);
}

void PostHttp::imageFetcher() {
const QUrl url(
        "http://upload.wikimedia.org/wikipedia/commons/e/e7/Nuvola_filesystems_services.png");
if (flag1 == true) {
    get(url);
}
}

void PostHttp::get(const QUrl &url) {
QNetworkRequest request(*(&url));
QNetworkReply* reply = m_networkAccessManager->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(onImageReply()));
}
/**
 * PostHttp::onGetReply()
 *
 * SLOT
 * Read and return the http response from our http post request
 */
void PostHttp::onGetReply() {
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
if (reply) {
    if (reply->error() == QNetworkReply::NoError) {
        const int available = reply->bytesAvailable();
        if (available > 0) {
            const QByteArray buffer(reply->readAll());
            response = QString::fromUtf8(buffer);
            JsonDataAccess dataAccess;
            QVariantMap results =
                       dataAccess.loadFromBuffer(response).toMap();
            QString token = (results["Token"]).value<QString>();
            int userId = (results["userId"]).value<int>();
            if (globalTokenValue == "") {
                globalTokenValue = token;
                globalUserId = userId;
            } else
                flag = false;
            QString success = (results["Success"]).value<QString>();

        }
    } else {
        response =
                tr("Error: %1 status: %2").arg(reply- >errorString(),
                        reply->attribute(
                                   QNetworkRequest::HttpStatusCodeAttribute).toString());
        qDebug() << response;
    }

    reply->deleteLater();
}

if (response.trimmed().isEmpty()) {
    response = tr("Unable to retrieve post response");
}
qDebug() << "response" << response;

}

void PostHttp::onNewsFeedReply() {

QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
if (reply) {
    if (reply->error() == QNetworkReply::NoError) {
        flag = false;
        const int available = reply->bytesAvailable();
        if (available > 0) {
            const QByteArray buffer(reply->readAll());
            response = QString::fromUtf8(buffer);
            JsonDataAccess dataAccess;
            QVariantMap results =
                      dataAccess.loadFromBuffer(response).toMap();
            data = results.value("Data").toList();
            qDebug() << "first element is" << data.first().toString();
            emit newsfeedComplete(data);

        }
    }
}

}
 void PostHttp::onImageReply() {
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
QImage img;
QString filePathWithName = "data/img/";
QString imageName;

if (reply) {
    if (reply->error() == QNetworkReply::NoError) {
        flag1 = false;
        const int available = reply->bytesAvailable();
        if (available > 0) {
            const QByteArray buffer(reply->readAll());
            response = QString::fromUtf8(buffer);
            img.loadFromData(buffer);
            img = img.scaled(40, 40, Qt::KeepAspectRatioByExpanding);
            const QImage swappedImage = img.rgbSwapped();
            const bb::ImageData imageData = bb::ImageData::fromPixels(
                    swappedImage.bits(), bb::PixelFormat::RGBX,
                    swappedImage.width(),  swappedImage.height(),
                    swappedImage.bytesPerLine());
            QByteArray byteArray = bb::utility::ImageConverter::encode(
                    "image/png", imageData, 75);
            qDebug() << "bytearray is" << byteArray;
//              QVariant image(byteArray);
            QVariant realImage(byteArray);

            qDebug() << "imag of image is" << realImage;
            emit imageLoaded(realImage);
        }
    }
}
}
//! [1]

And finally my QML file is

NewsFeed.qml

import bb.cascades 1.0
import Network.PostHttp 1.0
import bb.cascades 1.0
import "controls"
import my.library 1.0

Page {
actions: [
    ActionItem {
        title: "Logout"
        onTriggered: {
            netpost.logoutWebService();
            Application.quit();
        }
        ActionBar.placement: ActionBarPlacement.OnBar
    }
]
id:mainpage
onCreationCompleted: {
    Qt.mainImageview = imageviewid;
}
Container {

    layout: DockLayout {
    }

    // The background image
    ImageView {
        horizontalAlignment: HorizontalAlignment.Fill
        verticalAlignment: VerticalAlignment.Fill
        imageSource: "asset:///images/background.png"
    }
    //! [0]

    Container {
        id : innercontainer

        ActivityIndicator {
            id: progressIndicator

            horizontalAlignment: HorizontalAlignment.Fill
            verticalAlignment: VerticalAlignment.Fill
            onStarted: {

            }
            onCreationCompleted: {
                progressIndicator.running = true;

            }

        }

        ListView {
            id: listView
            objectName: "listView"

            dataModel: ArrayDataModel {
                id: myListModel

            }

            // Override default GroupDataModel::itemType() behaviour, which is to return item type "header"
            listItemComponents: ListItemComponent {
                id: listcomponent
                // StandardListItem is a convivience component for lists with default cascades look and feel
                StandardListItem {
                    title: ListItemData.postText
                    description: ListItemData.postDate
                    status: ListItemData.filePath
                    imageSource: "asset:///images/4.png"
                }

            }
            layoutProperties: StackLayoutProperties {
                spaceQuota: 1.0
            }
            horizontalAlignment: HorizontalAlignment.Fill
            verticalAlignment: VerticalAlignment.Fill

        }


        Container {
            id: root
            layout: StackLayout {
            }
            Label {
                text: ListItemData.postText
                horizontalAlignment: HorizontalAlignment.Left
                verticalAlignment: VerticalAlignment.Bottom
            }
            Label {
                text: ListItemData.postDate
                //                    textStyle.fontSize: 5
                horizontalAlignment: HorizontalAlignment.Right
                verticalAlignment: VerticalAlignment.Bottom
            }

            attachedObjects: [
                QTimer {
                    id: timer
                    property int f: 0
                    interval: 5000
                    onTimeout: {
                        progressIndicator.running = false;
                        netpost.imageFetcher();
                        netpost.newsFeedWebService("10");
                    }

                },
                PostHttp {

                    id: netpost
                    onComplete: {
                        progressIndicator.running = false;
                        progressIndicator.visible = false;
                        console.log("dsfdsafs"+netpost.model)
                        timer.stop();
                    }

                    onImageLoaded:{
                        console.log("value is image from cpp jhgsdh " + image)
                        imageviewid.setImageSource(image)
                    }
                    onNewsfeedComplete: {
                        console.log("response from newsfeed is "+info)
                        myListModel.append(info)

                    }
                }

            ]
        }

        onCreationCompleted: {
            // this slot is called when declarative scene is created
            // write post creation initialization here
            console.log("Page - onCreationCompleted()")

            // enable layout to adapt to the device rotation
            // don't forget to enable screen rotation in bar-bescriptor.xml (Application->Orientation->Auto-orient)
            OrientationSupport.supportedDisplayOrientation = SupportedDisplayOrientation.All;

            // populate list view model with the sample data
            timer.start();
            //                myListModel.load("app/native/assets/mydata.json")

        }
        ImageView {
            id: imageviewid
            imageSource: "asset:///images/4.png"
            enabled: true
            loadEffect: ImageViewLoadEffect.FadeZoom

        } 
    }
}
}

Please help me with this.

解决方案

So you've defined your slot with QVariant parameter however trying to emit it with QByteArray type which is returned by ImageConverter::encode() call.

Try to change that part of your code to this and give it a go:

QByteArray byteArray = bb::utility::ImageConverter::encode(QUrl(QDir::currentPath() + "/shared/camera/img.png"), imageData, 75);
QVariant image(byteArray);
emit imageLoaded(image);

Also, double check that everywhere where you declare/define this pair of signal/slot you're specified exactly the same parameter notation (ie const QVariant& in case of imageLoaded() signal and so on)

这篇关于在ImageView Blackberry 10中动态设置imageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆