How to create custom wheel events in Qt? - c++

I found multiple questions regarding custom QEvents. So since Qt 4 we have to derive from QEvent and register our custom type. There are some samples around.
What I want is a QWheelEvent with custom data in it. So the event should be usable everywhere as a "normal" QWheelEvent but if I want to I can check for my CustomWheelEvent type and retrieve the data from it.
The problem is that I don't know how to register the type because the constructor of the QWheelEvent does not offer the possibility to set the event type.
Looking at the internals of QEvent I could simply set the protected member Type t to an event type returned by registerEventType(). Does this have side-effects?
If I simply derive from QWheelEvent I can also use dynamic_cast to find out if it is my own event carrying my custom data. A simple static cast after a check for the type should be better though.
Any thoughts on this?
Edit: I have tried the approach with dynamic_casts but the cast seems to fail. This is possible if Qt deep-copies the event internally, so that a new QWheelEvent is created and passed through the event system instead of my CustomWheelEvent. This way my own data (defined in CustomWheelEvent) is stripped off the object and only the base class (QWheelEvent) is handled. I originally thought that the pointer is used as it is, so that I can rely on the dynamic_cast. More information on this is appreciated!

Read this:
Qt: Defining a custom event type
I think that you do want to register the event and that it will return a new unused type (number). In an example there, the static object sets the value to QEvent::None. The primary problem I see with the solution there is that it is not thread safe, so, be sure to make this thread safe somehow (like maybe call the static type method before things start so that they are initialized before it could be used in a multi-threaded way).

Related

wxWidgets wxFileSystemHandler::OpenFile() never gets called

I extended the class wxFileSystemHandler to handle special protocols I use in my application. My implementation of wxFileSystemHandler::CanOpen() is called, recognizes the protocol and returns TRUE. But my implementation of wxFileSystemHandler::OpenFile() never gets called. I inspected the wxWidgets code and saw that the CanOpen() member function is called by the pointer that I registered. But when a call to OpenFile() is made they pass the pointer to a wxFileSystem::MakeLocal() member function that tries to get another pointer inside a hash map that, obviously, is not my instance.
Someone got a problem like this before?
Not sure what exactly are you doing, i.e. when do you expect your handler to be called, but in any case MakeLocal() is supposed to create a new instance of the same class if you mark the object as being dynamically creatable using wxRTTI macros and use the object as given otherwise. So if you really need the same object to be reused, you probably need to use wxDECLARE_ABSTRACT_CLASS() in its class. But OTOH why is it a problem to make a new instance?

serialize a subclass, then deserialize it back into the subclass

Problem Introduction
I want to serialize a Message instance to send it over the network, then receive it, and deserialize the data back into an identical Message instance, which not a problem.
The problem is that I would like others to be able to subclass the Message class, but then deserialization becomes difficult, because I don't know which subclass the serialized data is from, so I don't know which deserialization function to use.
Serialization is easier, because I can create an abstract serlialize method that subclasses would have to implement. This way, at runtime, I can just call Message::serialize().
Before the serialization occurs, all I have is a pointer to a Message instance. After the deserialization, I would like to have a pointer to the Message instance (not a pointer to a subclass of the Message class).
I have come up with a few solutions, but I don't particularly like any of them because they seem like it would be difficult to maintain. I would use them if i have to, but I'm wondering if there are other ways.
I am doing this in C++.
Problems I've run into while trying to solve bigger problem
1. Identifying which subclass the serialized data is of
I need to identify which subclass the serialized data is of in order to determine which deserialization function to use. The following are possible solutions I've thought of so far:
Serialization protocol; I can make the first byte be a character which can act as a type identifier so I can figure out which subclass it is.
This makes me wonder where I would get such a unique identifier from? Is there a way to get a unique identifier for a subclass in C++? perhapse, something similar to Java's getCanonicalName()?
2. Performing the deserialization
After determining which subclass the Message instance is of, I need to execute the deserilization function, but my immediate solutons are messy. Here are some possible solutions I've thought of so far that I would like to improve upon, and avoid otherwise:
Big switch statement; I would identify whuch subclass the message is, then switch on the subclass type, and have a case for each subclass that performs the deserialization. I would like to avoid this approach for a few reasons:
Whenever one subclasses Message, they would have to add a case to the switch statement, which would undesirable, because the existence of the switch statement is not obvious to those subclassing Message.
It can become a very large switch statement, which decreases readability.
Build a map which maps subclass IDs to deserialization functions; an entry for each subclass of the Message class would be inserted into the map, so after receiving the Message instance from the network, and determining the subclass type, I can look up the deserialization function in the map, and call it. There are issues with this solution:
I can't think of a way to force subclassers of Message to insert an entry into this map at compile time.
Thanks for reading everything.

Is it possible for d_ptr to be NULL when Object is valid and alive?

