Question

I've come across a anomaly in Qt (v4.8.4) when re-assigning a new path to a pre-existing QDir object. Here is a reduced example demonstrating this:

    QString path1("F:/");   //Path must exist...
    QString path2("F:/Some/Valid/Path/For/You/");   //Path must exist...

    //Set default...
    QFileInfo fi1(path1);
    QDir d(fi1.absoluteDir());

    //CASE 1...
    if(!d.setCurrent(path2)) {
        qDebug() << QString("Cannot set path (%1)").arg(path2).toAscii().data();
        return -1;
    }

    qDebug() << "CASE 1:";
    qDebug() << QString("path2: %1").arg(path2).toAscii().data();
    qDebug() << QString("d    : %1").arg(d.absolutePath()).toAscii().data();
    //END of CASE 1...


    //CASE 2...
    QFileInfo fi2(path2);
    d = fi2.absoluteDir();

    qDebug() << "CASE 2:";
    qDebug() << QString("path2: %1").arg(path2).toAscii().data();
    qDebug() << QString("d    : %1").arg(d.absolutePath()).toAscii().data();
    //END of CASE 2...

Even though the call to d.setCurrent(path2) returns true, the new path is not set in the QDir object. OTOH, assigning the new path 1st to a QFileInfo object, and then calling absoluteDir() on that object returns an updated QDir object.

You can then directly assign the returned object to a pre-existing QDir object (through the overridden assignment operator), and the path in the QDir object will be correctly updated.

Why does the CASE 1 not work?

Was it helpful?

Solution

QDir::setCurrent is a static function that sets the current path of the application. It doesn't modifiy any QDir instance.

You should use QDir::setPath to assign a new path (or assign the QString directly to QDir with the = operator, since the conversion is implicit).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top