Subclassing QSqlTableModel insert new value - sql

I want to show SQL data from a local db-File in a QML-Tableview and than would like to do some edits to the sql-database.
What I managed to do after about three weeks: Showing my data in a QML-Tableview. I am not sure if I really need to subclass QSqlTableModel and I definitly would be glad if subclassing would not be neccessary at all.
In my main.cpp following should create my model and directly add a record.
// Create an instance of the SqlModel for accessing the data
SqlDataModel *sqlModel;
sqlModel = new SqlDataModel(0,base.database());
sqlModel->setTable("diaBaneDatabase");
sqlModel->setSort(0, Qt::AscendingOrder);
sqlModel->setEditStrategy(QSqlTableModel::OnFieldChange);
sqlModel->select();
QSqlRecord record(sqlModel->record());
record.setValue(0,50);
record.setValue(3,222);
sqlModel->insertRecord(-1, record);
sqlModel->submitAll();
This should add 222 to the 4th column. But nothing will be stored in my sqlDatabase
My SqlDataModel::setData loolks like this:
bool SqlDataModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
qDebug() << index.column() << " " << index.row() << " " << value << " ---- " << role;
qDebug() << roles[Qt::UserRole + 1];
//qDebug() << QSqlTableModel::setData(modelIndex, value);
qDebug() << QSqlQueryModel::setData(index, value);
return false;
}
The output will be:
0 39 QVariant(int, 50) ---- 2
"id"
false
1 39 QVariant(QString, "") ---- 2
"id"
false
2 39 QVariant(QString, "") ---- 2
"id"
false
3 39 QVariant(int, 222) ---- 2
"id"
false
4 39 QVariant(double, 0) ---- 2
"id"
false
5 39 QVariant(int, 0) ---- 2
"id"
false
6 39 QVariant(double, 0) ---- 2
"id"
false
7 39 QVariant(double, 0) ---- 2
"id"
false
For sure my setData method is wrong but I don't understand what should happen there and I didn't find any example for this.
Am I wrong with my assumption that I need to subclass QSqlTableModel to be able to put the model through QQmlContext to QML and than show the columns with roles named like my column-namings? If not how could I put the content of column 1 to QMLTableview:
TableViewColumn {
role: "id" // what should be the role if I don't subclass???
title: "ID"
width: 80
}
I'm happy for any help, comment, example, other posts or whatever brings me further forward ... thanks

