QVariant is not able to distinguish between QDateTime and QString

2.2k Views Asked by At

I have a QDateTime object which I store in a QVariant and then I check the QVariant with type() but it behaves strangely when I check the type.

void MainWindow::Test()
{

    QDateTime myDate; // QDateTime;
    myDate.setDate(QDate::currentDate());

    QVariant myVariant(myDate);
    qDebug() << myVariant.canConvert(QMetaType::QDateTime); // return true 

    // here is the problem
    qDebug() << myVariant.canConvert(QMetaType::QString); // return true as well
}
1

There are 1 best solutions below

0
On

canConvert means only that conversion is possible, not that variant contains specific type. To verify type use this approach:

qDebug() << (myVariant.type()==QVariant::DateTime);
qDebug() << (myVariant.type()==QVariant::String);