Qt qojbect_cast的使用

在学习《C++ GUI Programming with Qt 4》第四章例子中有如下代码

Cell *Spreadsheet::cell(int row, int column) const
{
    return static_cast<Cell *>(item(row, column));

    //报错
    //return qobject_cast<Cell *>(item(row, column));
}
注释内容报错,查看qobjec_cast。
T qobject_cast ( QObject * object )

本方法返回object向下的转型T,如果转型不成功则返回0,如果传入的object本身就是0则返回0。

在使用时有两个限制:

    1# T类型必须继承自QObject。

    2# 在声明时必须有Q_OBJECT宏。

官方例子如下:

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

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

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

后发现QTableWidgetItem类为纯cpp类,没有继承QObject类,故不能使用qobject_cast方法。

原文地址:https://www.cnblogs.com/weiweiqiao99/p/2072538.html