0

I've recently implemented a command design pattern in Java with the use of:

private HashMap<Component, CommandInterface> commands;

Where Component is any Java Component (JButton, JMenuItem, ...) and CommandInterface is an interface for my Command-Classes.

So my question is: How can I accomplish this with C++/Qt ?

I've already used QMap and QHash, but both of them need an overloaded operator (operator< or operator==) for their Key-values.

Is the only possible way to derive from QObject and overload operator< ?

Thanks in advance.

chrizbee
  • 145
  • 1
  • 13

1 Answers1

0

One very important difference between Java and C++ is that C++ makes a distinction between an object pointer (reference in Java) QObject* o; and an object value QObject o;

That being said, Qt strongly encourages to create the QObject on the heap (using new). So you end up with QObject pointers QObject*. Then your hashmap will work because comparing the pointers is like comparing integers.

QHash<QObject*, CommandInterface*> commands;

Do not forget to manage the lifetime of your objects though, you do not have a garbage collector like in Java. You can use the Qt tree ownership for convenience, depending on your needs : http://doc.qt.io/qt-5/objecttrees.html

ymoreau
  • 3,402
  • 1
  • 22
  • 60
  • Didn't know, you can use a pointer as the `Key` for `QHash` because of the `qHash()` function that needs to be provided. Thank you, I will give it a go ! – chrizbee Nov 17 '17 at 10:33
  • @ChristianB as I said a pointer is just an integer value (the memory address) so it can be used as such, and Qt provides `qHash()` for most of common C++ types and Qt data and container classes (QString, QVector etc). – ymoreau Nov 17 '17 at 10:52