How to implement UserControl in WinRT - c++

I have created a simple UserControl consisting solely of a Grid and an embraced Image.
Now I want to apply events such as "ManipulationDeltaEvent", etc. for touch-control. When I assign an event-handler like
pic->ActionToken = pic->ManipulationDelta +=
ref new ManipulationDeltaEventHandler(this, &MainPage::SwipeImageEventHandler);
pic->CompletedToken = pic->ManipulationCompleted +=
ref new ManipulationCompletedEventHandler(this, &MainPage::ImageManipulationCompletedEventHandler);
I receive valid EventRegistrationTokens, but when I want to swipe over the control, simply nothing happens (I debugged).
I read about overriding the OnManipulationDelta-method from Windows::UI::Xaml::Controls::Control, but I here I am stuck:
protected:
void OnManipulationDelta
(Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^ e) override {
}
Although only barely related, for C++\CLI it states on MSDN:
The OnManipulationDelta method has no default implementation. Override OnManipulationDelta in a derived class to handle the ManipulationDelta event. Be sure to call the OnManipulationDelta method of the base class so that base classes receive the event.
Please give me a hint, thank you.
EDIT
The overriding is unnecessary

You need to specify ManipulationMode on the control and the control needs a non-null Background or Fill, e.g. Background="Transparent".

Related

How to avoid cast using QToolBox?

I know that cast should be avoided and I´m trying to do it, but I can´t see how to do it using a QToolBox.
The window I´m building has a QToolBox for the user chose which operation he wants to do and inside the toolbox are the specific parameters to each operation. The apply button is outside the QToolBox.
When the user clicks the apply button I have to get which operation he has chosen and its parameters.
The problem is that QToolBox currentWidget() method returns a QWidget that is a class that I can´t change. So I can´t use virtual methods or something like that. The only way I see to get the parameters is using cast.
Here is some code to show my problem:
class BaseOperation : QWidget {
public:
virtual int getParameter() = 0;
}
class Operation1 : public BaseOperation {
...
}
class Operation2 : public BaseOperation {
...
}
...
_ui->toolBox->addItem(new Operation1(this), "OP 1");
_ui->toolBox->addItem(new Operation2(this), "OP 2");
...
QWidget* curItem = _ui->toolBox->currentWidget();
BaseOperation* op = dynamic_cast<BaseOperation*>(op);
op.getParameter();
Is there a better way to do what I want? I thought of using the item index in the toolbox and a hash map to do it, but this does not seem very OOP.
You can track widget changes, map index to concrete Operation class (not using hashmap, but simple switch-case) and then static_cast<> it, but that's what dynamic cast does for you, basically.
Using dynamic cast is perfectly OK in this case, IMO.
A possible different approach that avoids casts entirely is to use setProperty("name", QVariant(value)) to associate the data you need to the widgets, and then get the data back from the current widget using property("name").toInt() - this avoids casts and defining separate classes if what you need is an integer value (or something else reasonably simple)

Any instance access all instances (of a class)