I've been working on an example.
Some notes:
QML items such as TableView require a model so I think a QSqlTableModel is a very good option. Of course, you have other models that could be used to handle items of data.
In the class MySqlTableModel you will see the required role names. MySqlTableModel reimplements roleNames() to expose the role names, so that they can be accessed via QML.
You could reimplement the setData method in MySqlTableModel, but I think it is better to use the method insertRecord provided by QSqlTableModel.
I hope this example will help you to fix your errors.
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "mysqltablemodel.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("mydb");
if(!db.open()) {
qDebug() << db.lastError().text();
return 0;
}
QSqlQuery query(db);
if(!query.exec("DROP TABLE IF EXISTS mytable")) {
qDebug() << "create table error: " << query.lastError().text();
return 0;
}
if(!query.exec("CREATE TABLE IF NOT EXISTS mytable \
(id integer primary key autoincrement, name varchar(15), salary integer)")) {
qDebug() << "create table error: " << query.lastError().text();
return 0;
}
MySqlTableModel *model = new MySqlTableModel(0, db);
model->setTable("mytable");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
QSqlRecord rec = model->record();
rec.setValue(1, "peter");
rec.setValue(2, 100);
model->insertRecord(-1, rec);
rec.setValue(1, "luke");
rec.setValue(2, 200);
model->insertRecord(-1, rec);
if(model->submitAll()) {
model->database().commit();
} else {
model->database().rollback();
qDebug() << "database error: " << model->lastError().text();
}
QQmlApplicationEngine engine;
QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("myModel", model);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
mysqltablemodel.h
#ifndef MYSQLTABLEMODEL_H
#define MYSQLTABLEMODEL_H
#include <QSqlTableModel>
#include <QSqlRecord>
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>
class MySqlTableModel : public QSqlTableModel
{
Q_OBJECT
public:
MySqlTableModel(QObject *parent = 0, QSqlDatabase db = QSqlDatabase());
Q_INVOKABLE QVariant data(const QModelIndex &index, int role=Qt::DisplayRole ) const;
Q_INVOKABLE void addItem(const QString &name, const QString &salary);
protected:
QHash<int, QByteArray> roleNames() const;
private:
QHash<int, QByteArray> roles;
};
#endif // MYSQLTABLEMODEL_H
mysqltablemodel.cpp
#include "mysqltablemodel.h"
MySqlTableModel::MySqlTableModel(QObject *parent, QSqlDatabase db): QSqlTableModel(parent, db) {}
QVariant MySqlTableModel::data ( const QModelIndex & index, int role ) const
{
if(index.row() >= rowCount()) {
return QString("");
}
if(role < Qt::UserRole) {
return QSqlQueryModel::data(index, role);
}
else {
return QSqlQueryModel::data(this->index(index.row(), role - Qt::UserRole), Qt::DisplayRole);
}
}
QHash<int, QByteArray> MySqlTableModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[Qt::UserRole + 1] = "name";
roles[Qt::UserRole + 2] = "salary";
return roles;
}
void MySqlTableModel::addItem(const QString &name, const QString &salary)
{
QSqlRecord rec = this->record();
rec.setValue(1, name);
rec.setValue(2, salary.toInt());
this->insertRecord(-1, rec);
if(this->submitAll()) {
this->database().commit();
} else {
this->database().rollback();
qDebug() << "database error: " << this->lastError().text();
}
}
main.qml
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
TableView {
id: tableView
anchors.fill: parent
TableViewColumn {
role: "name"
title: "Name"
width: 200
}
TableViewColumn {
role: "salary"
title: "Salary"
width: 200
}
model: myModel
}
Button {
id: addButton
anchors.verticalCenter: parent.verticalCenter
text: "Add item"
onClicked: {
if (nameBox.text || salaryBox.text) {
myModel.addItem(nameBox.text, salaryBox.text)
}
}
}
TextField {
id: nameBox
placeholderText: "name"
anchors.verticalCenter: parent.verticalCenter
anchors.left: addButton.right
anchors.leftMargin: 5
}
TextField {
id: salaryBox
placeholderText: "salary"
anchors.verticalCenter: parent.verticalCenter
anchors.left: nameBox.right
anchors.leftMargin: 5
}
}

Related

Port not bound SystemC (E112)

