DoubleValidator is not checking the ranges properly - c++

Let me use an example to explain the issue.
If we have a TextField like this,
TextField {
text: "0.0"
validator: DoubleValidator { bottom: -359.9;
top: 359.9;
decimals: 1;
notation: DoubleValidator.StandardNotation }
onEditingFinished: {
console.log("I'm here!");
}
}
We can type numbers such as 444.9, 399.9 or -555.5. As you can see, the values are not between -359.9 and 359.9.
In the documentation we can find the following information:
Input is accepted but invalid if it contains a double that is
outside the range or is in the wrong format; e.g. with too many digits
after the decimal point or is empty.
I thought DoubleValidator didn't accept this kind of things, but unfortunately it does.
So I suppose the solution would be to check the final input, but again we have a problem: editingFinished is only emitted if the validator returns an acceptable state and this is not always the case.
Perhaps I'm not doing a good approach, I'm not understanding how to use DoubleValidator or maybe I need some code in C++.
By the way, I'm working with Qt 5.4.

The problem lies in the fact that QML TextField accepts intermediate input:
validator : Validator
Allows you to set a validator on the TextField. When a validator is set, the TextField will only accept input which leaves the text property in an intermediate state. The accepted signal will only be sent if the text is in an acceptable state when enter is pressed.
The validate()-function of QDoubleValidator describes when it returns QValidator::Intermediate:
State QValidator::validate(QString & input, int & pos) const
This virtual function returns Invalid if input is invalid according to this validator's rules, Intermediate if it is likely that a little more editing will make the input acceptable (e.g. the user types "4" into a widget which accepts integers between 10 and 99), and Acceptable if the input is valid.
So that means, the validator returns QValidator::Intermediate, as long as a double value is entered and because TextField is okay with "intermediate", you can type anything as long as it is a number.
What you can do is to subclass QDoubleValidator and to override validate(), so that it does not return Intermediate when the values are out of bounds:
class TextFieldDoubleValidator : public QDoubleValidator {
public:
TextFieldDoubleValidator (QObject * parent = 0) : QDoubleValidator(parent) {}
TextFieldDoubleValidator (double bottom, double top, int decimals, QObject * parent) :
QDoubleValidator(bottom, top, decimals, parent) {}
QValidator::State validate(QString & s, int & pos) const {
if (s.isEmpty() || (s.startsWith("-") && s.length() == 1)) {
// allow empty field or standalone minus sign
return QValidator::Intermediate;
}
// check length of decimal places
QChar point = locale().decimalPoint();
if(s.indexOf(point) != -1) {
int lengthDecimals = s.length() - s.indexOf(point) - 1;
if (lengthDecimals > decimals()) {
return QValidator::Invalid;
}
}
// check range of value
bool isNumber;
double value = locale().toDouble(s, &isNumber);
if (isNumber && bottom() <= value && value <= top()) {
return QValidator::Acceptable;
}
return QValidator::Invalid;
}
};

I found an easier way.
TextField {
id: control
onTextChanged:
{
if(!acceptableInput)
control.undo()
}
}
When text in TextField is invalid, acceptableInput would change to false, so when text changed ,check the property, if it's false, then call undo() to undo the changes.

The answer provided by #xsquared was perfect. I think it's a good idea to share with anyone curious how to integrate the solution with QML.
TextFieldDoubleValidator is the class which #xsquared suggested.
So the first thing is to register the new type in our main.
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include "textfielddoublevalidator.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<TextFieldDoubleValidator>("TextFieldDoubleValidator", 1,0,
"TextFieldDoubleValidator");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
After that, we can use the new type in our QML application:
main.qml
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import TextFieldDoubleValidator 1.0
Window {
visible: true
// DoubleValidator doesn't clear the TextField when
// text > 359.9 or < -359.9
TextField {
text: "0.0"
validator: DoubleValidator {
bottom: -359.9;
top: 359.9;
decimals: 1;
notation: DoubleValidator.StandardNotation
}
}
// Solution: use your own DoubleValidator.
// This works OK and text is cleared out when
// text > 359.9 or < -359.9
TextField {
y: 50
text: "0.0"
validator: TextFieldDoubleValidator {
bottom: -359.9;
top: 359.9;
decimals: 1;
notation: DoubleValidator.StandardNotation
}
}
}

Here is a pure qml version:
TextFieldInput{
validator: DoubleValidator
{
bottom: minimumValue
top: maximumValue
}
property real maximumValue: constants._MAXIMUM_INTEGER
property real minimumValue: constants._MINIMUM_INTEGER
property string previousText: ""
onTextChanged:
{
var numericValue = getValue()
if (numericValue > maximumValue || numericValue < minimumValue)
{
text = previousText
}
previousText = text
}
function setValue(_value)
{
text = String(_value)
}
function getValue()
{
return Number(text)
}}