This may seem like a trivial question, or I may have misunderstood previous information/the research I've done so far.
But is it possible to have a object with a function (in C++) that can access all instances of its own type?
In the context of my usage. I wanted to have a Button class, whereby I could simply instantiate multiple Buttons but call to a function could call reference all buttons.
ButtonInstance.isMouseTargetting(cursorCoordinates);
Is this possible? If so is it efficient?
Or should I have the class which owns the Button instances call each instance to check if the mouse coordinates match up?
I'm under the impression you are looking for advice on how to design this.
In the context of my usage. I wanted to have a Button class, whereby I
could simply instantiate multiple Buttons but call to a function could
call reference all buttons.
You want to do this in a button container. A button is not a button container and in a GUI context you already have an established hirerarchy.
Or should I have the class which owns the Button instances call each
instance to check if the mouse coordinates match up?
Yes. You probably already have a window/container class for this.
Your question is more of about Design pattern than C++ itself. Take a look at the Gang of Four book;you will find an appropriate implementation.
You can, for example, make a list of all objects created for a given class,
class Button {
public:
Button() {
_buttonList.push_back( this );
// assign index/handler to this button
}
~Button() {
_buttonList.erase( _handle );
}
static bool isMouseTargeting( float x, float y ) {
for ( auto button : _buttonList ) {
// check if inside
}
return false;
}
private:
static std::list< Button* > _buttonList;
// Handler _handle;
}
This is only a very general example of what you could do. You can use any other container besides a list (entirely up to you), and you have to find a way to index each button (or create a handle) so that you can later erase it in the destructor.
Beware of the default constructors (copy or move). If you don't explicitly create your constructors then some of your buttons will not enter the list, so either make them yourself or delete them.
Button( const Button& button ) = delete;
This is one way to do what you asked, but not necessarily the best solution. It may be simpler to just add the buttons to a non-static container by yourself and search from there.
The short answer is yes. But i will not recommend to put this functionality on the Button class since this will add extra (maybe not expected) responsibility to it. You can achieve the desired behavior by storing your Button objects on some collection and then call a function to check which button is targeted by the mouse.
Another solution would be to store the buttons collection as a member of a higher level class that represents your user-interface. This way you can call a method of this class and check if the mouse cursor is currently on some Button or not. With this design you can add the same support for other GUI elements (if you need to) easily.

Clean OOP design when making a GUI