I am trying to implement a producer (master) speaking to a memory element (slave) through the memory controller (which implements the interface simple_mem_interface).
Note: Some functions details and include statements are not fully mentioned in the code attached.
Searching for bugs in the code.
Adding debugging tools to find the fault in Write Enable Port.
binding.cpp
int sc_main(int argc, char* argv[])
{
sc_signal<unsigned int> d_out,d_in,address_d;
sc_signal<bool> wen, ren, ack;
sc_clock ClkFast("ClkFast", 100, SC_NS);
sc_clock ClkSlow("ClkSlow", 50, SC_NS);
Memory_Controller Controller1 ("Controller");
d_out = Controller1.data_mem_read;
ren.write(Controller1.REN);
ack.write(Controller1.ack);
d_in.write(Controller1.data_write);
address_d.write(Controller1.address);
wen.write(Controller1.WEN);
producer P1("Producer");
P1.out(Controller1);
P1.Clk(ClkFast);
Memory_module MEM("Memory");
MEM.Wen(wen);
MEM.Ren(ren);
MEM.ack(ack);
MEM.Clock(ClkSlow);
MEM.data_in(d_in);
MEM.data_out(d_out);
MEM.address(address_d);
sc_start(5000, SC_NS);
return 0;
Memory_controller.h
#define MEM_SIZE 100
#include <interface_func.h>
class Memory_Controller : public sc_module, public simple_mem_if
{
public:
// Ports
sc_in <unsigned int> data_mem_read{ "Data_Read_from_Memory" };
sc_out<bool> REN { "Read_Enable" };
sc_out<bool> WEN { "Write_Enable" };
sc_out <bool> ack{ "ACK_Bool" };
sc_out<unsigned int> address{ "Memory_Address" }, data_write{
"Data_Written_to_Memory" };
// constructor
Memory_Controller(sc_module_name nm) : sc_module(nm)
{ // Creating a 2 dimentional array holding adresses and data
WEN.write(false);
REN.write(false);
ack.write(false);
}
~Memory_Controller() //destructor
{
}
bool Write(unsigned int address_i, unsigned int datum) // blocking write
{
WEN.write(true);
REN.write(false);
data_write.write(datum);
address.write(address_i);
if (ack == true)
return true;
else
return false;
}
bool Read(unsigned int address_i, unsigned int& datum_i) // blocking read
{
WEN.write(false);
REN.write(true);
datum_i=data_mem_read;
address.write(address_i);
if (ack == true)
return true;
else
return false;
}
void register_port(sc_port_base& port, const char* if_typename)
{
cout << "binding " << port.name() << " to "
<< "interface: " << if_typename << endl;
}
};
Memory.h
#define MEM_SIZE 100
#include "interface_func.h"
class Memory_module : public sc_module
{
public:
sc_in<bool> Wen,Ren;
sc_in <unsigned int> address, data_in ;
sc_in<bool> Clock;
sc_out <unsigned int> data_out;
sc_out <bool> ack;
bool fileinput = false;
ifstream myfile;
unsigned int item [MEM_SIZE];
Memory_module()
{
}
void Write() // blocking write
{
while (true)
{
wait();
if (Wen==true)
{
if (address >= MEM_SIZE || address < 0)
{
ack=false;
}
else
{
item[address]=data_in;
ack=true;
}
}
}
}
void Read() // blocking read
{
while (true)
{
wait();
if (Ren)
{
if (address >= MEM_SIZE || address < 0)
ack=false;
else
{
data_out.write(item[address]);
ack=true;
}
}
}
}
SC_CTOR(Memory_module)
{
SC_THREAD(Read);
sensitive << Clock.pos();
SC_THREAD(Write);
sensitive << Clock.pos();
}
};
interface_func.h
class simple_mem_if : virtual public sc_interface
{
public:
virtual bool Write(unsigned int addr, unsigned int data) = 0;
virtual bool Read(unsigned int addr, unsigned int& data) = 0;
};
After debugging the SystemC binder.cpp code, the following error arises:
(E112) get interface failed: port is not bound : port 'Controller.Write_Enable' (sc_out)
You cannot drive your unconnected ports in the Memory_Controller constructor. If you want to explicitly drive these ports during startup, move these calls to a start_of_simulation callback:
Memory_Controller(sc_module_name nm) : sc_module(nm)
{}
void start_of_simulation()
{
WEN.write(false);
REN.write(false);
ack.write(false);
}

GTKmm application: Gdk key press signals not firing

I have (sort of) copied (but with some modifications) the example in the GTKmm tutorials on keyboard events. (link)
https://developer.gnome.org/gtkmm-tutorial/stable/sec-keyboardevents-overview.html.en#keyboardevents-simple-example
Here is my code:
#include <gtkmm/application.h>
#include <gtkmm/window.h>
#include <gtkmm/textview.h>
#include <iostream>
class MainWindow
{
public:
MainWindow()
{
_window_.set_default_size(600, 400);
_window_.add(_textview_);
Glib::RefPtr<Gtk::TextBuffer> textbuffer_rp{_textview_.get_buffer()};
textbuffer_rp->set_text("some text here");
_textview_.set_monospace();
_window_.add_events(Gdk::KEY_PRESS_MASK);
_window_.show_all_children();
}
Gtk::Window &get_window()
{
return _window_;
}
protected:
bool on_key_press_event(GdkEventKey* event)
{
std::cout << "some keypress event" << std::endl;
if
(
(event->keyval == GDK_KEY_H) &&
((event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK) == GDK_CONTROL_MASK))
)
{
std::cout << "Hello world!" << std::endl;
}
if
(
(event->keyval == GDK_KEY_C) &&
((event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK) == GDK_CONTROL_MASK))
)
{
signal_textview_CTRL_C();
}
else if
(
(event->keyval == GDK_KEY_V) &&
((event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK) == GDK_CONTROL_MASK))
)
{
signal_textview_CTRL_V();
}
else
{
std::cout << "unhandled key" << std::endl;
}
return true;
}
void signal_textview_CTRL_C()
{
_text_register_0_ = "some text gets put here";
}
void signal_textview_CTRL_V()
{
Glib::RefPtr<Gtk::TextBuffer> textbuffer_rp{_textview_.get_buffer()};
textbuffer_rp->set_text(_text_register_0_);
}
private:
Gtk::Window _window_;
Gtk::TextView _textview_;
Glib::ustring _text_register_0_;
};
int main(int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
MainWindow mainwindow;
return app->run(mainwindow.get_window());
}
However it is not working - none of the signal events appear to fire when I press the key sequences CTRL-C, CTRL-V, CTRL-H.
I think I have stripped all the irrelevant stuff from the code so this should be a working MWE.
Connect your handler as first.
_window_.signal_key_press_event().connect(sigc::mem_fun(*this, &MainWindow::on_key_press_event), false);
Return false to let _textview_ get the key.
Your conditions are contradictory.
GDK_KEY_H is keysym for shift+h. Then you check (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK) == GDK_CONTROL_MASK). You are asking if state (which we know is with GDK_SHIFT_MASK) is ONLY GDK_CONTROL_MASK.
Code:
#include <gtkmm/application.h>
#include <gtkmm/window.h>
#include <gtkmm/textview.h>
#include <iostream>
class MainWindow
{
public:
MainWindow()
{
_window_.set_default_size(600, 400);
_window_.add(_textview_);
Glib::RefPtr<Gtk::TextBuffer> textbuffer_rp{_textview_.get_buffer()};
textbuffer_rp->set_text("some text here");
_textview_.set_monospace();
_window_.add_events(Gdk::KEY_PRESS_MASK);
_window_.signal_key_press_event().connect(sigc::mem_fun(*this, &MainWindow::on_key_press_event), false);
_window_.show_all_children();
}
Gtk::Window &get_window()
{
return _window_;
}
protected:
bool on_key_press_event(GdkEventKey* event)
{
std::cout << "some keypress event " << std::hex<<event->keyval<<" "<<std::hex<<event->state<<std::endl;
if
(
(event->keyval == GDK_KEY_h) &&
(event->state & GDK_CONTROL_MASK)
)
{
std::cout << "Hello world!" << std::endl;
return true;
}
if
(
(event->keyval == GDK_KEY_c) &&
(event->state & GDK_CONTROL_MASK)
)
{
std::cout<<"ctrl c"<<std::endl;
signal_textview_CTRL_C();
return true;
}
else if
(
(event->keyval == GDK_KEY_v) &&
(event->state & GDK_CONTROL_MASK)
)
{
std::cout<<"ctrl v"<<std::endl;
signal_textview_CTRL_V();
return true;
}
else
{
std::cout << "unhandled key" << std::endl;
}
return false;
}
void signal_textview_CTRL_C()
{
_text_register_0_ = "some text gets put here";
}
void signal_textview_CTRL_V()
{
Glib::RefPtr<Gtk::TextBuffer> textbuffer_rp{_textview_.get_buffer()};
textbuffer_rp->set_text(_text_register_0_);
}
private:
Gtk::Window _window_;
Gtk::TextView _textview_;
Glib::ustring _text_register_0_;
};
int main(int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
MainWindow mainwindow;
return app->run(mainwindow.get_window());
}

Qimages container

I’m looking for a class like QSprite, which takes responsibility for reading pixmaps from a source file, split the source image into sequence of images and return sub image by index.
Something like this:
class QSprite2
{
bool load(QUrl url, QSize frameSize);
QImage getFrame(int index);
};
Is there any way to get described functionality with existing classes. Or maybe I have to implement the describe logic by myself?
You can use QQuickImageProvider. Here's a class I wrote that does something similar:
SpriteImageProvider.h:
#ifndef SPRITEIMAGEPROVIDER_H
#define SPRITEIMAGEPROVIDER_H
#include <QHash>
#include <QImage>
#include <QString>
#include <QQuickImageProvider>
#include "IsleGlobal.h"
class ISLE_EXPORT SpriteImageProvider : public QQuickImageProvider
{
public:
SpriteImageProvider();
QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override;
private:
int parseFrameIndex(const QString &frameIndexStr) const;
int parseFrameWidth(const QString &frameWidthStr) const;
int parseFrameHeight(const QString &frameHeightStr) const;
QHash<QString, QImage> mImages;
};
#endif // SPRITEIMAGEPROVIDER_H
SpriteImageProvider.cpp:
#include "SpriteImageProvider.h"
#include <QImage>
#include <QDebug>
SpriteImageProvider::SpriteImageProvider() :
QQuickImageProvider(QQmlImageProviderBase::Image)
{
}
static const QRgb whiteRgba = qRgba(255, 255, 255, 255);
static const QRgb magentaRgba = qRgba(255, 0, 255, 255);
static const QRgb transparentRgba = qRgba(0, 0, 0, 0);
QImage SpriteImageProvider::requestImage(const QString &id, QSize *size, const QSize &)
{
QStringList args = id.split(QLatin1String(","));
if (args.length() < 1) {
qWarning() << "Must pass at least the file name as arguments for SpriteImageProvider source";
return QImage();
} else if (args.length() != 1 && args.length() != 2 && args.length() != 4) {
qWarning() << "Must pass either (fileName), (fileName, frameIndex) or"
<< "(fileName, frameWidth, frameHeight, frameIndex) as arguments for SpriteImageProvider source";
return QImage();
}
const QString imageFilename = ":/" + args.first();
int frameIndex = -2;
int frameWidth = -2;
int frameHeight = -2;
if (args.length() > 1) {
frameIndex = parseFrameIndex(args.last());
if (frameIndex == -1)
return QImage();
}
if (args.length() == 4) {
frameWidth = parseFrameIndex(args.at(1));
if (frameWidth == -1)
return QImage();
frameHeight = parseFrameIndex(args.at(2));
if (frameHeight == -1)
return QImage();
}
QHash<QString, QImage>::const_iterator it = mImages.find(imageFilename);
if (it == mImages.end()) {
QImage image(imageFilename);
if (image.isNull()) {
qWarning() << "Failed to load image at" << imageFilename;
return image;
}
// TODO: is there a better way of doing this?
QImage alphaImage = image;
for (int y = 0; y < alphaImage.height(); ++y) {
for (int x = 0; x < alphaImage.width(); ++x) {
const QRgb pixelRgb = alphaImage.pixel(x, y);
if (pixelRgb == whiteRgba || pixelRgb == magentaRgba)
alphaImage.setPixel(x, y, transparentRgba);
}
}
mImages.insert(imageFilename, alphaImage);
it = mImages.find(imageFilename);
}
if (frameWidth == -2 || frameHeight == -2) {
if (frameIndex == -2) {
// Use the whole image.
frameWidth = it.value().width();
frameHeight = it.value().height();
frameIndex = 0;
} else {
frameWidth = 64;
frameHeight = 64;
}
}
// Copy an individual frame out of the larger image.
const int framesWide = it.value().width() / frameWidth;
const QRect subRect((frameIndex % framesWide) * frameWidth,
(frameIndex / framesWide) * frameHeight,
frameWidth,
frameHeight);
// qDebug() << "id" << id;
// qDebug() << "framesWide" << framesWide;
// qDebug() << "subRect" << subRect;
const QImage frameImage = it.value().copy(subRect);
*size = frameImage.size();
return frameImage;
}
int SpriteImageProvider::parseFrameIndex(const QString &frameIndexStr) const
{
bool convertedToIntSuccessfully = false;
const int frameIndex = frameIndexStr.toInt(&convertedToIntSuccessfully);
if (!convertedToIntSuccessfully) {
qWarning() << "Failed to convert frame index" << frameIndexStr << "to an int";
return -1;
}
return frameIndex;
}
int SpriteImageProvider::parseFrameWidth(const QString &frameWidthStr) const
{
bool convertedToIntSuccessfully = false;
const int frameWidth = frameWidthStr.toInt(&convertedToIntSuccessfully);
if (!convertedToIntSuccessfully) {
qWarning() << "Failed to convert frame width" << frameWidthStr << "to an int";
return -1;
}
return frameWidth;
}
int SpriteImageProvider::parseFrameHeight(const QString &frameHeightStr) const
{
bool convertedToIntSuccessfully = false;
const int frameHeight = frameHeightStr.toInt(&convertedToIntSuccessfully);
if (!convertedToIntSuccessfully) {
qWarning() << "Failed to convert frame height" << frameHeightStr << "to an int";
return -1;
}
return frameHeight;
}
It also supports "alpha keys" - white and magenta pixels in the source image will be turned into transparent pixels.
It's registered with the QML engine like this:
mEngine->addImageProvider("sprite", new SpriteImageProvider);
and used in QML like this:
import QtQuick 2.5
Image {
source: qsTr('image://sprite/sprites/hugh.png,%1').arg(_sceneItemComponent ? _sceneItemComponent.facingDirection : 0)
}
where facingDirection is the frame index to use. There are also other arguments you can pass that are mentioned in the .cpp file.

