Problems with Open-Source Downloads read and

[SOLVED]qobject_cast<t> confusion

  • hello,

    I was using an example out of a book callled "programming a gui with qt4 second edition" (running qt5). bassically in an example in which we were making a spreadsheet, the author used the following algorithm to open a file in the recent files section.

    void MainWindow::openRecentFiles()
    QAction *action = qobject_cast<QAction *>(sender());

               //loadFile takes in the files name and loads the file


    I know that sender() will get the value of the sender of the signal an return a pointer to the object that called it. qobject_cast will then use it's argument (sender()) to cast it to the specified type(QAction). however can't i just do the following:

        QAction *action = sender();

    any help is greatly appreciated

  • qobject_cast is more like a safe way of casting. When the conversion is not possible, it returns NULL. Doing like you said, an impossible conversion would raise a runtime error.

  • Lifetime Qt Champion


    No because sender() returns a QObject * and not the type of object that emitted the signal. You could also be calling that slot from different places like a QPushButton or even directly from the code thus adding more complexity on the handling inside your slot.

    Hope it helps

  • Thanks for the replies, really helps :)

Log in to reply