Related

How to delete row from TableView properly

I'm using Qt 5.15.0 on Manjaro.
I have a table I created with TableView in qml.
I can delete a row with right click on the Id field like this:
The deletion etc works but I get these errors in qml:
The method for delete rows looks like this in main.qml:
function deleteRowFromDatabase(row) {
console.log("before" + model.countOfRows())
if (!model.removeEntry(row)) {
console.log(qsTr("remove row %1 failed").arg(row))
}
model = QuestionsProxyModel
console.log("after" + model.countOfRows())
}
The error point to the delegate row of id in main.qml
DelegateChoice {
column: 0
delegate: QuestionIdDelegate {
id: questionIdDelegate
width: tableView.columnWidthProvider(column)
text: model.id /// this is undefined
row: model.row
Component.onCompleted: {
questionIdDelegate.markForDelete.connect(
tableView.deleteRowFromDatabase)
}
}
}
Removing of the rows is implemented from C++ In a class derrived from QIdentityProxyModel in questionsproxmodel.h:
bool QuestionsProxyModel::removeEntry(int row)
{
return removeRows(row, 1);
}
This model takes a class QuestionSqlTableModel derrived from QSqlTableModel as a source model
The remove rows is implemented like this in questionssqltablemodel.qml:
bool QuestionSqlTableModel::removeRows(int row, int count,
const QModelIndex &parent)
{
auto result = QSqlTableModel::removeRows(row, count, parent);
if (result) {
select(); // row is not deleted from sql database until select is called
}
return result;
}
From my understanding the countOfRows of the model gets updated only after the select() is called so I assume between QSqlTableModel::removeRows and select the TableView reads one more time with the non existing row and causes these errors in QML. How can that be prevented?
Full Source code to try it out:
main.cpp:
#include <QDebug>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QFile>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include "questionsproxymodel.h"
#include "questionsqltablemodel.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QUrl dbUrl{"file:///home/sandro/Desktop/test.db"};
auto exists = QFile::exists(dbUrl.toLocalFile());
auto db = QSqlDatabase::addDatabase("QSQLITE", "DBConnection");
db.setDatabaseName(dbUrl.toLocalFile());
db.open();
if (!exists) {
const QString questionTableName = "questions";
QSqlQuery query{db};
query.exec("CREATE TABLE " + questionTableName +
" ("
"id INTEGER PRIMARY KEY AUTOINCREMENT)");
}
QScopedPointer<QuestionSqlTableModel> questionSqlTableModel(
new QuestionSqlTableModel(nullptr, db));
QScopedPointer<QuestionsProxyModel> questionsProxyModel{
new QuestionsProxyModel};
questionsProxyModel->setSourceModel(questionSqlTableModel.get());
if (!exists) {
for (int i = 0; i < 10; ++i) {
questionsProxyModel->addNewEntry();
}
}
QQmlApplicationEngine engine;
qmlRegisterSingletonInstance<QuestionsProxyModel>(
"QuestionsProxyModels", 1, 0, "QuestionsProxyModel",
questionsProxyModel.get());
const QUrl url(QStringLiteral("qrc:/qml/main.qml"));
engine.load(url);
return app.exec();
}
questionssqltablemodel.h
#include <QSqlTableModel>
class QuestionSqlTableModel : public QSqlTableModel {
Q_OBJECT
public:
explicit QuestionSqlTableModel(QObject *parent = nullptr,
const QSqlDatabase &db = QSqlDatabase());
bool removeRows(int row, int count, const QModelIndex &parent) override;
};
questionssqltablemodel.cpp
#include "questionsqltablemodel.h"
#include <QBuffer>
#include <QDebug>
#include <QPixmap>
#include <QSqlError>
#include <QSqlField>
#include <QSqlRecord>
#include <QSqlRelationalDelegate>
QuestionSqlTableModel::QuestionSqlTableModel(QObject *parent,
const QSqlDatabase &db)
: QSqlTableModel{parent, db}
{
setTable("questions");
setSort(0, Qt::AscendingOrder);
if (!select()) {
qDebug() << "QuestionSqlTableModel: Select table questions failed";
}
setEditStrategy(EditStrategy::OnFieldChange);
}
bool QuestionSqlTableModel::removeRows(int row, int count,
const QModelIndex &parent)
{
auto result = QSqlTableModel::removeRows(row, count, parent);
if (result) {
select(); // row is not deleted from sql database until select is called
}
return result;
}
questionsproxymodel.h:
#include <QIdentityProxyModel>
#include <QObject>
class QuestionsProxyModel : public QIdentityProxyModel {
Q_OBJECT
enum questionRoles {
idRole = Qt::UserRole + 1,
};
public:
QuestionsProxyModel(QObject *parent = nullptr);
QHash<int, QByteArray> roleNames() const override;
Q_INVOKABLE QVariant data(const QModelIndex &index,
int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value,
int role = Qt::EditRole) override;
bool addNewEntry();
Q_INVOKABLE bool removeEntry(int row);
Q_INVOKABLE int countOfRows() const;
private:
QModelIndex mapIndex(const QModelIndex &source, int role) const;
};
questionsproxymodel.h:
#include "questionsproxymodel.h"
#include <QBuffer>
#include <QDebug>
#include <QPixmap>
#include <QByteArray>
#include <QSqlError>
#include <QSqlTableModel>
QuestionsProxyModel::QuestionsProxyModel(QObject *parent)
: QIdentityProxyModel(parent)
{
}
QHash<int, QByteArray> QuestionsProxyModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[idRole] = "id";
return roles;
}
QVariant QuestionsProxyModel::data(const QModelIndex &index, int role) const
{
QModelIndex newIndex = mapIndex(index, role);
if (role == idRole) {
return QIdentityProxyModel::data(newIndex, Qt::DisplayRole);
}
return QIdentityProxyModel::data(newIndex, role);
}
bool QuestionsProxyModel::setData(const QModelIndex &index,
const QVariant &value, int role)
{
QModelIndex newIndex = mapIndex(index, role);
if (role == idRole) {
return QIdentityProxyModel::setData(newIndex, value, Qt::EditRole);
}
return QIdentityProxyModel::setData(newIndex, value, role);
}
bool QuestionsProxyModel::addNewEntry()
{
auto newRow = rowCount();
if (!insertRows(newRow, 1)) {
return false;
}
if (!setData(createIndex(newRow, 0), newRow + 1)) {
removeRows(newRow, 1);
return false;
}
auto sqlModel = qobject_cast<QSqlTableModel *>(sourceModel());
return sqlModel->submit();
}
bool QuestionsProxyModel::removeEntry(int row)
{
return removeRows(row, 1);
}
int QuestionsProxyModel::countOfRows() const
{
return rowCount();
}
QModelIndex QuestionsProxyModel::mapIndex(const QModelIndex &source,
int role) const
{
switch (role) {
case idRole:
return createIndex(source.row(), 0);
}
return source;
}
main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15
import Qt.labs.qmlmodels 1.0
import QtQuick.Controls.Material 2.15
import QuestionsProxyModels 1.0
ApplicationWindow {
id: root
visible: true
width: 1460
height: 800
TableView {
id: tableView
width: parent.width
anchors.fill: parent
boundsBehavior: Flickable.StopAtBounds
reuseItems: true
clip: true
property var columnWidths: [60]
columnWidthProvider: function (column) {
return columnWidths[column]
}
model: QuestionsProxyModel
delegate: DelegateChooser {
id: chooser
DelegateChoice {
column: 0
delegate: QuestionIdDelegate {
id: questionIdDelegate
width: tableView.columnWidthProvider(column)
text: model.id
row: model.row
Component.onCompleted: {
questionIdDelegate.markForDelete.connect(
tableView.deleteRowFromDatabase)
}
}
}
}
ScrollBar.vertical: ScrollBar {}
function deleteRowFromDatabase(row) {
console.log("before" + model.countOfRows())
if (!model.removeEntry(row)) {
console.log(qsTr("remove row %1 failed").arg(row))
}
model = QuestionsProxyModel
console.log("after" + model.countOfRows())
}
}
}
QuestionIdDelegate.qml:
import QtQuick 2.15
import QtQuick.Controls 2.15
TextField {
property int row
signal markForDelete(int row)
id: root
implicitHeight: 100
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
readOnly: true
background: Frame {}
MouseArea {
id: mouseArea
anchors.fill: parent
acceptedButtons: Qt.RightButton
onClicked: {
eraseContextMenu.popup(root, 0, mouseArea.mouseY + 10)
}
}
Menu {
id: eraseContextMenu
y: root.y
MenuItem {
text: qsTr("Delete entry")
onTriggered: {
eraseDialog.open()
eraseContextMenu.close()
}
}
MenuItem {
text: qsTr("Cancel")
onTriggered: {
eraseContextMenu.close()
}
}
}
Dialog {
id: eraseDialog
title: qsTr("Delete database entry")
modal: true
focus: true
contentItem: Label {
id: label
text: qsTr("Do you really want to erase the entry with id %1?").arg(
root.text)
}
onAccepted: {
markForDelete(root.row)
}
standardButtons: Dialog.Ok | Dialog.Cancel
}
}
.pro:
QT += quick
QT += quickcontrols2
QT += sql
CONFIG += c++17
DEFINES += QT_DEPRECATED_WARNINGS
HEADERS += \
questionsproxymodel.h \
questionsqltablemodel.h
SOURCES += \
main.cpp \
questionsproxymodel.cpp \
questionsqltablemodel.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
edit:
The answer solves the error stated above. However I detected another problem with the code.
If I delete the row 1 and then the row 2 my output looks like this:
This binding loop error points Dialog in QuestionsIDDelegate:
Dialog {
id: eraseDialog
title: qsTr("Delete database entry")
modal: true
focus: true
contentItem: Label {
id: label
text: qsTr("Do you really want to erase the entry with id %1?").arg(
root.text)
}
onAccepted: {
markForDelete(root.row)
}
standardButtons: Dialog.Ok | Dialog.Cancel
}
One way to prevent this is to check that the property is not undefined:
text: model.id === undefined ? "" : model.id
I'm not going to fix the code, but I am going to try to explain why you are having trouble. I feel the why of things will help more people.
This image may not be 100% accurate but it is how one must visualize things in their mind. You have three distinct lanes an object lives in when you introduce QML: C++, QML Engine, and JavaScript engine. Each and every one of those lanes believes beyond a shadow of a doubt that they control the life and death of the object.
When you are just passing integers around that are passed by value, this is no issue. When you are passing QStrings around, because of the copy-on-write charter of Qt, this is only a minor issue. When you are passing real objects around, worse yet, complex containers of real objects, you have to understand this completely. The answer that "fixed" your problem really only masked it. You will find there is a lot of QML and JavaScript code out there that exists only to mask an application not respecting the lanes.
Had this application used an actual database there would be a fourth lane. Yes, SQLite provides an SQL interface and allows many things, but an actual database has an external engine providing shared access and controlling the life of cursors. SQLite files tend to be single user. Yes, multiple threads within your application can access it, but while your application is running you cannot open a terminal window and use command line tools to examine the database. Think of it more as a really nice indexed file system without sharing.
So, you create an object in C++ and then expose it to QML. The QML engine now believes beyond a doubt that it controls the life and death of that object despite not having its own copy.
QML is really feeble. It can't actually do much, so it has to hand any significant object off to JavaScript. The JavaScript engine now believes beyond a shadow of a doubt that it now controls the life and death of that object.
You need to also envision these lanes as independent threads. There will most likely be many threads within each, but, in general, any signal or communication between these will go on the event loop of the target as a queued event. That means it will only be processed when it finally bubbles to the top of the queue for that event loop.
This, btw, is why you can never use Smart Pointers when also using QML/JavaScript. Especially the kind that do reference counting and delete the object when there are no more references. There is no way for the C++ lane to know that QML or JavaScript are still using the object.
The answer telling you to check for undefined property is masking the problem that your code is drunk driving across all lanes. Eventually, on a faster (or sometimes slower) processor garbage collection for one of the lanes will run at a most inopportune moment and you will be greeted with a stack dump. (The drunk driving code will hit a tree that does not yield.)
Correct Solution #1:
Never use QML or JavaScript. Just use C++ and Widgets. Stay entirely within the C++ lane. If that is a route open to you it's a good way to go. There is an awful lot of production code out there doing just that. You can obtain a copy of this book (or just download the source code from the page) and muddle through building it.
Correct Solution #2:
Never actually do anything in QML or JavaScript. This is an all together different solution than #1. You can use QML for UI only, leaving all logic in C++. Your code is failing because you are trying to actually do something. I haven't built or tried your code. I simply saw
function deleteRowFromDatabase(row)
which shouldn't exist at all. C++ holds your model. You emit a signal from your QML/JavaScript lanes when user action requires deletion. This signal becomes a queued event in the C++ lane. When it is processed the row will be deleted and the model updated. If you have properly exposed your model to QML it will emit some form of "model changed" signal and the UI will update accordingly. One of the main points of MVC (Model-View-Controler) is communication to/from the model. When the data changes it notifies the view(s).
Correct Solution #3:
Never use C++. Have your C++ be a "Hello World!" shell that just launches your QML. Never create and share an object between C++ and the other two lanes. Do everything inside of JavaScript and QML.
Binding loop errors, in general, happen when code drunk drives across all three lanes. They also happen when code doesn't view each lane as at least one distinct thread with its own event loop. The C++ lane hasn't finished (perhaps not even started) the delete operation but your code is already trying to use the result.
I don't know why, but some people edit these things and delete the correct answers. The full information was too long for SO and is contained here,
https://www.logikalsolutions.com/wordpress/uncategorized/so-you-cant-get-your-qt-models-to-work-with-qml/
with source even.

