In many cases, I would like to override a Qt class to extend or modify its behavior. But almost all Qt classes uses an internal private class such as QNetworkDiskCachePrivate inside QNetworkDiskCache. I know there are advantages of this approach. But there is a HUGE problem of the private class: it makes overriding the class a lot more difficult. With other C++ class library with source code, I usually override a class method, copy the code from the implementation in the parent class and make small modifications here and there to achieve the behavior I want. However, in Qt, the private class is not exported and not visible to the derived class. Since Qt classes maintains the critical internal data in the private class through the "d" member, the invisibility of the private internal class makes the possibility of behavior extension very limited. You can only play with the few exposed public method.
I tried extracting the entire source files of the class and renaming the class name and file names. But the Qt class library is so much intertwined that extracting a single class out of it is messy as well in most cases.
Do I miss something here? Or Qt classes are just really bad in terms of extendability?
Qt classes are better than most in terms of extendability; they often have hooks to change their behavior without resorting to copying and pasting an entire method. Having said that, if the generally accepted methods of extending don't work, yes the Qt classes are harder to hack. That's probably a good thing because copying-pasting-and-modifying the base class implementation means that your derived class won't get any improvements or bugfixes that are made in the base class implementation.
If you want to do it, you're going to need to convince your build system to let you include the private headers and then refer to the private classes from your new implementation. Pay attention to the disclaimer in the Qt docs; when you do this you are opening yourself up to breakage with every new version of Qt that is released (Qt only guarantees the public API, and you're messing with its internals). Qt's public API is wonderfully readable and documented; the internal code can be pretty cryptic, so you really, really want to be sure that you can't accomplish what you want with the public API. If you're still resolved to use the private class stuff, this might help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With