First i created a new c++ class with a member function, which is giving back a string:
#ifndef TESTNAME_H
#define TESTNAME_H
#include <QObject>
#include <QString>
#include <QVariant>
class testname : public QObject
{
Q_OBJECT;
public:
testname();
Q_INVOKABLE QString getName();
};
#endif // TESTNAME_H
#include "testname.h"
testname::testname()
{
}
QString testname::getName() {
return "sometext";
}
I have a qml file with only a text in the middle, like this:
import QtQuick 1.1
Rectangle {
width: 360
height: 360
Text {
id: text1
anchors.centerIn: parent
text: testqml
font.pixelSize: 12
}
}
Notice that the property "text" is a variable named "testqml". This variable contains the string returned by the function of the class i showed above. The code for this is in the main.cpp:
#include <QApplication>
#include "qmlapplicationviewer.h"
#include <testname.h>
#include <QDeclarativeContext>
#include <QDebug>
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
// Create instance of "testname"
testname *test = new testname;
QmlApplicationViewer viewer;
viewer.rootContext()->setContextProperty("testqml", test->getName());
viewer.addImportPath(QLatin1String("modules"));
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/classtest/main.qml"));
viewer.showExpanded();
return app->exec();
}
Using the setContextProperty-Function, the returned string is exposed to the qml file and is correctly shown in the running program.
But i'm actually intending to inherit a model for a GridView. So i created a Gridview with one list element in QML:
import QtQuick 1.1
Rectangle {
width: 360
height: 360
GridView {
id: grid_view1
anchors.centerIn: parent
width: 140
height: 140
cellHeight: 70
delegate: Item {
x: 5
height: 50
Column {
spacing: 5
Rectangle {
width: 40
height: 40
color: colorCode
anchors.horizontalCenter: parent.horizontalCenter
}
Text {
x: 5
text: name
anchors.horizontalCenter: parent.horizontalCenter
font.bold: true
}
}
}
model: ListModel {
ListElement {
name: testqml
colorCode: "grey"
}
}
cellWidth: 70
}
}
The variable "testqml" is now in the "name" Field of the List, which is in the example a string. If i use a string "likethis", it is correctly displayed. But if i run my program (main.cpp and class are remaining unchanged) i get this error:
ListElement: cannot use script for property value
name: testqml
^
Now i'm stuck. I found an reported bug with a similar issue #QTBUG-16289, but i don't know how to solve my problem. Any ideas, how-tos, tutorials or something to solve my problem?
Thanks and regards :)
I ran your code and reproduced your error but what are you ultimately trying to do?
Your delegate indicates that you want to inject a number of model items with name and color from C++, otherwise, why use a GridView, correct?
If that is not the case then perhaps what follows will not be that useful, or perhaps some variant of it might be. So I went ahead and constructed an example of what I thought you might be trying to accomplish.
In summary, on my system, after creating an arbitrary number of model items (in this case 20), the scrollable GridView delegate (midway along the scroll range) looks like this:
As I said, it seems that you want to inject a number of QString items from a C++ model into a QML GridView, noting that using a GridView implies that you would like to have a number of items. In most cases you will want to inherit from a pre-defined Qt Model, which automatically takes care of several important details like keeping the QML views in-sync with the model, and automatically updating the views when items are removed or new ones are added.
With this in mind, the QAbstractListModel is a convenient Class from which to base your model (this is not the only option though, see the help files). At first glance, setting up this model can appear complicated, so I went ahead and defined a minimal version which I hope illustrates what you want to do.
Below is the code for the model (note: I put all of the code in the .h file so no .m file is needed). I also created some "Items" to inject into the model, for simplicity, a struct Item is used as defined below, but these could easily be instances of another suitably defined Class:
#include <QString>
#include <QColor>
#include <QDebug>
#include <QAbstractListModel>
// Create an Item so we have something to put in the model:
struct Item {
QString name;
QString color;
};
class testname : public QAbstractListModel
{
Q_OBJECT
public:
explicit testname(QObject *parent = 0) : QAbstractListModel(parent)
{
// Create some items and then add to the model:
int N = 20;
QStringList colorNames = QColor::colorNames();
Item* items = new Item[N];
for (int i = 0; i < N; i++) {
items[i].name = QString("item"+QString::number(i));
items[i].color = colorNames[i];
//qDebug() << items[i].name << "; " << items[i].color;
_model<<items[i];
}
}
// enum DataRoles for QAbstractListModel:
enum DataRoles {
NameRole = Qt::UserRole + 1,
ColorRole
};
// addData() method for QAbstractListModel:
void addData(const Item& entry) {
beginInsertRows(QModelIndex(), rowCount(), rowCount());
_model << entry;
endInsertRows();
}
// rowCount() method for QAbstractListModel:
int rowCount(const QModelIndex & parent = QModelIndex()) const {
return _model.count();
}
// data() required for QAbstractListModel:
QVariant data(const QModelIndex & index, int role) const {
if ( !index.isValid() || index.row() < 0 || index.row() >= _model.count() )
return QVariant();
Item modelEntry = _model[index.row()];
if (role == NameRole) {return modelEntry.name;}
if (role == ColorRole) {return modelEntry.color;}
return QVariant();
}
// roleNames() method for QAbstractListModel:
QHash<int,QByteArray> roleNames() const {
QHash<int, QByteArray> roles;
roles[NameRole] = "Name";
roles[ColorRole] = "Color";
return roles;
}
private:
// Below are the model items:
QList<Item> _model;
};
Next is the QML code which uses the C++ model defined above and registered as "testqml" in main.cpp, and then defined through the property, model: in GridView.
Note that in the delegate that the Color and Name properties of the model are defined as role names in the class above (these could be any label you like). To help visualize what is going on, the model roles are very similar to the columns of a table, with the row entries corresponding to the model items:
import QtQuick 1.1
Rectangle {
width: 360
height: 360
/* ------------------- */
GridView {
id: grid_view1
anchors.centerIn: parent
width: 140; height: 140
cellHeight: 70
delegate: delegateItem
model: testqml // the C++ model is set here
cellWidth: 70;
}
/* ------------------- */
Component {
id: delegateItem
Item {
x: 5; height: 50
Column {
spacing: 5
Rectangle {
width: 40; height: 40;
color: Color // Note: this a role defined in the C++ model
anchors.horizontalCenter: parent.horizontalCenter
}
Text {
x: 5;
text: Name // Note: this is another role defined in the C++ model
anchors.horizontalCenter: parent.horizontalCenter
font.bold: true
}
}
}
} // end delegateItem
} // end Rectangle
And then my main.cpp is nearly the same as yours, I'll go ahead and post it to avoid any confusion:
#include "qtquick1applicationviewer.h"
#include <QApplication>
#include "testname.h"
#include <QDeclarativeContext>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
testname *test = new testname();
QtQuick1ApplicationViewer viewer;
viewer.rootContext()->setContextProperty("testqml",test);
viewer.addImportPath(QLatin1String("modules"));
viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/QMLSetProperty/main.qml"));
viewer.showExpanded();
return app.exec();
}
Hope this helps!
Related
I have some data structure updated in c++ layer. I have to display it in qml and save changes from qml layer to c++ structures. I hope there is a declarative approach to do it but I in desperate to find it.
Here is the part of code:
C++ header:
#ifndef NODEINFO_H
#define NODEINFO_H
#include <QObject>
#include <QString>
class NodeInfo : public QObject {
Q_OBJECT
Q_PROPERTY(QString label READ label WRITE setLabel NOTIFY labelChanged)
public:
NodeInfo(QObject *parent = 0);
virtual ~NodeInfo() {}
const QString& label() const;
void setLabel(const QString& val);
signals:
void labelChanged();
private:
QString d_label;
};
#endif // NODEINFO_H
C++ body:
#include "nodeinfo.h"
#include <QDebug>
NodeInfo::NodeInfo(QObject *parent) : QObject(parent), d_label("Test string") {
}
const QString &NodeInfo::label() const {
qDebug() << "NodeInfo::label: getter";
return d_label;
}
void NodeInfo::setLabel(const QString &val) {
qDebug() << "NodeInfo::label: setter - " << val;
d_label = val;
emit labelChanged();
}
main.cpp
#include <QGuiApplication>
#include <QDebug>
#include <QQmlContext>
#include <QQuickView>
#include <QQmlApplicationEngine>
#include "nodeinfo.h"
int main(int argc, char *argv[]) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
// qmlRegisterType<NodeInfo>("NodeInfo", 1, 0, "NodeInfo");
NodeInfo nodeDescr;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("nodeData", &nodeDescr);
const QUrl url(QStringLiteral("qrc:/main.qml"));
engine.load(url);
QObject *root = engine.rootObjects().value(0);
if (QWindow *window = qobject_cast<QWindow *>(root))
window->show();
else
return -1;
return app.exec();
}
Qml code:
import QtQuick 2.15
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
ApplicationWindow {
id: root
width: 360
height: 520
visible: true
// property alias a_label: nodeData.label
Column {
anchors.fill: parent
TextInput {
id: simpleTxt
text: nodeData.label
}
Text {
id: txt
text: nodeData.label
}
Button {
text: "writeProp"
onClicked: nodeData.label = simpleTxt.text
}
// Binding {
// target: nodeData
// property: "label"
// value: simpleTxt.text
// }
}
}
So when I'm editing text in TextInput it should automatically set property in c++ code but it do not. Only if I press button.
There is the Binding way as you see in comments and it works but I it's not a true way I hope.
Let's imagine if I have 15-30 or more data fields in my c++ structure and it's full rubbish if I must do 30 Bindings such way or if I need to write signal/slot on each data field and connect them.
But what is right way?
Any ideas appreciated
A simpler solution is to assign the signal associated to the property text:
Text {
id: txt
text: nodeData.label
onTextChanged: {
if(nodeData.label != simpleTxt.text)
nodeData.label = simpleTxt.text
}
}
text: nodeData.label sets binding nodeData.label --> text (one direction). I.e. text is updated whenever nodeData.label is changed. When the user types some text in the field, this binding is destroyed.
So if you want to update nodeData.label when the user changes text, you need to use onTextChaged event.
Text {
onTextChanged: nodeData.label = text
}
One more note: you need to check if the property is really changed before emitting the appropriate changed signal. So the code should be something like this:
void NodeInfo::setLabel(const QString &val) {
qDebug() << "NodeInfo::label: setter - " << val;
if (d_label != val)
{
d_label = val;
emit labelChanged();
}
}
This will prevent your code from endless binding loops.
I am connecting a ProgressBar to two Buttons. The ProgressBar will do a computation of a loop as soon as I push the button. The computation will be erased if I will push the other button. I still haven't implemented the pause button.
The print screen of what I am trying to achieve is below and in case needed the whole code of the minimal verifiable example is available here:
The problem is that as soon as I connect the ProgressBar with my main.cpp file I have a bunch of errors all that look like the following:
class ProgressDialog has no member named...
code is below:
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include "progressbardialog.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQuickView view;
ProgressBarDialog progressDialog;
// One way but it does not work
// engine.rootContext()->setContextProperty("control", QVariant::fromValue(progressDialog.refModel()));
// Another way but this also does not work
view.setSource(QUrl::fromLocalFile("main.qml"));
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
progressbardialog.h
#ifndef PROGRESSBARDIALOG_H
#define PROGRESSBARDIALOG_H
#include <QObject>
#include <QFutureWatcher>
class ProgressBarDialog : public QObject
{
Q_OBJECT
Q_PROPERTY(float progress READ progress WRITE setProgress NOTIFY progressChanged)
public:
ProgressBarDialog();
float progress(int &iterator);
// I will use this as a reference to pass to main.cpp using setContextProperty()
QObject &refModel()
{
return m_Model;
}
public Q_SLOTS:
void startComputation();
void cancelComputation();
signals:
void progressChanged();
private:
int m_progressValue;
QObject m_Model;
QFutureWatcher<void> m_futureWatcher;
};
#endif // PROGRESSBARDIALOG_H
progressbardialog.cpp
#include "progressbardialog.h"
#include <QtConcurrent/QtConcurrentMap>
ProgressBarDialog::ProgressBarDialog()
{}
void spin(int &iteration)
{
const int work = 1000 * 1000 * 40;
volatile int v = 0;
for(int j = 0; j < work; ++j)
++v;
}
float ProgressBarDialog::progress(int &iterator)
{
(void) iterator;
const int work = 1000 * 1000 * 40;
volatile int v = 0;
for(int j = 0; j < work; ++j)
++v;
emit progressChanged();
}
void ProgressBarDialog::startComputation()
{
// Prepare the vector
QVector<int> vector;
for(int i = 0; i < 40; ++i)
vector.append(i);
const QFuture<void> future = QtConcurrent::map(vector, spin);
m_futureWatcher.setFuture(future);
}
void ProgressBarDialog::cancelComputation()
{
m_futureWatcher.cancel();
}
and finally the main.qml
import QtQuick 2.12 // for the Item
import QtQuick.Controls 2.12 // for ApplicationWindow
import QtQuick.Layouts 1.12
ApplicationWindow {
visible: true
width: 440
height: 480
title: qsTr("Progress Bar")
ColumnLayout {
spacing: 10
width: parent.width
GroupBox {
id: box1
title: "Start - Stop"
font.pointSize: 20
Layout.alignment: parent.width
spacing: 10
GridLayout {
width: parent.width
columns: 1
RowLayout {
spacing: 200
Layout.fillWidth: true
Layout.fillHeight: false
Button {
id: buttonStart
text: "Start"
font.pointSize: 15
enabled: !progressDialog.active
onClicked: progressDialog.startComputation()
}
Button {
id: buttonFinish
text: "Finish"
font.pointSize: 15
enabled: progressDialog.cancelComputation()
}
}
}
}
GroupBox {
id: boxprogress
title: "Progressbar"
font.pointSize: 20
Layout.alignment: parent.width
spacing: 10
GridLayout {
width: parent.width
columns: 1
RowLayout {
Layout.fillWidth: true
Layout.fillHeight: false
ProgressBar {
id: progressbar_id
Layout.fillWidth: true
Layout.fillHeight: true
width: parent.width
// These are hard-coded values to confirm it is working
from: 0
to: 100
value: 5
onValueChanged: {
console.log("Progressbar value changed: ", progressbar_id.value)
}
onVisibleChanged: {
console.log("Progressbar visibility changed: ", progressbar_id.visible)
}
}
Connections {
target: progressDialog
onProgressChanged: progressbar_id.value = progress;
}
// This is working if clicking on the progressbar
MouseArea {
anchors.fill: parent
onClicked: progressbar_id.value += 5;
}
}
}
}
}
}
What I tried so far :
1) In order to prove myself that the ProgressBarDialog is correctly working I tried it before as a stand alone main.qml using hard-coded values (which I left in the code so you can see what I have done). But as soon as I started implementing it in the .cpp file and setting the Q_PROPERTY I received all the errors I posted on the second screenshot.
2) I am sure about the procedure taken so far because: a) According to the official documentation and from this post because I will need to check the process of a long running operations; b) According to QtConcurrent the process has a better possibility to be checked, and that is exactly what I did using QtConcurrent::map()
3) I am using the following statement in the progressbardialog.h to make sure that the object is correctly connected and listens to the QML file:
QObject &refModel()
{
return m_Model;
}
But this did n't show and substancial improvements. Therefore digging more into the process I was thinking that it should have been the case to use setContextProperty(), whih cled me to the next point.
4) According to the official documentation and according to this post here I thought I would have fix the error, but it still remains.
I am runnign out of ideas and anyone who may have had this problem, please point to the right direction for a possible solution.
Q_PROPERTY is designed to easier read/write/react to variable change (C++ side) on the QML side. To complete your example with variable read/write/notify add correct getter/setter (signal is already ok).
float progress();
void setProgress(float);
If you want to call a function from QML mark it Q_INVOKABLE instead.
Also what is the point of volatile in your code?
So to sum up, mark your iteration function as a Q_INVOKABLE. It will increment some internal progress value and then emit progressChanged(). This should cause QML side to update.
So I'm new to Qt and I'm trying to improve my C++ skills, so I decided to start a project where I can search items in a QStringList using a textfield. I got the search function working and I was able to move the result of the search into another QStringList, where I can use it to display to the user in a function that is declared as a "public slot".
The main Idea is that the list will auto update as soon as the user enters a character into the textfield, which it already does. So I managed to get the resulted list into the Slot function to be able to display a different list every time and character gets typed in the textfield.
In the function where I pass in the list of search results, I am trying to use this
m_context->setContextProperty("resultModel",QVariant::fromValue(m_resultList));
where resultModel is the name of my model in QML and m_resultList is where the results of the search are being stored, to display the list in the ListView. My program compiles but it crashes after I run it.
So, my true question is: Is there any way that I can display a C++ QStringList not in the main.cpp into a QML ListView?
The reason why I'm asking for it to not be in the main is because I tried to use that same line above in the main.cpp with a hard coded QStringList and the list was able to display, so there must be an issue with it not being in the main. Also because I would not be able to use the slot function in SearchClass to auto update.
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
#include "searchclass.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<SearchClass>("b9c.backend", 1, 0, "BackEnd");
QQmlApplicationEngine engine;
SearchClass obj;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QQmlContext *context = engine.rootContext();
obj.getContext(context);
//the line below works if provided with a qstringlist
//context->setContextProperty("resultModel", QVariant::fromValue(resultList));
return app.exec();
}
SearchClass.h
#ifndef SEARCHCLASS_H
#define SEARCHCLASS_H
#include <QObject>
#include <QQmlContext>
class SearchClass : public QObject
{
Q_OBJECT
Q_PROPERTY(QString userSearch READ userSearch WRITE setUserSearch NOTIFY userSearchChanged)
public:
SearchClass(QObject *parent = 0);
QStringList resultList;
QString userSearch();
void setUserSearch(QString &userSearch);
void getFilenameAndInput(QString inputString);
QString CompareInputAndFilename(QString inputString, QString filename);
QStringList getFileName();
//get context
void getContext(QQmlContext *context);
signals:
void userSearchChanged();
public slots:
void setUserSearch();
private:
QStringList m_resultList;
QString m_userSearch;
QQmlContext* m_context;
};
#endif // SEARCHCLASS_H
SearchClass.cpp
#include "searchclass.h"
#include <QDebug>
#include <QQmlContext>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
SearchClass::SearchClass(QObject *parent) : QObject(parent)
{
connect(this, SIGNAL(userSearchChanged()), this, SLOT(setUserSearch()));
}
//the result should be displayed in this SLOT when ever the user types in a character into the textfield
void SearchClass::setUserSearch(){
qDebug() << "SLOT: " << m_resultList;
//The line below makes the program crash. It works when implemented in the main.cpp
// m_context->setContextProperty("resultModel", QVariant::fromValue(m_resultList));
}
QString SearchClass::userSearch()
{
return m_userSearch;
}
void SearchClass::setUserSearch(QString &userSearch)
{
if (userSearch == m_userSearch)
return;
m_userSearch = userSearch;
qDebug() << "Input: " <<m_userSearch;
getFilenameAndInput(m_userSearch);
emit userSearchChanged();
}
QStringList SearchClass::getFileName(){
//Returns the items that will be searched for...
}
void SearchClass::getFilenameAndInput(QString inputString){
//Puts the search results into class variable m_resultList...
m_resultList = resultList;
}
QString SearchClass::CompareInputAndFilename(QString inputString, QString filename){
//Search processing...
}
//gets context to use setProperty in the above signal, but it crashes
void SearchClass::getContext(QQmlContext *context){
m_context = context;
}
main.qml
import QtQuick 2.6
import QtQuick.Controls 2.0
import b9c.backend 1.0
import QtQuick.Window 2.2
ApplicationWindow {
id: root
width: 300
height: 480
visible: true
BackEnd { id: backend }
TextField {
id: txtfield
text: backend.userSearch
placeholderText: qsTr("Search...")
width: parent.width
onTextChanged: backend.userSearch = text
}
ListView {
id:view
height: parent.height
width: parent.width
y: 5 + txtfield.height
model: resultModel
delegate: Rectangle {
border.color: "lightblue"
height: 25
width: parent.width
Text {
anchors.centerIn: parent
text: modelData
}
}
}
}
You are doing it wrong. In every possible way. You even name getContext() the function that actually sets the context.
m_resultList is never set to anything in that code you have provided. So there is no way to tell you why your application is crashing, because the actual data is a mystery.
You also have a QObject derived class - your SearchClass. So you should expose that as a context property, and then have the string list interfaced to QML by being implemented as a Q_PROPERTY of SearchClass.
Here is a simple example:
// the equivalent of your SearchClass
class Test : public QObject {
Q_OBJECT
Q_PROPERTY(QStringList model MEMBER m_model NOTIFY modelChanged)
QStringList m_model;
public slots:
void setModel(QString m) {
m_model = m.split(" ");
modelChanged();
}
signals:
void modelChanged();
};
// in main.cpp
Test t;
engine.rootContext()->setContextProperty("Test", &t);
// in main.qml
Column {
TextField {
onTextChanged: Test.setModel(text)
}
ListView {
width: 200; height: 300
spacing: 5
model: Test.model
delegate: Rectangle {
height: 25
width: 200
color: "lightgray"
Text { text: modelData; anchors.centerIn: parent }
}
}
}
As you type the text string is sent to Test::setModel(), which then splits it into space separated tokens and sets the QStringList, which is used as a model source for the list view.
I'm trying out something in QML to try and make it alittle easier to merge the two more seamlessly; to be precise, I'm trying to link an object with structured data to QML.
I have the following setup:
main.cpp:
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include "dataobject.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<DataObject>("DO", 1,0,"DataObject");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
dataobject.h:
#ifndef DATAOBJECT_H
#define DATAOBJECT_H
#include <QObject>
#include <QVariant>
#include <iostream>
class DataObject : public QObject
{
Q_OBJECT
Q_PROPERTY(qreal a MEMBER a NOTIFY aChanged)
Q_PROPERTY(qreal b MEMBER b NOTIFY bChanged)
public:
explicit DataObject(QObject *parent = 0);
signals:
void aChanged();
void bChanged();
public slots:
void printState() {
using namespace std;
cout << a << ", " << b << endl;
}
private:
qreal a;
qreal b;
};
#endif // DATAOBJECT_H
dataobject.cpp:
#include "dataobject.h"
DataObject::DataObject(QObject *parent) :
QObject(parent)
{
connect(this, SIGNAL(aChanged()), this, SLOT(printState()));
connect(this, SIGNAL(bChanged()), this, SLOT(printState()));
}
main.qml:
import DO 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
menuBar: MenuBar {
Menu {
title: qsTr("File")
MenuItem {
text: qsTr("Exit")
onTriggered: Qt.quit();
}
}
}
Text {
text: qsTr("Hello World")
MouseArea {
property DataObject myData;
anchors.fill: parent
drag.target: parent
onReleased: {
myData.a = mouse.x;
myData.b = mouse.y;
}
}
}
}
qml.qrc:
<RCC>
<qresource prefix="/">
<file>main.qml</file>
</qresource>
</RCC>
Now, what I'd hoped was that values generated by QML could be feed into a object in C++ directly (i.e. the onReleased handler in the MouseArea trying to write to the myData field). However, this basic proof of concept doesn't work, but I don't really understand why.
The error I get (on drag and release of the mouse button) is:
qrc:///main.qml:29:TypeError:Type error
Which matches up with the line "myData.a = mouse.x;", so it fails straight away.
Any idea's where I'm going wrong? I've tried with the fields being int, double, QVariant, and qreal, none of which have worked. Is in a fundamental inability in QML to link objects like that? If so, any idea how, for example, anchors.fill is implemented in the Qt source code?
It helps if you break down the expression on the line where the error is coming from. Try just printing myData.a first:
print(myData.a)
myData.a = mouse.x;
myData.b = mouse.y;
qrc:///main.qml:31: TypeError: Cannot read property 'a' of null
So, myData is null. We can verify this with another QObject-based type:
MouseArea {
property DataObject myData;
property Item item
anchors.fill: parent
drag.target: parent
onReleased: {
print(item)
myData.a = mouse.x;
myData.b = mouse.y;
}
}
qml: null
So, you can fix this error by initialising the property:
property DataObject myData: DataObject {}
You can think of QObject-based properties as pointers for JavaScript; they can be null or point to a valid object... or be undefined. :) I can't find anything mentioned about this here, but that's where this behaviour should be mentioned.
If you'd like to simplify things, you can have the object default-constructed for you by making it a child object of the MouseArea, rather than a property:
MouseArea {
DataObject {
id: myData
}
anchors.fill: parent
drag.target: parent
onReleased: {
myData.a = mouse.x;
myData.b = mouse.y;
}
}
Currently, you won't be able to refer to this property from C++. However, you can achieve this in two ways:
Declare a property alias to the item.
Give it an objectName and use QObject::findChild to find it.
I'm just beginning to learn C++ and Qt Framework in particular and I already have a problem right there. The question is how do I create and display data which is not just a string but rather an object, which properties I can access and display. E.g I have a list of employees and I want to display a list which looks like this:
---------------------
John Smith
Salary: 50,230
---------------------
Max Mustermann
Salary: 67,000
---------------------
The goal is that each item in the list is clickable and opens a new window with the details. Also, the important part is that I can be able to style the properties differently.
Qt provide us model and view frameworks, it is pretty flexible.
You could save your data by "model", show the data of your "model" by "view"
and determine how to play your data by "delegate"
The codes of c++ is a little bit verbose, so I use qml from the document to express the idea
import QtQuick 2.1
import QtQuick.Window 2.1
import QtQuick.Controls 1.0
Rectangle {
width: 640; height: 480
//the new window
Window{
id: newWindow
width: 480; height:240
property string name: ""
property string salaryOne: ""
property string salaryTwo: ""
Rectangle{
anchors.fill: parent
Text{
id: theText
width:width; height: contentHeight
text: newWindow.name + "\nSalaryOne : " + newWindow.salaryOne + "\nSalaryTwo : " + newWindow.salaryTwo
}
Button {
id: closeWindowButton
anchors.centerIn: parent
text:"Close"
width: 98
tooltip:"Press me, to close this window again"
onClicked: newWindow.visible = false
}
}
}
ListModel {
id: salaryModel
ListElement {
name: "John Smith"
SalaryOne: 50
SalaryTwo: 230
}
ListElement {
name: "Max Mustermann"
SalaryOne: 67
SalaryTwo: 0
}
}
//this is the delegate, determine the way you want to show the data
Component {
id: salaryDelegate
Item {
width: 180; height: 40
Column {
Text { text: name }
Text { text: "Salary : " + SalaryOne + ", " + SalaryTwo }
}
MouseArea{
anchors.fill: parent
//set the value of the window and make it visible
onClicked: {
newWindow.name = model.name
newWindow.salaryOne = model.SalaryOne
newWindow.salaryTwo = model.SalaryTwo
newWindow.visible = true
view.currentIndex = index
}
}
}
}
ListView {
id: view
anchors.fill: parent
model: salaryModel
delegate: salaryDelegate
}
}
You could separate the window or ListView into different qml files, combine the power of c++ ,qml and javascript. Declarative langauge like qml is pretty good on handling UI.
c++ version
#include <memory>
#include <QApplication>
#include <QListView>
#include <QSplitter>
#include <QStandardItemModel>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStandardItemModel model(2, 1);
model.appendRow(new QStandardItem(QString("John Smith\nSalary: %1, %2\n").arg(50).arg(230)));
model.appendRow(new QStandardItem(QString("Max Mustermann\nSalary: %1, ").arg(67) + QString("000\n")));
QSplitter splitter;
QListView *list = new QListView(&splitter);
list->setModel(&model);
splitter.addWidget(list);
splitter.show();
return a.exec();
}
Enhance them by your need, c++ version also support delegate.
You could encapsulate the QListView and open a new window when the
user click on the index(you need QItemSelectionModel to detect which
item you selected).Before you can design higly customize UI,you have
to study a lot of the model and view frameworks of Qt. Since your case
are pretty simple, default QListView and QStandardItemModel is enough.
Supplement : How to detect which index you selected?
//the type of model_selected is QItemSelectionModel*
model_selected = list->selectionModel();
connect(model_selected, SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(selection_changed(QItemSelection, QItemSelection)));
void imageWindow::selection_changed(QItemSelection, QItemSelection)
{
//do what you want
}