简体   繁体   English

将不同类型的对象存储在容器中

[英]Store objects of different types in a container

I have two objects QColor , QFont and there's a possibility of adding more. 我有两个对象QColorQFont并且有可能添加更多对象。
I want to store that objects in a container for instance QList but this container needs one type of data. 我想将该对象存储在例如QList的容器中,但是此容器需要一种类型的数据。

QFont font = QFontDialog::getFont(&fontDlgRet, initFont, parent);
QColor color = QColorDialog::getColor(initColor, parent);

Is there a container accepts adding different types of objects? 是否有一个接受添加不同类型对象的容器?

Is there a container accepts adding different types of objects? 是否有一个接受添加不同类型对象的容器?

Yes: QVariantList, QVariantMap, QVariantHash. 是:QVariantList,QVariantMap,QVariantHash。

You can also roll your own manually, like std::vector<QVariant> for instance. 您也可以手动滚动自己的滚动条,例如std::vector<QVariant>

See http://doc.qt.io/qt-5/qvariant.html 参见http://doc.qt.io/qt-5/qvariant.html

Also, note that loosing type information like this is frowned upon and bad practice. 另外,请注意,像这样丢失类型信息是不受欢迎的,也是不明智的做法。 If you have a finite set of types you can use std::variant instead. 如果您有一组有限的类型,则可以改用std::variant

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

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