简体   繁体   English

Qt命令模式QHash / QMap

[英]Qt Command Pattern QHash/QMap

I've recently implemented a command design pattern in Java with the use of: 我最近使用以下命令在Java中实现了命令设计模式:

private HashMap<Component, CommandInterface> commands;

Where Component is any Java Component ( JButton , JMenuItem , ...) and CommandInterface is an interface for my Command-Classes. 其中Component是任何Java组件( JButtonJMenuItem ,...),而CommandInterface是我的Command-Classes的接口。

So my question is: How can I accomplish this with C++/Qt ? 所以我的问题是:如何使用C ++ / Qt完成此操作?

I've already used QMap and QHash , but both of them need an overloaded operator ( operator< or operator== ) for their Key -values. 我已经使用QMapQHash ,但他们都需要一个重载运营商( operator<operator== ),为他们的Key -值。

Is the only possible way to derive from QObject and overload operator< ? 是从QObject和重载operator<得出的唯一可能方法吗?

Thanks in advance. 提前致谢。

One very important difference between Java and C++ is that C++ makes a distinction between an object pointer (reference in Java) QObject* o; Java和C ++之间的一个非常重要的区别是C ++区分了对象指针(Java中的引用) QObject* o; and an object value QObject o; 和对象值QObject o;

That being said, Qt strongly encourages to create the QObject on the heap (using new). 话虽这么说,Qt强烈鼓励在堆上创建QObject(使用new)。 So you end up with QObject pointers QObject* . 因此,您最终得到了QObject指针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. 但是,不要忘记管理对象的生命周期,因为您没有像Java那样的垃圾收集器。 You can use the Qt tree ownership for convenience, depending on your needs : http://doc.qt.io/qt-5/objecttrees.html 您可以根据需要使用Qt树所有权以方便使用: http : //doc.qt.io/qt-5/objecttrees.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM