qobject_cast<>() application

qobject_cast() performs a dynamic cast on the QObject class. The behavior of the qobject_cast() function is similar to the standard c++ dynamic_cast(). Its advantage is that it does not require RTTI support and can work across dynamic library boundaries. It tries to coerce the argument to the pointer type specified in the angle brackets. If the type of the object is correct (determined at runtime), it returns a non-zero pointer, and if the type of the object is incompatible, it returns 0. 

The qobject_cast function uses the following syntax
DestType* qobject_cast<DestType*>(QObject *p);
 This function is similar to dynamic_cast in C++, but the execution speed is faster than dynamic_cast, and does not require
the support of C++ RTTI, but qobject_cast is only applicable For QObject and its derived classes.
 The main function is to convert the source type QObject to the target type DesType (or subtype) in angle brackets, and
return a pointer to the target type. If the conversion fails, it returns 0. In other words, if the source type QObject belongs to the target
type DestType (or its subtypes), a pointer to the target type is returned, otherwise 0 is returned.
 Conditions for using qobject_cast: The target type DestType must inherit (directly or indirectly) from QObject and
use the Q_OBJECT macro.


There are two restrictions in use:
1# T type must inherit from QObject.
2# There must be a Q_OBJECT macro in the declaration.

Suitable for multiple objects connected to the same slot function. Can simplify the preparation of signal slots.

 code show as below:

#include "QtLanguage.h"
#include "ui_QtLanguage.h"
#include <QTranslator>
#include <QRadioButton>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    ui->radioButton->setChecked(true);
    connect(ui->radioButton,SIGNAL(toggled(bool)),this,SLOT(changeLanguage()));
    connect(ui->radioButton_2,SIGNAL(toggled(bool)),this,SLOT(changeLanguage()));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::changeLanguage()
{
    QTranslator translator;
    QRadioButton* radio = qobject_cast<QRadioButton*>(sender());
    if(radio == ui->radioButton)
    {
        translator.load(":/en_US.qm");
        qApp->installTranslator(&translator);
        ui->retranslateUi(this);
    }
    else if(radio == ui->radioButton_2)
    {
        translator.load(":/zh_CN.qm");
        qApp->installTranslator(&translator);
        ui->retranslateUi(this);
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_41882459/article/details/113843787