qgraphicsitem_cast: replace runtime with compile-time check

Specialize the cast template for QGraphicsItem, where we can skip the
runtime comparisons of the type.

In addition, replace the runtime check for QGraphicsItem::Type with a
compile time check in the main template.

We need to do both so that we correctly cast up to QGraphicsItem for
custom item types that don't provide their own Type alias.

Pick-to: 6.8
Change-Id: Ic1bff3404fe890747865ce1349cddbcfebb3b77b
Reviewed-by: Axel Spoerl <axel.spoerl@qt.io>
(cherry picked from commit 7af5912e61160681be736ff07a1cd0a0f6b28944)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Volker Hilsheimer 2025-04-01 12:52:58 +02:00 committed by Qt Cherry-pick Bot
parent 9b8655cf0d
commit 6ff7f71c31

View File

@ -969,15 +969,33 @@ private:
template <class T> inline T qgraphicsitem_cast(QGraphicsItem *item)
{
typedef typename std::remove_cv<typename std::remove_pointer<T>::type>::type Item;
return int(Item::Type) == int(QGraphicsItem::Type)
|| (item && int(Item::Type) == item->type()) ? static_cast<T>(item) : nullptr;
constexpr int ItemType = int(Item::Type);
if constexpr (int(Item::Type) == int(QGraphicsItem::Type))
return static_cast<T>(item);
else
return (item && ItemType == item->type()) ? static_cast<T>(item) : nullptr;
}
template <class T> inline T qgraphicsitem_cast(const QGraphicsItem *item)
{
typedef typename std::remove_cv<typename std::remove_pointer<T>::type>::type Item;
return int(Item::Type) == int(QGraphicsItem::Type)
|| (item && int(Item::Type) == item->type()) ? static_cast<T>(item) : nullptr;
constexpr int ItemType = int(Item::Type);
if constexpr (ItemType == int(QGraphicsItem::Type))
return static_cast<T>(item);
else
return (item && ItemType == item->type()) ? static_cast<T>(item) : nullptr;
}
template <>
inline QGraphicsItem *qgraphicsitem_cast<QGraphicsItem *>(QGraphicsItem *item)
{
return item;
}
template <>
inline const QGraphicsItem *qgraphicsitem_cast<const QGraphicsItem *>(const QGraphicsItem *item)
{
return item;
}
#ifndef QT_NO_DEBUG_STREAM