Say I have two main classes, Application and ApplicationGUI. Application does lots of things and can happily run without any knowledge that ApplicationGUI exists. ApplicationGUI is linked to Application in many ways, it has maybe 50 or 100 different knobs that can change Application's behavior.
ApplicationGUI is a hierarchical structure such that it has many instances of ControlGroup, each containing an arbitrary number of Buttons and Knobs, or even another ControlGroup.
Current design: Upon instantiation of the ApplicationGUI (Application was already running with some set of default parameters), I pass pointers of Application's parameters to various components of the GUI. For example:
my_gui.sound_controlgroup.knob.link_to_param(&(my_application.volume));
If I need to do something more complex, say call a member function of Application, my_application.update_something(), how is this done?
The easy answer is to pass a pointer to my_application to my_gui.sound_controlgroup.knob, but if I only ever need to call one of my_application's functions, it seems like I am giving my knob an option to change all kinds of things that it should even know about (my_application.update_something_unrelated(), for instance). What is the cleanest thing to do in this case?
Additionally, this either requires making all subcomponents of ApplicationGUI public or having a function at each stage of the hierarchy to forward that pointer to the bottom level. This leads to quite a lot of functions. Is this a necessary consequence of a UI with a lot of knobs?
Quick Short Answer
In order to implement interaction between your non GUI related Application object and your GUIApplication object I suggest apply the "Property and Method and Event Handler" paradigm.
Extended Complex Answer
G.U.I. development is one of the most practical implementation of the O.O.P. theory.
What is the "Property and Method and Event Handler" paradigm ?
That means build, both Non GUI Classes, and GUI Classes, should have:
Properties
Methods
Event handlers
"Events" (Handlers) are also called "Signals", and are implemented with functions pointers. Not sure, but, I think your "knob" (s) are like Event Handlers.
It's a technique to apply the my_application.update_something_unrelated(), you have in your question.
Since, C++, like Java, does not have property syntax, you may use "getter" and "setter" methods, or use a "property" template.
For example, if your application has a Close method, you may declare something like the following examples.
Note: They are not full programs, just an idea:
// Applications.hpp
public class BaseApplicationClass
{
// ...
};
public class BaseApplicationClientClass
{
// ...
};
typedef
void (BaseApplicationClientClass::*CloseFunctor)
(BaseApplicationClass App);
public class ApplicationClass: public BaseApplicationClass
{
// ...
public:
Vector<BaseApplicationClientClass::CloseFunctor>
BeforeCloseEventHandlers;
Vector<BaseApplicationClientClass::CloseFunctor>
AfterCloseEventHandlers;
protected:
void ConfirmedClose();
public:
virtual void Close();
} Application;
// Applications.cpp
void ApplicationClass::ConfirmedClose()
{
// do close app. without releasing from memory yet.
} // void ApplicationClass::ConfirmedClose()
void ApplicationClass::Close()
{
// Execute all handlers in "BeforeCloseEventaHandlers"
this.ConfirmedClose();
// Execute all handlers in "AfterCloseEventaHandlers"
} // void ApplicationClass::Close()
// AppShells.cpp
public class AppShell: public BaseApplicationClientClass
{
// ...
};
void AppShell::CloseHandler(ApplicationClass App)
{
// close GUI
} // void AppShell.CloseHandler(ApplicationClass App)
void AppShell::setApp(ApplicationClass App)
{
App->BeforeCloseEventHandlers->add(&this.CloseHandler);
} // void AppShell.setApp(ApplicationClass App)
void main (...)
{
ApplicationClass* AppKernel = new ApplicationClass();
ApplicationGUIClass* AppShell = new ApplicationGUIClass();
AppShell.setApp(App);
// this executes "App->Run();"
AppShell->Run();
free AppShell();
free AppKernel();
}
UPDATE: Fixed type declaration from global function pointer (a.k.a. "global functor") to object function pointer (a.k.a. "method functor").
Cheers.
Do you know about the model-view-controller (MVC) paradigm? Think of the Application class as the model, the entire hierarchy of GUI controls as the view, and the ApplicationGUI class as the controller. You don't want Application to know about the controls, and you don't want the controls to know about Application; they should both talk only to the controller, ApplicationGUI.
Using ApplicationGUI as the conduit for communication between controls and Application means that you can test either Application or controls by replacing the other with a mock object, for example. More importantly, you can change either the controls or Application without impacting the other. Individual controls don't need to know anything about Application -- they only need to know where to send their value when it changes. And Application shouldn't care whether an input comes from a knob or a slider or a text field. Keeping those two areas separate will simplify each of them.
Additionally, this either requires making all subcomponents of
ApplicationGUI public or having a function at each stage of the
hierarchy to forward that pointer to the bottom level. This leads to
quite a lot of functions. Is this a necessary consequence of a UI with
a lot of knobs?
A given control shouldn't care what value it manages. It doesn't need to know whether the value determines the number of alien invaders on the screen or the coolant level in a nuclear reactor. It does needs to know things like the minimum and maximum values, label to display, scale to use (linear, log, etc.), and other things that directly impact the way the control works. It also needs to know who to tell when something changes, and it might need some way to identify itself.
With that in mind, ApplicationGUI doesn't need to expose accessors for every possible parameter of Application. Instead, it should have a general method that lets controls send it updates. When a control changes, it should send a message to ApplicationGUI containing the new value(s) along with its identifier, and ApplicationGUI takes care of mapping that identifier to some particular parameter of Application. A control's identifier could be some identifying number that's given to it, or it could just be a pointer to the control.
Of course, sometimes communication has to go the other way, too... a GUI usually has both inputs and outputs, so you'll want some means for ApplicationGUI to get updates from Application and update the state of the GUI. For the same reasons described above, Application should send those updates to ApplicationGUI and let the latter find the actual UI components that need to be changed.

C++/Qt - multiple inheritance with QGraphicsItem doesn't work as expected