I have a class MyAction which derives from the QWidgetAction which derives from the QAction.
When I call QWidget::addActions(QList<QAction*> actions), I have exception on trying to get d_ptr and use it (inside QWidget, not by myself) from action in list:
QActionPrivate *apriv = action->d_func();
apriv->widgets.append(this);
Code above is taken from QWidget source file. By the way, my action is placed in actions list as cast of this pointer which of type MyAction:
actions->push_back(this);
I think that the reason of exception in that that I trying to push into QList my class MyAction, casting const this pointer to QAction*.
If d-pointer pattern is used properly then it never can be null.
D-pointer have to point to valid memory block which will live as long as object lives.
Only exception for this role are classes implementing copy on write which provide null state (for example QString), but this never applies to QObjects.
Your problem must be result of some dangling pointer or other memory issue. Or incorrect type casting. In such cases call stack doesn't have to point to source of problem, problem can be almost anywhere.
I recommend to run your program with valgrind or other memory checking tool. Or some static analysis tool.
You should never use d_func() from client code. The whole point of the pimpl idiom is to stay away from the implementation details and that the library can freely change implementation details like data representation, internal methods and so on.
That is, d_func() along with d_ptr is meant for internal usage. If you need to access it for some reason, that means you seem to violate the design principle of the library, or you are trying to access something that should be exposed to the API, but was not yet needed.
Based on your exact use case - which we do not know, I would suggest to consider these alternatives.
The problem was in that I created MyAction variable on the stack, so, actually, QObject wasn't alive when I'm trying to pass it to QWidget function. That's why I couldn't get d-pointer different from NULL. I couldn't knew that object was actually dead, all strings and variables inside my action was valid.

Member pointers or reference arguments?

I have the following problem.
I got a class PluginLoader which oversees loading of plugins. It divides sub-stages of work to other classes like Plugin. Plugin calls functions of PluginLoader in its processing. Let's call that function AddData. Here, PluginLoader has to check if the data it receives is duplicate. For that, it uses a ConflictResolver class. Now, my problem is how to make an object of ConflictResolver available to PluginLoader. There are 3 ways I see out of this.
Use a ConflictResolverFactory class and create an object of ConflictResolver for PluginLoader.
Pass a constructed ConflictResolver* to the PluginLoader via its constructor or a member function SetConflictResolver and store it in a member variable and use it later. Both ways have drawbacks. If I pass it in the constructor, I will have to throw if the pointer is NULL. And I can't use exceptions as it is the custom here. If I pass it via SetConflictResolver, there is no way that I can guarantee that that function will be actually called by the user. Or I will have to check whether the member ConflictResolver* is NULL everywhere I use it.
Pass a ConflictResolver & to PluginLoaders Load method where all the work will be done. In turn, Plugins Load method has to accept a ConflictResolver & as well (though it has no use for it) and pass that back to AddData where PluginLoader will be able to use it.
Third method is safer compared to second. However, I have to pass around a reference even when it is not used.
If the first method cannot be used, what is the best way to do this?
Apologies for the wall :wq!
You could pass a ConflictResolver& to the PluginLoader constructor. You can now guarantee that the object is not null.

References vs information hiding C++

I need suggestions on how to solve the type of problems described below. I'm fairly new at C++ and OO-design.
I've learnt:
Pointers shall be avoided when ever they can be replaced by references.
Objects shall have no knowledge of objects that they don't need to know about.
But when creating objects having references to other objects we must pass these references as input arguments to the constructor. Thus we need to know about objects we should not not know anything about.
But look at the following example:
Suppose I have a object "Menu" that needs to have it's own timer object "Timer". I'd like to implement this association as a reference.
The object MenuHandler aggregates a lot of Menu objects but shall not have any knowledge about Timer objects. But when the MenuHandler creates a Menu object it must pass a Timer reference argument to the constructor. Thus, ****MenuHandler** must know about **Timer****.
Any suggestions on how to treat these kind of problems?
I'd hesitate to bless your choice of words when it comes to the two numbered points. They're a sign you're on the right way learning C++, but they might be misleading to other novices. When I take a look at your concrete examples, this becomes more obvious.
A MenuHandler should not create menus. The content of menus is determined by by the application, so the application object (or the Controller part, if you've implemented Model-View-Controller) should create menus. The MenuHander merely takes ownership of menus created elsewhere.
Also, it may make sense to give each menu its own timer. That means the relation can be described as "Has a"; the menu has a timer. The relationship usually implmented by references can be described as "Knows a" (the inheritance relationship is usally called "Is a"). If each Menu object has a Timer, it can be a member, and initialized by the Menu constructor(s). The Timer object internally may obtain a reference to the system clock in its constructor, but that's not your concern.
Why not simply make the Timer object a member (by value) of the Menu class?
I find that I produce better (more maintainable, faster, etc) code and that I'm more productive using references in C++ than I would be solving the same problem with pointers... I think the traditional answer to your example would be to have a factory object that creates menus. In this way, the MenuHandler doesn't need to know about the Timer class.
The MenuHandler creates a Timer object, passes it into the Menu constructor, and forgets about it. That seems entirely reasonable.
If the MenuHandler unnecessarily kept a reference to the Timer, that would be against the advice point #2.
In a more general case where you need to provide a class to another class in order to do some kind of callback, you avoid mutual dependency (both know each other) by using an interface.
Class A derives from the interface. Class B accepts the interface as paramater in the constructor and calls the virtual function from that interface when needed.
Also check the observer design pattern.
For #1 Be very careful with the lifetime of your objects. References are no that suitable to handle dynamic graph of objets ( like your menu, menuhandler, timer, etc... ). What if you want to change the timer object later ?
It's not a good idea to have references as members in a class if the lifetime of referenced objects is not really known.
Avoiding pointer does not mean using references everywhere, you should have a look at smart pointers which will be more suitable for what you want to do.