Using c++ enum in qml - qt

I have an enum that I use in qml
class SettingManager : public QObject
{
Q_OBJECT
public:
enum BookKinds{
BookKind1=0,
BookKind2=1,
};
Q_ENUMS(BookKinds)
Q_PROPERTY(BookKinds bookKind READ bookKind WRITE setBookKind NOTIFY bookKindChanged)
explicit SettingManager(QObject *parent = nullptr);
void setBookKind(BookKinds dkob);
BookKinds bookKind();
signals:
void bookKindChanged();
};
in main.cpp I registerd SettingManager
qmlRegisterType<SettingManager>("Test",1,0,"SettingManager");
I use this in qml file
onCurrentIndexChanged:
{
if(tbarBookKindForDisplay.currentIndex==0)
{
settingManager.bookKind=BookManager.BookKind1;
}
else if(tbarBookKindForDisplay.currentIndex==1){
settingManager.bookKind=BookManager.BookKind2;
}
}
when CurrentIndex of TabBar changes below error occurs:
Error: Cannot assign [undefined] to int

You register the type as SettingManager but use it as BookManager. The correct code is:
settingManager.bookKind = SettingManager.BookKind1;
You should also use Q_ENUM instead of Q_ENUMS.

Related

How can access 'in-memory' sqlite database from QML?

I created an in-memory SQLite database using Qt-C++
const QString m_DRIVER = "QSQLITE";
QSqlDatabase m_db;
m_db = QSqlDatabase::addDatabase(m_DRIVER, "mkddb");
m_db.setDatabaseName(":memory:");
My question is how I can access it in QML?
As long as You have the database connection established in some class of Yours, eg. Database Handler, You can expose it to QML in a very simple way. Here is a very brief concept of how such handler would look like:
DatabaseHandler.h
class DatabaseHandler : public QObject
{
Q_OBJECT
public:
explicit DatabaseHandler(QObject *parent = nullptr);
Q_INVOKABLE void addDatabaseEntry(QString queryString);
private:
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE", "mkddb");
QSqlQuery databaseQuery;
};
DatabaseHandler.cpp
DatabaseHandler::DatabaseHandler(QObject *parent) : QObject(parent)
{
database.setDatabaseName(":memory:");
database.open();
databaseQuery = QSqlQuery(database);
}
void DatabaseHandler::addDatabaseEntry(QString queryString)
{
databaseQuery.exec(queryString);
}
The object itself has to be a QObject with a Q_OBJECT macro as on the code above.
To expose the DatabaseHandler to QML, in eg. main.cpp You would have to write this:
qmlRegisterType<DatabaseHandler>("com.organization.databasehandler", 1, 0, "DatabaseHandler");
Then in QML code You can import the database handler and use its methods as long as they're declared with the macro Q_INVOKABLE like in the DatabaseHandler.h:
import com.organization.databasehandler 1.0
ApplicationWindow {
DatabaseHandler {
id: databaseHandler
}
Button {
onClicked: databaseHandler.addDatabaseEntry(/*Query to execute on the database*/)
}
}

Qt: How do I notify changing mouse coordinates to parent object

