A few design questions...
-
Zap: that's a very good explanation. I'm still unclear on the combGainIChanged function, though. Do I actually implement this, or is it part of the BFM of Qt? I ask because I don't see an analog for it in the code we did in the other thread.
It seems that I'm not yet tying data to a display item, too...is that the next step?
EDIT:
Another question: can the combGainI stuff be adapted to be general-purpose, or do I need to replicate this for each variable I wish to display with QML?
-
Hey, Volker:
Just to be sure I was clear: when qmake runs, it puts the executable into Contents/MacOS, not into Contents/Resources. So, I just modified my .pro file accordingly:
@APP_QML_FILES.files = DemodShaperFilter.qml
APP_QML_FILES.path = Contents/MacOS
QMAKE_BUNDLE_DATA += APP_QML_FILES
@Unless I'm missing something, I don't see a downside to putting the .qml file (and other needed files) into the same directory as the executable...
-
In theory, Contents/MacOS conatains the executable(s), and Contents/Resources would be the place to put QML files. It's not really harmful, to put resources like QMLs into Contents/MacOS too. The only drawback is that it is not best practise on OS X and that Apple recommends Contents/Resources.
What makes me wonder, is how qmake puts that files into the wrong dir. Assuming there are two files QuickTest.qml and TestPage.qml within the same directory as the .pro file, the following snippet puts it into Contents/Resources:
@
APP_QML_FILES.files = QuickTest.qml TestPage.qml
APP_QML_FILES.path = Contents/Resources
QMAKE_BUNDLE_DATA += APP_QML_FILES
@You might want to remove the application bundle directory before building, as qmake just adds files, but does not remove them!
-
[quote author="mzimmers" date="1301678701"]Zap: that's a very good explanation. I'm still unclear on the combGainIChanged function, though. Do I actually implement this, or is it part of the BFM of Qt? I ask because I don't see an analog for it in the code we did in the other thread.
[/quote]No you do not need to implement it. The implementation of signals is generated automatically for you by the moc step of the build process. When you run qmake, it scans the files listed in the HEADERS section for class containing Q_OBJECT. It adds rules to the generated Makefile to run these headers through the Qt moc tool. The moc generates the moc_*.cpp files that you will find in your build tree. The signal/slot and other metaobject magic is implemented in these files.
[quote author="mzimmers" date="1301678701"]
It seems that I'm not yet tying data to a display item, too...is that the next step?
[/quote]Yes we will tackle that next. A swim and some food first for me though ;-)
EDIT:
[quote author="mzimmers" date="1301678701"]
Another question: can the combGainI stuff be adapted to be general-purpose, or do I need to replicate this for each variable I wish to display with QML?[/quote]That depends on what you want to do. You need to expose all properties that you wish to access from QML in this way. If you have a lot of data then there are alternative approaches using a subclass of QAbstractListModel for example.
Which approach to use depends upon how you structure your code. From what you have said earlier it sounded like you will have an object hierarchy, so it may be simplest to expose a member or two from each object as properties in this way. If you have a class with 20 such data items then it may pay you to look into the model approach for that case.
It will become clearer as we progress...
-
You can verify what you have done so far by converting your original GUI to use the new property changed signals instead of the original dataChanged( int, int ) signal. So if you now have two properties, one for each of the two variables, then you will need to make two connections - one for each property notifier signal.
Another way of verifying that it works would be to make use of the QTestLib framework and write a unit test for your class. In such tests you can make use of QSignalSpy to ensure that the signals were emitted as expected. Unit tests are nice as they can be run at any time in the future if you need to convince yourself that a certain part of your codebase is still working as it should.
Once you have verified that you calculation works as it should you can start putting together your QML scene that will display the state of your calculation object's properties. See if you can have a go at that from what you find in the QML examples. At this stage we don't need anything extravagant, just a couple of rectangles and text elements should suffice. Let us know if you need a hand with this.
-
Just got back to this stuff. So, if I understand your first paragraph above, I want to change this line in widget.cpp:
@ connect (soc, SIGNAL(dataChanged(int, int)), this, SLOT(setValue(int, int)));@
to:
@ connect (soc, SIGNAL(combGainIChanged(int)), this, SLOT(setCombGainI(int)));@
Is this right? If so, what should I expect to see happen?
EDIT:
Actually, instead of changing that line, can I just add the second line (if correct)? For now, I might as well keep the original GUI working, too.
Thanks. -
Yes replace the original line with the second one that you posted. Then you need to implement the slot setCombGainI(int) such that it updates that value in your GUI.
You would then need a corresponding slot for any other variable, combGainQ say.
If you keep the original connections how can you know that your new signals are being emitted when they should be and with the right values?
I would seriously consider adding a simple unit test. Have a read of the QTest Framework docs. They have a nice "tutorial":http://doc.qt.nokia.com/latest/qtestlib-tutorial.html that explains it all. Trust me it can be very surprising what unit tests can show up in the course of testing. As long as you writie good tests they are very valuable things to have around.
-
[quote author="ZapB" date="1301904635"]Yes replace the original line with the second one that you posted. Then you need to implement the slot setCombGainI(int) such that it updates that value in your GUI.[/quote]
Right, and this is the missing ingredient, isn't it? Currently, setCombGainI() emits this:
@ emit combGainIChanged (combGainI);@
So, what do I do now to "tie together" the code and the GUI?
[quote]You would then need a corresponding slot for any other variable, combGainQ say.[/quote]
Yeah, I figured I'd get one right and then do the other.
[quote]If you keep the original connections how can you know that your new signals are being emitted when they should be and with the right values? [/quote]
I guess I'm missing something. I thought if I maintained the two GUIs, I could verify the new one by comparing its results with the original. Plus, I still have the console output. Or, is this not what you're asking?
[quote]I would seriously consider adding a simple unit test. Have a read of the QTest Framework docs. They have a nice "tutorial":http://doc.qt.nokia.com/latest/qtestlib-tutorial.html that explains it all. Trust me it can be very surprising what unit tests can show up in the course of testing. As long as you writie good tests they are very valuable things to have around.[/quote]
I'll do this, I promise. I just thought it would be better for me to have a little better grasp of what I'm doing here before I went about designing a test for it.
Thanks.
-
[quote author="mzimmers" date="1301916754"][quote author="ZapB" date="1301904635"]Yes replace the original line with the second one that you posted. Then you need to implement the slot setCombGainI(int) such that it updates that value in your GUI.[/quote]
Right, and this is the missing ingredient, isn't it? Currently, setCombGainI() emits this:
@ emit combGainIChanged (combGainI);@
[/quote]I meant that you need to implement a setCombGainI( int ) slot on your GUI class (Widget in the original example). This should modify the text string passed to the QLabel.
As far as being able to maintain your old working GUI I suggest that you do the new work in a branch of your version control system. Then you can go back and forth between the old method and the new one at will.
BTW having a unit test for the calculation part (the class with the properties) does not mean you abandon the existing GUI code. The unit test becomes an executable that exists parallel to your GUI binary. It's just that it tests one aspect (usually one class) of your code-base.
-
I meant that you need to implement a setCombGainI( int ) slot on your GUI class (Widget in the original example). This should modify the text string passed to the QLabel.
OK, so I'm going to modify setValue, right? Apart from (temporarily) changing it to work with only one variable, what else am I going to do? It still seems like I'm missing the "hook up" to a "real" GUI. Am I still going to use the ui->label->setText call for this?
-
Yes that is right. The bit that I think is still missing is modifying the class with the properties to emit the notification signals when you have calculated new values.
Modifying the setData() slot to work with a single int and modifying the connect call should be all that is needed in addition.
I'll try to get a simple QML demo up and running shortly that shows how this will fit together.
-
OK, thanks, Zap. I'll stand by to hear from you on this before I make these changes. So, will I be doing some work within Designer for this upcoming step?
EDIT: hey, Zap...can you give me a sneak preview as to what the call to the new GUI will look like (or at least where to find it in the docs?) That might be enough to get me launched on this.
Thanks.
-
Righto here goes...I have had to split this into multiple posts as the original was too large for a single post. Maybe I should turn this in to a wiki article ;-)
I have chosen to modify the original example that I gave you in the other thread - the one with our custom Widget class and the Generator class. I have renamed the property to combGainI to match your naming scheme so that it is easier for you to see how it would map across to your case.
In this example I have decided to keep the old QWidget based GUI and to extend it with a QML based widget that operates in parallel. This way you can see how both types of GUI can use the same C++ backend as a data source. I could of course added in a third view which was based on QGraphicsView but that is probably too much for a simple example ;-)
I'll present it as if we are starting from scratch but more briefly than before. So let's get started...
In qt-creator create a new Qt C++ project and choose QWidget as the base class of our main widget. Use designer to edit the ui file and add a QLabel and a QDeclarative view and lay them out vertically in the widget as shown below.
!http://www.theharmers.co.uk/simple-example-form.png(designer-form)!
The two parts of the form demonstrate the use of QWidget-based GUI elements and using QML for a declarative approach. For completeness the raw xml for widget.ui is:
@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>494</width>
<height>328</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>CombGainI =</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QDeclarativeView" name="declarativeView">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</widget>
<layoutdefault spacing="6" margin="11"/>
<customwidgets>
<customwidget>
<class>QDeclarativeView</class>
<extends>QGraphicsView</extends>
<header>QtDeclarative/QDeclarativeView</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@The main() function just creates our custom Widget and shows it:
@
#include <QtGui/QApplication>
#include "widget.h"int main( int argc, char* argv[] )
{
QApplication a( argc, argv );
Widget w;
w.show();
return a.exec();
}
@ -
Now we get to the interesting parts. We'll take a look at the Generator class first. The generator class is what is used to calculate new values of a property. Here is the class declaration:
@
#ifndef GENERATOR_H
#define GENERATOR_H#include <QObject>
class Generator : public QObject
{
Q_OBJECT
Q_PROPERTY( int combGainI READ combGainI NOTIFY combGainIChanged )public:
explicit Generator( QObject* parent = 0 );int combGainI() const { return m_combGainI; }
public slots:
void calculateNextValue();signals:
void combGainIChanged();private:
int m_combGainI;
};#endif // GENERATOR_H
@As you can see we declare a single member variable, m_combGainI, which we expose via the Q_PROPERTY macro as a read-only property. That is not to say that we can't change th evalue of the variable, just that its value can only be changed form within the class but not via the property system.
Note that in accordance with the Q_PROPERTY statement we provide a getter function and a notifier signal that we must emit when the property changes.
We also provide a handy function for the purposes of this example that allows a new value of the combGainI property to be calculated, calculateNextValue().
Here is the implementation of the Generator class:
@
#include "generator.h"Generator::Generator( QObject* parent ) :
QObject( parent ),
m_combGainI( 0 )
{
}void Generator::calculateNextValue()
{
// Calculate a new value
++m_combGainI;// Let the world know this property has changed emit combGainIChanged();
}
@As you can see it is very simple. The calculateNextValue() function simply increments our member variable and then emits the appropriate property change notifier signal. Note that the signal implementation is provided by the moc during the build process.
That is all there is to our Generator class. Of course in your real application the calculations will likely be much more complex than this but this is enough to give you an idea of how it all works.
Now let's take a look at the Widget class. We have already layed out the ui for our Widget class consisting of a QLabel and a QDeclarativeView. Here is the declaration of the Widget class:
@
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
namespace Ui {
class Widget;
}class Generator;
class QTimer;
class Widget : public QWidget
{
Q_OBJECTpublic:
explicit Widget( QWidget* parent = 0 );
~Widget();public slots:
void updateCombGainI();protected:
void keyPressEvent( QKeyEvent* e );private:
Ui::Widget ui;
QTimer m_timer;
Generator* m_generator;
};#endif // WIDGET_H
@This is a very simple class. We declare the ui member variable as per usual along with a pointer to a Generator object and a QTimer which is used to periodically call Generator::calculateNextValue().
I have also overridden the virtual QWidget::keyPressEvent( QKeyEvent* ) function in this class. As you'll see below, the implementation of this function simply quits the running application when the user presses the escape key.
-
Here is the implementation of the Widget class:
@
#include "widget.h"
#include "ui_widget.h"#include "generator.h"
#include <QCoreApplication>
#include <QDeclarativeContext>
#include <QKeyEvent>
#include <QTimer>Widget::Widget( QWidget* parent ) :
QWidget( parent ),
ui( new Ui::Widget ),
m_timer( new QTimer( this ) ),
m_generator( new Generator( this ) )
{
ui->setupUi( this );// Use a couple of connections to do something useful. // This one causes new data to be calculated once a second (once the timer is started) connect( m_timer, SIGNAL( timeout() ), m_generator, SLOT( calculateNextValue() ) ); // This one causes the new data to update the GUI connect( m_generator, SIGNAL( combGainIChanged() ), this, SLOT( updateCombGainI() ) ); // Get a pointer to the declarative view QDeclarativeView* view = ui->declarativeView; // We need to tell the declarative view about our C++ object that we wish to expose. // The exposed object and it's API form the interface with which our QML interacts. view->rootContext()->setContextProperty( "generator", m_generator ); // Now load a qml file that binds to properties of this C++ object. view->setSource( QUrl( "qrc:/simple.qml" ) ); // Start the timer off to kick things into motion m_timer->start( 1000 );
}
Widget::~Widget()
{
delete ui;
}void Widget::updateCombGainI()
{
int combGainI = m_generator->combGainI();
QString s = QString( "CombGainI = %1" ).arg( combGainI );
ui->label->setText( s );
}void Widget::keyPressEvent( QKeyEvent* e )
{
switch ( e->key() )
{
case Qt::Key_Escape:
QCoreApplication::instance()->quit();
break;default: QWidget::keyPressEvent( e ); }
}
@Let's look at the parts that implement the QWidget-based part of the GUI first. In the constructor we call
@ui->setupUi( this );@
to instantiate the actual widgets that we layed out in designer. Then we make a couple of connections that cause the timer to trigger a call to Generator::calculateNextValue() and also calls the function Widget::updateCombGainI() when the Generator class emits its notifier signal:
@
// Use a couple of connections to do something useful.// This one causes new data to be calculated once a second (once the timer is started)
connect( m_timer, SIGNAL( timeout() ), m_generator, SLOT( calculateNextValue() ) );// This one causes the new data to update the GUI
connect( m_generator, SIGNAL( combGainIChanged() ), this, SLOT( updateCombGainI() ) );
@And finally in the constructor we start off the timer:
@
m_timer->start( 1000 );
@The other half of the QWidget-based GUI is to actually show the updates in the QLabel. This is done in the function
@
void Widget::updateCombGainI()
{
int combGainI = m_generator->combGainI();
QString s = QString( "CombGainI = %1" ).arg( combGainI );
ui->label->setText( s );
}
@Since we are using the property notifier signal which has no arguments we first need to query the Generator object for the new value. Then we construct a string using that value and set it as the text property of the label. All simple stuff and nothing new here.
-
Now let's consider the declarative approach. Looking at the Widget constructor again, we see that we get a pointer to the declarative view. Using this pointer we first expose our m_generator member variable to the world of QML by using the QDeclarativeContext associated with the view:
@view->rootContext()->setContextProperty( "generator", m_generator );@
This is a very important line. What this means is that within the qml file that we use the actual member variable m_generator from C++ will be available to use in the qml file as an object called "generator".
Think about that for a moment as this is the crucial part of linking our familar world of C++ with the brave new world of QML. The implications in this case are that we can bind properties of QML elements to javascript expressions including references to properties of the "generator" object. If our "generator" object also had writable properties we could set those properties from within QML too.
With this in mind it should be clear that the "generator" object and the API of the Generator class form the programming interface to our application for QML. When exposing objects to QML (or QtScript) it pays to think about what objects you should expose and what properties and invokable functions those objects should have. Choosing wisely is a key to a good design and a clean interface between C++ and QML/javascript.
OK, now that we have exposed the "generator" object (m_generator in C++) we can now proceed to load a qml file:
@
view->setSource( QUrl( "qrc:/simple.qml" ) );
@Here I have decided to compile the qml file into the application to avoid the resource location issues that you know all about ;-) The contents of the resource file, simple.qrc are trivial:
@
<RCC>
<qresource prefix="/">
<file>simple.qml</file>
</qresource>
</RCC>
@Now let's look at the actual content of the QML file. I simply added a new qml using qt-creator and edited it to look like this:
@
import QtQuick 1.0Rectangle {
id: myRect
width: 100
height: 62
color: "#008000"Text { // Here we use the expose "generator" object to set the text text: "CombGainI = " + generator.combGainI; anchors.centerIn: parent } Connections { target: generator onCombGainIChanged: { // This is not very declarative way of toggling the color but // this is just to show how simple it is to do things if ( myRect.color == "#008000" ) myRect.color = "#ff0000"; else myRect.color = "#008000"; } }
}
@As you can see this is a very trivial QML file for demonstration purposes. It consists of a Rect item and within that a Text item. The Rect item has an id of "myRect" so that we can refer to it from elsewhere in the file. We set soem basic dimensions and then set the color to green.
Look carefully at the Text item. The line anchors.centerIn: parent simple tell the layout system to centre the text item in it's parent ie myRect. The magic line though is:
@text: "CombGainI = " + generator.combGainI;@
This establishes what is known as a "property binding". That is, the text property of the Text element is bound to the javascript expression which concatenates the string "CombGainI = " and the combGainI property of the "generator" object that we exposed in the constructor of the Widget class.
Once you have declared this property binding the QML framework does some bookkeeping and notices that the text property is dependent upon the "generator" object's combGainI property. It is kind enough to put in some glue such that anytime the combGainI property changes (and emits the notifier signal) the expression is re-evaluated and the text property updated.
That is the other part of the magic bridge between the worlds of C++ and QML. So to summarise the two aspects are:
Expose objects that have properties from C++ to QML using QDeclarativeContext::setContextProperty()
Use those exposed object's properties in property bindings in your QML documents.
I have added a little extra at the end of the simple.qml file that shows one way in which the background colour of the rectangle, myRect, can be toggled as a result of the combGainI property changing. In this case it is simply toggled between green and red.
When you build and run this example you should see the QLabel and the QML scene changing to show the new value of combGainI once every second. The rect in the QML scene will also flip between red and green.
Anyway that is the end of this long post. I hope it gives you an basic idea of how to couple C++ and QML together in order to display data calculated in C++ in a GUI written with QML.
It is a lot to take in at first but I have tried to highlight the important concepts. Feel free to come back with questions if you have any.
Happy hacking.
-
Hey, Zap -
Thanks a ton for all this work. I will have more questions soon, I'm sure, but right now...I don't see how to go about editing the .qrc file. I've created it, but it won't let me put anything in it. Advice?
Thanks again.
EDIT:
I might as well mention some build errors:
@ view->rootContext()->setContextProperty("soc", soc);@
is giving this:
bq. error: invalid use of incomplete type 'struct QDeclarativeContext'
soc is an instance of my Soc class; I've been using that instead of the m_generator variable. Did I mess this up?
I'm getting a similar error for QKeyEvent.
Thanks...
-
Ah sorry I realised as I was going to sleep last night that I missed a trivial but important aspect to get this to build - you need to edit the .pro file so that it includes the line:
@QT += core gui declarative@
and re-run qmake. This will then tell qmake to add directives to the Makefile to allow the compiler and linker to find the QtDeclarative headers and libraries. Sorry about that.
To edit the .qrc file, just click on it in qt-creator. This will open it in the resource editor. Click on the "Add" button and choose "Add prefix". Then edit the prefix to "/" in the line edit below. Then click on "Add"->"Add Files..." and in the file dialog choose your .qml file. That's it. Your .qml file will now get compiled into your application.
Don't forget to add:
@
#include <QDeclarativeContext>
#include <QKeyEvent>
@in your .cpp file.
-
To make things easier I have uploaded a tarball of the example to my "webserver":http://www.theharmers.co.uk/simpletest.tar.gz. Just download it, unpack it and run qmake && make.