zoukankan      html  css  js  c++  java
  • Qt中的强制类型转换

    在C++开发中经常要进行数据类型的强制转换。

    刚开始学习的时候,直接对基本数据类型强制类型转换,如float fnum = 3.14; int num = (int)fnum;

    随着C++标准的发展,又提供了dynamic_cast、const_cast 、static_cast、reinterpret_cast等高级安全的强制转换方法。

    dynamic_cast: 通常在基类和派生类之间转换时使用,run-time cast。
    const_cast: 主要针对const和volatile的转换。
    static_cast: 一般的转换,no run-time check.通常,如果你不知道该用哪个,就用这个。
    reinterpret_cast: 用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整形数。

    QT框架提供的强制类型转换方法:

    qobject_cast  qobject_cast()函数的行为类似于标准C ++ dynamic_cast(),其优点是不需要RTTI支持,并且它可以跨动态库边界工作。

    QObject *obj = new QTimer;          // QTimer inherits QObject

    QTimer *timer = qobject_cast<QTimer *>(obj);

    // timer == (QObject *)obj

    QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);

    // button == 0

    qgraphicsitem_cast  场景视图Item类转换

    QGraphicsScene和 QGraphicsItem 的大多数便利函数(例如:items(),selectedItems()、collidingItems()、childItems())返回一个 QList<QGraphicsItem *> 列表,在遍历列表的时候,通常需要对其中的 QGraphicsItem 进行类型检测与转换,以确定实际的 item。

    以下代码出处:https://blog.csdn.net/liang19890820/article/details/53612446

    QList<QGraphicsItem *> items = scene->items();

    foreach (QGraphicsItem *item, items) {

        if (item->type() == QGraphicsRectItem::Type) {        // 矩形

            QGraphicsRectItem *rect = qgraphicsitem_cast<QGraphicsRectItem*>(item);

            // 访问 QGraphicsRectItem 的成员

        } else if (item->type() == QGraphicsLineItem::Type) {      // 直线

            QGraphicsLineItem *line = qgraphicsitem_cast<QGraphicsLineItem*>(item);

            // 访问 QGraphicsLineItem 的成员

        } else if (item->type() == QGraphicsProxyWidget::Type) {    // 代理 Widget

            QGraphicsProxyWidget *proxyWidget = qgraphicsitem_cast<QGraphicsProxyWidget*>(item);

            QLabel *label = qobject_cast<QLabel *>(proxyWidget->widget());

            // 访问 QLabel 的成员

        } else if (item->type() == CustomItem::Type) {         // 自定义 Item

            CustomItem *customItem = qgraphicsitem_cast<CustomItem*>(item);

            // 访问 CustomItem 的成员

        } else {

            // 其他类型 item

        }

    }

    需要注意的是,为了使该函数正确使用自定义Item,需要在QGraphicsItem子类中重写type()函数才行。

    class CustomItem : public QGraphicsItem

    {

      public:

         enum { Type = UserType + 1 };

         int type() const override

         {

             // Enable the use of qgraphicsitem_cast with this item.

             return Type;

         }

         ...

    };

    qvariant_cast  QVariant类型转换为实际的类型

    Returns the given value converted to the template type T.

    This function is equivalent to QVariant::value().

     

    等等...

  • 相关阅读:
    系统安全
    导出csv文件示例
    MsChart在MVC下的问题
    记录一些测试的结果
    使用CTE减少统计子查询
    otl获得sql出错位置(oracle)
    在sql语句中使用plsql变量
    Java经典编程题50道之二十四
    Java经典编程题50道之二十三
    Java经典编程题50道之二十二
  • 原文地址:https://www.cnblogs.com/MakeView660/p/11045437.html
Copyright © 2011-2022 走看看