I have a little problem with the Qt class QGraphicsScene:
To detect the current mouse coordinates I made a new class QGraphicsScenePlus with QGraphicsScene as the base class. I have already redefined the slot function mouseMoveEvent(QGraphicsSceneMouseEvent* event) and the received coordinates seem to be correct. Now I want to notify the parent QMainWindow class, where the QGraphicsScenePlus object is stored, whenever the mouse coordinates change. What is the best way to do this? I already tried to define signals and slots, but it didn't work. The slot function wasn't found during the execution of the program.
Here is the code so far:
qgraphicssceneplus.h
#ifndef QGRAPHICSSCENEPLUS_H
#define QGRAPHICSSCENEPLUS_H
#include <QObject>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
class QGraphicsScenePlus : public QGraphicsScene {
public:
QGraphicsScenePlus(QObject* parent = 0);
public slots:
void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
public:
int mx = 0;
int my = 0;
};
#endif // QGRAPHICSSCENEPLUS_H
qgraphicssceneplus.cpp
#include "qgraphicssceneplus.h"
QGraphicsScenePlus::QGraphicsScenePlus(QObject* parent) : QGraphicsScene(parent) {
}
void QGraphicsScenePlus::mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent) {
mx = mouseEvent->scenePos().x();
my = mouseEvent->scenePos().y();
this->update();
}
Comment
I am not sure how you made the above code compiled.
1. Even though you subclass from a QObject, you still need the Q_OBJECT macro to keep meta-object compiler informed:
class QGraphicsScenePlus : public QGraphicsScene {
Q_OBJECT // <--- You miss this
public:
QGraphicsScenePlus(QObject* parent = 0);
2. It's not allowed to assign primitive value in C++ class definition, do it in the constructor instead:
public:
int mx /*= 0*/;
int my /*= 0*/;
};
Solution
As for your question:
What is the best way to do this? I already tried to define signals and slots, but it didn't work.
The best way is still Signals & Slots.
Code
qgraphicssceneplus.h
class QGraphicsScenePlus : public QGraphicsScene {
Q_OBJECT
public:
QGraphicsScenePlus(QObject* parent = 0);
public slots:
void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
signals:
void sendCoord(int,int); // for sending the information of coordinates
public:
int mx;
int my;
};
qgraphicssceneplus.cpp
QGraphicsScenePlus::QGraphicsScenePlus(QObject* parent) : QGraphicsScene(parent) {
mx = 0;
my = 0;
}
void QGraphicsScenePlus::mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent) {
mx = mouseEvent->scenePos().x();
my = mouseEvent->scenePos().y();
emit sendCoord(mx, my); // emit the signal
this->update();
}
To catch the signal, define the slot in QMainWindow. For example:
public slots:
void receiveCoord(int x, int y);
and connect it to the signal of your graphic scene.
Demo

How to store global data in QList

Can you explain a methods for storing program data with global access ?
I found these keywords:
- using static class to store data
- pass QList by value
- pass Qlist by reference
- use 'friend' keyword
but I cannot find any real example of storing global QList, as they say, it is a bad design to use global variables. Also there is a mention that using pointers on a QList is a bad idea because of implicit sharing (?).
So where should I store my Qlist for accessing it from a different class in an other .cpp ? So I have:
mainwindow.h
QList <SceneCard> sceneList;
QString mTitle;
public slots:
QString setValue()
{
return mTitle;
}
mainwindow.cpp
MainWindow::AddScene()
{
sceneCard = new SceneCard(sNumber);
sceneList.append(sceneCard);
mTitle = "Nejat is right!"
}
void MainWindow::showSceneCard()
{
SceneDialog D;
connect(D,SIGNAL(getValue()),this,SLOT(setValue()));
D.exec();
}
scenedialog.h
#ifndef SCENEDIALOG_H
#define SCENEDIALOG_H
#include <QDialog>
#include <QList>
namespace Ui {
class SceneDialog;
}
class SceneDialog : public QDialog
{
Q_OBJECT
public:
SceneDialog(QWidget *parent = 0);
~SceneDialog();
signals:
QString getValue();
private:
Ui::SceneDialog *ui;
QString myText;
};
scenedialog.cpp
#include "scenedialog.h"
#include "ui_scenedialog.h"
#include <QDebug>
SceneDialog::SceneDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SceneDialog)
{
ui->setupUi(this);
myText = getValue();
qDebug() << myText; // myText is empty!!
}
You can put your list as a class member and use Qt's Signal/slot mechanism to access the list from other classes. Just make a signal in the target class, connect it to a slot in the class containing the list and make a connection between two objects of the classes. This way you can access any data member of other classes by connecting a signal to a slot returning that value and just emitting the signal and getting the return value.
For example if you have two classes like :
class A: public QObject
{
Q_OBJECT
public:
A(QObject *parent = 0);
~A();
signals:
int getValue();
private:
void someFunction()
{
int val = getValue();
}
};
class B
{
Q_OBJECT
public:
B(QObject *parent = 0);
~B();
public slots:
int getValue()
{
return someValue;
}
};
And connect the signal from an object of A to the slot in an object of B :
connect(a, SIGNAL(getValue()), b, SLOT(getValue()));
In class A you can access the value returned from getValue slot in B by just calling the signal and using the returned value.
Note that the two objects should be in the same thread for this to work. If they are in different threads then the connection type should be of type Qt::BlockingQueuedConnection :
connect(a, SIGNAL(getValue()), b, SLOT(getValue()), Qt::BlockingQueuedConnection);
Another way is two use static class members but it is not recommended unless you have a good reason to do it. If you have two classes like :
class A {
public:
static QList<int> list;
};
class B {
public:
void do_something();
};
You can access A's static data member from B like this:
void B::do_something()
{
int val = A::list[0];
...
};

