What is qobject_cast?

前端 未结 2 1188
既然无缘
既然无缘 2020-12-29 06:13

Could someone explain in as simple terms as possible (or as simple as you would like) what qobject_cast is, what it does and why we would need to cast one class

2条回答
  •  粉色の甜心
    2020-12-29 06:35

    qobject_cast is same thing as dynamic_cast, but works only for children of QObject. It doesn't require RTTI and it works much faster, because it is not possible to use QObject in multiple inheritance.

    Don't hesitate to do self-research and to read some basic things about OOP and C++. Especially about polymorphism. And don't hestiate to read Qt documentation, it contains a lot of easy-to-understand examples.

    A resent usage of qobject_cast is getting a pointer to a class inside a slot:

    QObject::connect( btn, &QPushButton::clicked, this, &MyClass::onClicked );
    void MyClass::onClicked()
    {
        // How to get pointer to a button:
        QObject *p = sender();
        // It's QObject. Now we need to cast it to button:
        QPushButton *btn = qobject_cast( p );
        Q_ASSERT( btn != nullptr ); // Check that a cast was successfull
        // Now we can use a QObject as a button:
        btn->setText( "We just clicked on a button!" );
    }
    

提交回复
热议问题