C++ / QML interactive combo box implementation

I have two combo boxes, the data for the second one being determined by that of the first one. The number of strings in the second combo box varies from 2 to 4. If I:
select a new string in the first combo box and
the last choice is selected
in the second combo box with a longer list than the previous list of
that box,
the currentString in the second combo box remains and overrides the correct text
For instance, if I select Scubapro in the first combo box (4 options in 2nd box) and Smart in the second combo box (the 4th option), then select any other choice in the first combo box again (< 4 options in 2nd box), the entry in the second combo box remains "Smart", which is inappropriate. The correct list is, however, loaded into the 2nd combo box. Inspection of the underlying stringlist also suggests that it contains the correct data. The problem appears to be the visual updating of the second combo box. The heart of the algorithm comes from Stackoverflow and is the generator called each time text in combo box 1 changes.
What can one do to rectify this?
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#include <QQuickView>
#include <QQuickItem>
#include <QStringListModel>
#include <QQmlContext>
#include <QDebug>
QStringList dat1, dat2, dat3;
QStringList vendorList;
class Generator : public QObject
Q_OBJECT
QStringListModel * m_model;
public:
Generator(QStringListModel * model) : m_model(model) {}
Q_INVOKABLE void generate(const QVariant & val) {
m_model->removeRows(0,m_model->rowCount()); // This has no effect
if (QString::compare(val.toString(), QString::fromStdString("Mares"), Qt::CaseInsensitive) == 0) {
m_model->setStringList(dat1);
}
else {
if (QString::compare(val.toString(), QString::fromStdString("ScubaPro"), Qt::CaseInsensitive) == 0) {
m_model->setStringList(dat2);
}
else
m_model->setStringList(dat3);
}
};
int main(int argc, char *argv[])
{
QStringListModel model1, model2;
generator(&model2);
dat1 << "Puck" << "Nemo" << "Matrix";
dat2 << "Aladin" << "Meridian" << "Galilio" << "Smart";
dat3 << "D4" << "D6";
vendorList << "Mares" << "Scubapro" << "Suunto" << "Shearwater";
model1.setStringList(vendorList);
QGuiApplication app(argc, argv);
QQuickView view;
QQmlContext *ctxt = view.rootContext();
ctxt->setContextProperty("model1", &model1);
ctxt->setContextProperty("model2", &model2);
ctxt->setContextProperty("generator", &generator);
view.setSource(QUrl("qrc:main.qml"));
view.show();
return app.exec();
}
#include "main.moc"
Here is the QML:
import QtQuick 2.0
import QtQuick.Controls 1.0
Rectangle {
width: 400; height: 300
Text { text: "Vendor"; }
Text {
x: 200
text: "Product"; }
ComboBox {
id: box2
objectName: "productBox"
x:200; y:25; width: 180
model: model2
textRole: "display"
}
ComboBox {
y:25; width: 180
id: box1
model: model1
textRole: "display"
onCurrentTextChanged: {
generator.generate(currentText)
}
}
}
Any comments are highly appreciated.
The ComboBox item does not react to changes performed under the hood to the model.
There are a couple of solutions to work around it.
A possible one is to reassign the model to itself at the end of the signal handler, by using the statement:
model = model;
As from the documentation:
Changing the model after initialization will reset currentIndex to 0.
Otherwise, you can explicitly set currentIndex to your preferred value or, even better, to -1.
In fact, from the documentation we have that:
Setting currentIndex to -1 will reset the selection and clear the text label.