I recently met a strange problem of my little program and it would be great if you help me to get the reason of this behavior.
My task is quiet simple - I want to use Qt Graphics Framework to show some objects and I want Box2D to calculate bodies position. So my class hierarchy looks like the following:
I have 1 base abstract class B2DObject. It contains some Box2D staff + some common parameters for its successors (names, some flags, etc.). It also has couple of pure virtual functions that will be reimplemented in successor classes.
Then I implement some classes that represent basic shapes: circles, rectangles, polygons, etc. I am doing it in the following way:
class ExtendedPolygon : public B2DObject, public QGraphicsPolygonItem { ... };
class ExtendedCircle : public B2DObject, public QGraphicsEllipseItem { ... };
etc.
(for those who are not familiar with Qt, QGraphics***Item is inherited from QGraphicsItem).
Also I inherited QGraphicsScene and reimplemented its mousePressEvent. In this function I request an object placed at some point on the screen using QGraphicsScene::itemAt function (which returns QGraphicsItem*), convert it to B2DObject* and try to get some internal field from this object:
void TestScene::mousePressEvent (QGraphicsSceneMouseEvent *event)
{
QGraphicsItem* item = itemAt (event->scenePos ());
if (item)
{
B2DObject* obj = reinterpret_cast < B2DObject* > (item);
QString objName = obj->Name(); // just for example,
// getting other internal fields has
// the same effect (described below)
// use retrieved field somehow (e.g. print in the screen)
}
// give the event to the ancestor
}
Unfortunately, dynamic_cast will not work here because these classes are completely unrelated.
Then I create necessary objects and add it to my scene:
ExtendedPolygon* polygon = new ExtendedPolygon (parameters);
polygon->setName (QString ("Object 1"));
...
TestScene scene;
scene.addItem (polygon);
(for those who are not familiar with Qt, here is the prototype of the last function:
void QGraphicsScene::addItem(QGraphicsItem *item);
I guess it just stores all items in internal index storage and calls QGraphicsItem::paint (...) when item needs to be repainted. I suppose QGraphicsScene doesn't make any significant changes to this item).
So my problems start when I run the program and click on an item on the screen. TestScene::mousePressEvent is called (see a piece of code above).
Mouse click position is retrieved, item is found. Casting works fine: in the debugger window (I'm using Qt Creator) I see that obj points to ExtendedPolygon (address is the same as when I add the item to the scene and in the debugger window I can see all the fields). But when I get some field, I receive garbage in any case (and it does not matter, what I'm trying to get - a QString or a pointer to some other structure).
So first of all, I would like to get any advice about my multiple inheritance. In 95% of cases I try to avoid it, but here it is very effective in the programming point of view. So I would appreciate it if you provide me with your point of view about the architecture of the classes hierarchy - does it even suppose to work as I expect it?
If on this level everything is quite fine, then it would be great if someone gets any idea why doesn't it work.
I have some ideas about workaround, but I really would like to solve this problem (just in order not to repeat the same error anymore).
Looks like I've found the root cause of my problem. It was just lack of knowledge regarding how multiple inheritance really works on data layer.
Let's assume that we have 2 basic classes, A and B. Each of them provides some internal data fields and some interfaces.
Then we create a derived class AABB, inheriting both A and B:
class AABB : public A, public B {...}
AABB could add some additional data fields and reimplement some of the interfaces, but it is not necessary.
Let's create and object of class AABB:
AABB* obj = new AABB ();
For example, obj points at address 0x8416e0. At this address starts data from ancestor class A. Data from ancestor class B starts with some offset (it should bw equal to sizeof (A)), for example, at 0x841700.
If we have some function f (B* b), and if we pass a pointer at AABB object to that function (like this: f (obj), obj is created above), actually not obj start address is passed, but rather a pointer at a start of B data section of AABB object.
Thus this misunderstanding of multiple inheritance inner works has led me to the problem I've got.
I guess Qobjects and multiple inheritance has been already treated. As an example: QObject Multiple Inheritance

Is it possible to enumerate the wxFrame children in wxWidgets?

I'm using the wxGlade designer to generate the GUI for a small application.
It generates a class, inherited from wxFrame, which is the main application window.
In order to facilitate the maintenance, I'd like to avoid writing additional code in this generated class.
But all the widgets created with the wxGlade are actually created in the auto-generated method do_layout() and it is not possible to access them outside the scope of that generated method in the generated class.
Is there a way to get pointer of certain widget outside that generated class - by name, by type, by enumerating the children or something like that?
All classes inherited from wxWindow (wxFrame being one of them) have a function "GetChildren", which returns a list of child windows that you can then enumerate over. If you are looking for a specific field by name then use the "FindWindow" function.
Actually I found the answer myself:
wxWindowList & children = myframe->GetChildren();
for ( wxWindowList::Node *node = children.GetFirst(); node; node = node->GetNext() )
{
wxWindow *current = (wxWindow *)node->GetData();
// .. do something with current
}
May I recommend you try wxFormBuilder. I also used wxGlade before, but it presents too much constraints on how you use it. For example, with wxFormBuilder you can select 'visibility' (public,protected,private) for each control on the form. It can also generate virtual functions for event handlers, so you just derive your class from wxFormBuilder generated class and implement those functions.