Is it possible to emit a Qt signal from a const method?

In particular, I am implementing a QWizardPage ("MyWizardPage") for a QWizard, and I want to emit a signal ("sigLog") from my override of the QWizardPage::nextId virtual method.
Like so:
class MyWizardPage
: public QWizardPage
{
Q_OBJECT
public:
MyWizardPage();
virtual int nextId() const;
Q_SIGNALS:
void sigLog(QString text);
};
int MyWizardPage::nextId() const
{
Q_EMIT sigLog("Something interesting happened");
}
But when I try this, I get the following compile error on the Q_EMIT line:
Error 1 error C2662: 'MyWizardPage::sigLog' : cannot convert 'this' pointer from 'const MyWizardPage' to 'MyWizardPage &'
It is possible to emit a signal from a const method by adding "const" to the signal declaration, like so:
void sigLog(QString text) const;
I tested this and it does compile and run, even though you don't actually implement the signal as a normal method yourself (i.e. Qt is okay with it).
You may try to create another class , declare it as friend for your wizard page and add to wizard as a mutable member. after that you may emit it's signal instead of wizard's.
class ConstEmitter: public QObject
{
Q_OBJECT
...
friend class MyWizardPage;
Q_SIGNALS:
void sigLog(QString text);
};
class MyWizardPage
: public QWizardPage
{
Q_OBJECT
public:
MyWizardPage();
protected:
mutable CostEmitter m_emitter;
Q_SIGNALS:
void sigLog(QString text);
};
int MyWizardPage::nextId() const
{
Q_EMIT m_emitter.sigLog("Something interesting happened");
}
MyWizardPage::MyWizardPage()
{
connect(&m_emitter,SIGNAL(sigLog(QString)),this,SIGNAL(sigLog(QString)));
}
or you may just use
int MyWizardPage::nextId() const
{
Q_EMIT const_cast<MyWizardPage*>(this)->sigLog("Something interesting happened");
}
that is not recommended way, because const_cast is a hack, but it's much shorter :)

Qt4 parent pointer usage

I'm having some problem with understanding usage of parent pointer in QT4.
class firstClass : public QWidget
{
Q_OBJECT
public:
firstClass(QWidget *parent = 0);
~firstClass();
void doSomething();
private:
secondClass * myClass;
};
class secondClass : public QWidget
{
Q_OBJECT
public:
secondClass(QWidget *parent = 0);
void doSomethingElse();
};
I want to call doSomething() method while running doSomethingElse(). Is there any way to do it using parent pointer?
I tried parent->doSomething() but it doesn't work. It seems that Qt Creator is suggesting only methods from QObject class after parent->.
On the other hand I can't write it like secondClass(firstClass *parent = 0); - compilator returns error:
Thanks for any suggestions.
If you are positive that the parent of secondClass is always going to be firstClass then you can do this:
static_cast<firstClass *>(parent)->doSomething();
Alternatively you can use qobject_cast and check to make sure that parent is actually an instance of firstClass:
firstClass *myParent = qobject_cast<firstClass *>(parent);
if(myParent){
myParent->doSomething();
}
The more Qt-ish way to do this would be to use signals and slots, instead of trying to directly call a different function.
class firstClass : public QWidget
{
Q_OBJECT
public:
firstClass(QWidget *parent = 0);
~firstClass();
public slot:
void doSomething();
private:
secondClass * myClass;
};
class secondClass : public QWidget
{
Q_OBJECT
public:
secondClass(QWidget *parent = 0);
void doSomethingElse()
{
// ...
emit ( triggerDoSomething() );
// ...
}
signal:
void triggerDoSomething();
};
firstClass::firstClass(QWidget *parent) :
QWidget(parent), myClass(new secondClass(this))
{
// ...
bool connected = connect(myClass, SIGNAL(triggerDoSomething()),
SLOT(doSomething()));
assert( connected );
}

Resources