Qml QColor Type Error

I am trying to set a QColor property of a custom QQuickPaintedItem by passing a QColor from C++ to QML. I have tried the following:
Converting QColor to QVariant. In the JS debugger, the color object was empty.
Converting QColor to a color string "#RRGGBB". This still throws the type error.
QML Code:
m_DisplayScreens[m_DisplayScreens.length].backgroundColor = m_Model.getBackgroundColor(i_Timer);
m_DisplayScreens is a list of my custom QML widget. I can set the backgroundColor property just fine by doing something like.
DisplayScreen
{
backgroundColor: "Red"
}
The "m_Model" object is simply a QObject which is the 'backend' of the QML form. The code for getBackgroundColor is as follows:
Q_INVOKABLE QString getBackgroundColor(int index);
QString CountDownPanelModel::getSegmentColor(int index)
{
return "#003300";
}
The specific error is: xxx.js:19: TypeError: Type error
Any help would be appreciated. I've been banging my head against this for a few hours now.
Thanks,
Jec
1st Edit:
Ok folks, here is my attempt when returning a QColor;
class CountDownPanelModel : public QObject
{
Q_OBJECT
public:
explicit CountDownPanelModel(QObject *parent = 0);
~CountDownPanelModel() = default;
Q_INVOKABLE QColor getBackgroundColor(int index);
Q_INVOKABLE QColor getSegmentColor(int index);
};
QColor CountDownPanelModel::getBackgroundColor(int index)
{
return QColor(44, 44, 44);
//return m_TimerList->at(index)->getTimerData()->getBackgroundColor();
}
QColor CountDownPanelModel::getSegmentColor(int index)
{
return QColor(200, 200, 200);
//return m_TimerList->at(index)->getTimerData()->getSegmentColor();
}
The result of using a QColor is the same as using the QString. I get "Type Error" at the line I assign the color at. For example:
var m_DisplayScreens = [];
function createDisplays()
{
m_DisplayScreens = [];
var timerCount = m_Model.getTimerCount();
var bg = m_Model.getBackgroundColor(0);
var fg = m_Model.getSegmentColor(0)
for (var i_Timer = 0;
i_Timer < timerCount;
++i_Timer)
{
var component = Qt.createComponent("DynamicSevenSegmentDisplay.qml");
var display = component.createObject(m_Panel);
display.initialize(m_Model.getSevenSegmentDisplayInitializer())
display.y = 100 * (i_Timer);
m_DisplayScreens[m_DisplayScreens.length] = display;
m_DisplayScreens[m_DisplayScreens.length].backgroundColor = m_Model.getBackgroundColor(i_Timer);
m_DisplayScreens[m_DisplayScreens.length].segmentColor = m_Model.getSegmentColor(i_Timer)
}
m_Panel.height = 100 * timerCount;
}
Just for completeness, here is DynamicSevenSegmentDisplay.qml
SevenSegmentDisplayScreen
{
y: 0
height: 100
width: parent.width - x
backgroundColor: "Black"
borderPercentage: 10
displayCount: 20
text: "1234567890"
anchors.left: m_SettingsButton.right
anchors.leftMargin: 8
}
I'm completely confused as to why I can't assignthe QColor to backgroundColor. The debugger just shows nothing in the 'value' column. I take it this is the JS version of 'null'.
This is not a definitive answer but I found several issues. I was previously developing using Linux Mint. I recently switched to Ubuntu and found several issues with passing data between C++ and QML. I got a message about a CRC miss match.
"the debug information found in "/usr/lib/x86_64-linux-gnu/dri/i915_dri.so" does not match "/usr/lib/x86_64-linux-gnu/dri/i965_dri.so" (CRC mismatch)."
So this also could be part of the problem. But for the most part it looks like its my development machine.