How to notify ListView that DataModel has changed

I created a ListView and I want to use it with a custom DataModel. However, I have a problem: at the moment the view gets created, I don't have the data loaded into the model. The model data is set after the view is created and when I set the data onto the model, the view doesn't update and doesn't read again the model data. This is my ListView:
ListViewCountainer.qml
Container {
// countryModelData is set after ListViewCountainer gets created
// when countryModelData gets set, the model is populated with data
property variant countryModelData
leftPadding: 20.0
rightPadding: 20.0
topPadding: 20.0
bottomPadding: 20.0
CountryDetailsListView {
id: countryDetailsListView
dataModel: CountryDataModel {
countryData: countryModelData
}
}
}
And here is my model:
countrydatamodel.h
#ifndef COUNTRYDATAMODEL_H_
#define COUNTRYDATAMODEL_H_
#include <QtCore/QAbstractListModel>
#include <QtCore/QList>
#include <QObject>
#include <QtCore/QVariant>
#include <bb/cascades/DataModel>
#include <bb/data/JsonDataAccess>
class CountryDataModel : public bb::cascades::DataModel
{
Q_OBJECT
Q_PROPERTY(QVariant countryData READ getCountryData WRITE setCountryData)
public:
CountryDataModel(QObject* parent = 0);
virtual ~CountryDataModel();
Q_INVOKABLE int childCount(const QVariantList& indexPath);
Q_INVOKABLE QVariant data(const QVariantList& indexPath);
Q_INVOKABLE bool hasChildren(const QVariantList& indexPath);
Q_INVOKABLE QString itemType(const QVariantList& indexPath);
Q_INVOKABLE void removeItem(const QVariantList& indexPath);
Q_INVOKABLE QVariant getCountryData();
Q_INVOKABLE void setCountryData(QVariant data);
private:
QVariantList m_elements;
};
#endif /* COUNTRYDATAMODEL_H_ */
countrydatamodel.cpp
#include <src/countrydatamodel.h>
#include <QtCore/QtAlgorithms>
#include <QtCore/QDebug>
#include <bb/cascades/DataModel>
#include <bb/data/JsonDataAccess>
CountryDataModel::CountryDataModel(QObject* parent) : bb::cascades::DataModel(parent)
{
}
CountryDataModel::~CountryDataModel()
{
}
bool CountryDataModel::hasChildren(const QVariantList &indexPath)
{
qDebug() << "==== CountryDataModel::hasChildren" << indexPath;
if ((indexPath.size() == 0))
{
return true;
}
else
{
return false;
}
}
int CountryDataModel::childCount(const QVariantList &indexPath)
{
qDebug() << "==== CountryDataModel::childCount" << indexPath;
if (indexPath.size() == 0)
{
qDebug() << "CountryDataModel::childCount" << m_elements.size();
return m_elements.size();
}
qDebug() << "==== CountryDataModel::childCount" << 0;
return 0;
}
QVariant CountryDataModel::data(const QVariantList &indexPath)
{
qDebug() << "==== CountryDataModel::data" << indexPath;
if (indexPath.size() == 1) {
return m_elements.at(indexPath.at(0).toInt());
}
QVariant v;
return v;
}
QString CountryDataModel::itemType(const QVariantList &indexPath)
{
Q_UNUSED(indexPath);
return "";
}
void CountryDataModel::removeItem(const QVariantList& indexPath)
{
if(indexPath.size() == 1) {
m_elements.removeAt(indexPath.at(0).toInt());
}
emit itemRemoved(indexPath);
}
QVariant CountryDataModel::getCountryData()
{
return QVariant(m_elements);
}
void CountryDataModel::setCountryData(QVariant data)
{
m_elements = data.toList();
qDebug() << "================== CountryDataModel: " << m_elements;
}
I put some debug messages in the childCount function for example and it gets called only once, which means that the ListView asks the model for the data just once, when the model is created.
Is it possible to force ListView to read again the data from the model after the model gets populated with data? Or how could I make this approach work and load the data in the view?
Thanks!
In order for the model to be updated, the setCountryData member function needs to be updated like so:
void CountryDataModel::setCountryData(QVariant data)
{
m_elements = data.toList();
emit itemsChanged(bb::cascades::DataModelChangeType::AddRemove, QSharedPointer< bb::cascades::DataModel::IndexMapper >(0));
}
FML...
You need to declare a signal for the property you want to update in backend.
Q_PROPERTY(QVariant countryData READ getCountryData WRITE setCountryData NOTIFY contryDataChanged)
add its declaration as well.
Then you say -
emit contryDataChanged();
wherever you feel like list should re-read contents. (normally setter methods).

