QVariant与std :: shared_ptr

cho*_*syg 6 c++ qt

我有以下问题,我正在使用

Q_DECLARE_METATYPE( std::shared_ptr<int> );
qRegisterMetaType< std::shared_ptr<int> >();
QMetaType::registerComparators< std::shared_ptr<int> >();
Run Code Online (Sandbox Code Playgroud)

std::shared_ptr<int>与例如QListModel 一起使用.我需要一个行为

QVariant::fromValue( std::shared_ptr<int>( new int(5) ) ) == QVariant::fromValue( std::shared_ptr<int>( new int(5) ) )
Run Code Online (Sandbox Code Playgroud)

是真的.上面的代码在这里返回false,因为std::shared_ptr<int>::operator== ()比较了原始指针.是否可以注册标准运算符以外的比较器QMetaType::registerComparators

Joh*_*nck 5

您可以尝试使用registerConverter()允许将隐式转换为shared_ptr<int>常规int,然后以这种方式进行比较。显然,您不会这样做registerComparator()。一种替代方法是包装shared_ptr<int>您自己的类并以所需的方式实现比较。

或退房Q_DECLARE_SMART_POINTER_METATYPE