Show, change data and keep QQmlListProperty in qml

in the past i resolved a problem with QQmlListProperty for expose c++ qlist to qml, and the problem was resolved, now i try use their solution again, but i can't.
the first time the list exposed to qml every time are different, this time no, i have a Qlist in a main class, and many data from her are loaded from db, and others changed in runtime.
When the application start, the load of data and exposed to Qml is ok, i need change of page(gui) and keep the data stored in program and probably used many of their data in other guis (as text), and every time i change of page (with loader element) the program crashes, i believe a directions of pointers are changed in qml when the data from c++ class is copied to gui in qml.
My Code from QmlListproperty class and method of Load data in qml, and copy from the main qml to page.
definition of class ListBombsUi.h"
#include "StructBombUi.h"
class ListBombsUi: public QObject{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<CStructBombUi> bombsUi READ bombsUiList NOTIFY bombsUiChanged);
Q_CLASSINFO("DefaultProperty", "bombsUi");
public:
ListBombsUi(QObject *parent=0);
QQmlListProperty<CStructBombUi> bombsUiList();
static void appendBombUi(QQmlListProperty<CStructBombUi> *list, CStructBombUi *pdt);
static void clear(QQmlListProperty<CStructBombUi> *property);
static int listSize(QQmlListProperty<CStructBombUi> *property);
static CStructBombUi *bombUiAt(QQmlListProperty<CStructBombUi> *property, int index);
void addBomb(CStructBombUi *bombUi);
Q_INVOKABLE int size();
void Q_INVOKABLE getMemory();
Q_INVOKABLE void clearList();
CStructBombUi* getValue(int index) const;
QList<CStructBombUi *> copyList();
signals:
void bombsUiChanged();
public:
int lastAdded;
private:
CStructBombUi *item;
QList<CStructBombUi*> m_BombsUi;
i register how qmltype
qmlRegisterType<ListBombsUi>("BombsListUiModel", 1, 0, "ListBombsUi");
definition of main methods of ListBombsUi
ListBombsUi::ListBombsUi(QObject *parent):QObject(parent)
{}
QQmlListProperty<CStructBombUi> ListBombsUi::bombsUiList()
{
return QQmlListProperty<CStructBombUi>(this, &m_BombsUi, &ListBombsUi::appendBombUi,
&ListBombsUi::listSize,
&ListBombsUi::bombUiAt,
&ListBombsUi::clear);
emit bombsUiChanged();
}
void ListBombsUi::appendBombUi(QQmlListProperty<CStructBombUi> *list, CStructBombUi *pdt)
{
ListBombsUi *bombsList= qobject_cast<ListBombsUi *>(list->object);
if(bombsList) {
pdt->setParent(bombsList);
bombsList->m_BombsUi.append(pdt);
bombsList->bombsUiChanged();
}
}
void ListBombsUi::clearList()
{
m_BombsUi.clear();
emit bombsUiChanged();
}
void ListBombsUi::addBomb(CStructBombUi *bombUi)
{
m_BombsUi.append(bombUi);
emit bombsUiChanged();
}
definition in main class for two data, i use the first as aux, but is possible use the second directly(their are my idea originallly)
QList<CStructBombUi * > listBombs;
ListBombsUi *listBufferBombs;
i assign a listBufferBombs to element in qml
listBufferBombs = mainObject->findChild<ListBombsUi*>("listGralBombs");
method for expose data to qml
void EgasWindowWork::setDataOfBombsInModels()//, const QList <CEstrucBombUi> *const dataArrayBombs)
{
if( (mainObject) ) {
CStructBombUi e,k,j;
e.initializing(QStringList()<<"text1"<<"text2"<<"text3");
e.update(QString("15"), QString("1"), QString("1"), QString("1"),QString("1"));
k.initializing(QStringList()<<"text1"<<"text2");
k.update(QString("2"), QString("2"), QString("2"), QString("2"),QString("2"));
listBombs.append(&e);
listBombs.append(&k);
for(qint16 i=0; i<listBombs.size() ; i++)
{ listBufferBombs->addBomb( listBombs.value(i) ); }
QMetaObject::invokeMethod(mainObject, "setDataOfModelBombs"); //this method copy the list located in main qml for page
}
the metod in main.qml file
function setDataOfModelBombs()
{
if(itemOfPageLoaded) {
itemOfPageLoaded.listBombs=listed
itemOfPageLoaded.setDataOfBombs() //this function put every data inside the every field of qml gui element
}
}
declaration of loader element in main.qml file
Loader{
id: pageLoader
focus: true
//anchors.horizontalCenter: parent.horizontalCenter
width: parent.width
height: parent.height-50
anchors.top: headerIcons.bottom
objectName: "switchPages"
z: 2
source: "BombsUi.qml"
property bool valid: item !== null
Binding {
target: pageLoader.item
property: "numberBombs"
value: numberOfBombs
when: pageLoader.status == Loader.Ready
}
}
method in qml file loaded as page
function setDataOfBombs()
{
var size=newList.size()
arrayBombs.model=size //i use a repater container, and model is the number of elements loaded
if(size>0) {
for(var i=0; i<size; i++) {
//exactly in the next line the error happens
arrayBombs.itemAt(i).priceText=newList.bombsUi[i].ultimateProductPrice
arrayBombs.itemAt(i).volumeText = newList.bombsUi[i].ultimateProductVolume
//exist mor date, but with this are sufficient
}
}
}
and here is declaration of element repeater-grid
Item{
width: parent.width; height: parent.height
Item{
id: bombsArea
height: parent.height; width: parent.width*0.7
anchors.leftMargin: 10
y: 3
x: 2
Grid{
id: gridOfBombsModel
width: parent.width; height: parent.height
spacing: 7
rows: 6; columns: Math.round((parent.width/165))
Repeater{
id: arrayBombs
BombModel{
numberBomb: (index + 1)
MouseArea{
anchors.fill: parent
onClicked:{
parent.borderProperties.color="red"
parent.borderProperties.width=1.5
}
}
}
}
}
}
the program load the page 1 ok, but i change a page "n" and return to page 1, crashes. i accept alternatives to, Thanks for your help.
Well, i detected two things, fail in constructor of CStructBombsUi and i descart use of auxiliar list, and the use of CStructBombsUi* exclusively, and change the function in qml file, i show the changes.
Changes in main.qml
function setDataOfModelBombs()
{
if(itemOfPageLoaded) {
itemOfPageLoaded.numberBombs=listBombs.size()
itemOfPageLoaded.setDataOfBombs(listBombs.bombsUi)
}
}
changes in detailsbombs.qml (file loaded as page), and here i don't instance a ListBombs
function setDataOfBombs(bombsUi)
{
if(numberBombs>0) {
for(var i=0; i<numberBombs; i++)
{
arrayBombs.itemAt(i).priceText=bombsUi[i].ultimateProductPrice
arrayBombs.itemAt(i).volumeText = bombsUi[i].ultimateProductVolume
arrayBombs.itemAt(i).amountText= bombsUi[i].getUltimateProductMount()
arrayBombs.itemAt(i).fuelText= bombsUi[i].getUltimateProductName()
if(bombsUi[i].getFuels())
{arrayBombs.itemAt(i).setListOfFuelsInBomb( bombsUi[i].getFuels() ) }
}
}
}
The next line don't exist more
QList<CStructBombUi* > listBombs;
And every is a pointer
CStructBombUi *e=new CStructBombUi();
i don't use a list of values, with this adjusts the program don't crashes

QML failing to detect QObject destroyed in C++

The presented code does the following:
<1> Create object of QObject derived class and expose it to QML
<2> The class has a pointer to another QObject derived class and the pointer is accessible to QML via Q_PROPERTY.
<3> MouseArea in QML detects user-click and simply asks the c++ code for the pointer to be deleted.
<4> Color of rectangle turns black once this is detected.
The problem is that while certain approaches detect the deletion of the pointer by c++ other approaches don't.
Look at the inline comments:
Combination of (1) and (1b) works
Combination of (1) and (1d) does not work
(2) alone by itself works but (3) alone by itself does not.
When things work you should see the color of the Rectangle turn to black from yellow.
Can someone please explain this behaviour?
CPP codes:
class Name : public QObject
{
Q_OBJECT
Q_PROPERTY(bool boolVal READ boolVal CONSTANT FINAL)
public:
bool boolVal() const {return true;}
};
class Root : public QObject
{
Q_OBJECT
Q_PROPERTY(QObject* name READ name CONSTANT FINAL)
public:
QObject* name() const {return m_pName;}
Q_INVOKABLE void deleteName() {delete m_pName; m_pName = 0;}
private:
Name *m_pName {new Name};
};
//--- main
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Root objRoot;
QtQuick2ApplicationViewer viewer0;
viewer0.rootContext()->setContextProperty("objRoot", &objRoot);
viewer0.setMainQmlFile(QStringLiteral("qml/dualWindowApp/main.qml"));
viewer0.showExpanded();
return app.exec();
}
QML Code:
import QtQuick 2.0
Rectangle {
width: 360
height: 360
color: "red"
Rectangle {
id: objRect
anchors {left: parent.left; top: parent.top}
height: 70; width: 70;
property bool checked
property QtObject temp: objRoot.name
color: checked ? "yellow" : "black" // (1)
//color: objRect.temp && objRect.temp.boolVal ? "yellow" : "black" //--->WORKS (2)
//color: objRoot.name && objRoot.name.boolVal ? "yellow" : "black" //--->DOES NOT WORK !!! (3)
Binding on checked {
//value: objRect.temp && objRect.temp.boolVal //--->DOES NOT WORK !!! (1a)
//value: objRect.temp !== null && objRect.temp.boolVal //--->WORKS (1b)
value: objRect.temp ? objRect.temp.boolVal : false //--->WORKS (1c)
//Using directly without collecting in local QtQobject temp:
//----------------------------------------------------------
//value: objRoot.name && objRoot.name.boolVal //--->DOES NOT WORK !!! (1d)
//value: objRoot.name !== null && objRoot.name.boolVal //--->DOES NOT WORK !!! (1e)
//value: objRoot.name ? objRoot.name.boolVal : false //--->DOES NOT WORK !!! (1f)
}
Text {
text: "Destroy"
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: objRoot.deleteName()
}
}
}
using: {Qt/QML 5.2.0, Win 7, MinGW 4.8, QtQuick 2.0}
Your property declaration looks strange to me: name can obviously change, but you've declared it CONSTANT. My guess is it it'd work a whole lot better without the CONSTANT, and instead provide a NOTIFY of a nameChanged signal emitted when the value of name changes, else there's no guarantee the QML states bound to the C++ properties will be updated.