SimCardInfo issue on Blackberry10

I'd like to display/get a read on IMSI (tested it on Dev Alpha B). The issue is that I could get a read on others property of SimCardInfo such as Mobile Network Code, Mobile Country Code, Serial Number but IMSI (subscriberIdentifier).
Here is the code
main.cpp
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/device/HardwareInfo>
#include <bb/device/SimCardInfo>
#include <QLocale>
#include <QTranslator>
#include <Qt/qdeclarativedebug.h>
using namespace bb::cascades;
using namespace bb::device;
Q_DECL_EXPORT int main(int argc, char **argv)
{
qmlRegisterUncreatableType<bb::device::HardwareInfo>("bb.device", 1, 0, "HardwareInfo", "");
qmlRegisterUncreatableType<bb::device::SimCardInfo>("bb.device", 1, 0, "SimCardInfo", "");
// this is where the server is started etc
Application app(argc, argv);
// localization support
QTranslator translator;
QString locale_string = QLocale().name();
QString filename = QString( "hwinfo_%1" ).arg( locale_string );
if (translator.load(filename, "app/native/qm")) {
app.installTranslator( &translator );
}
//create object
HardwareInfo hwInfo;
SimCardInfo simcardInfo;
QmlDocument *qml = QmlDocument::create("asset:///main.qml");
qml->setContextProperty("_hardware", &hwInfo);
qml->setContextProperty("_simcardinfo", &simcardInfo);
// create root object for the UI
AbstractPane *root = qml->createRootObject<AbstractPane>();
// set created root object as a scene
Application::instance()->setScene(root);
// we complete the transaction started in the app constructor and start the client event loop here
return Application::exec();
// when loop is exited the Application deletes the scene which deletes all its children (per qt rules for children)
}
main.qml file
import bb.cascades 1.0
import bb.device 1.0
Page
{
Container
{
leftPadding: 20
topPadding: 20
Container
{
topMargin: 10
layout: StackLayout
{
orientation: LayoutOrientation.LeftToRight
}
Button
{
text: "retrieve"
onClicked:
{
lbl0.text = "Model name: " + _hardware.modelName
lbl1.text = "IMEI: " + _hardware.imei
lbl2.text = "IMSI: " + _simcardinfo.subscriberIdentifier
lbl3.text = "SN: " + _simcardinfo.serialNumber
lbl4.text = "Mobile Network Code: " + _simcardinfo.mobileNetworkCode
lbl5.text = "Mobile Country Code: " + _simcardinfo.mobileCountryCode
}
}
}
Container
{
layout: StackLayout {
}
Label
{
id:lbl0
}
Label
{
id:lbl1
}
Label
{
id:lbl2
}
Label
{
id:lbl3
}
Label
{
id:lbl4
}
Label
{
id:lbl5
}
}
}
}
Any help is much appreciated.
reference
http://developer.blackberry.com/cascades/reference/bb_device_simcardinfo.html
You're declaring hwInfo and simCardInfo as stack variables, that means that after the constructor ends both variables no longer exist, so when the QML runtime tries to access the properties you assigned to them it just can't.
To make it work you need to declare those variables as heap variables so they can outlive their scope.
HardwareInfo* hwInfo = new HardwareInfo();
SimCardInfo* simcardInfo = new SimCardInfo();
qml->setContextProperty("_hardware", hwInfo);
qml->setContextProperty("_simcardinfo", simcardInfo);