2015-10-12

Qt: Dynamic Copy File in the Thread example, requires Wraparound class


  • Wraparound class


ThreadCopyFile::ThreadCopyFile(QObject *parent) : QObject(parent)
{
    qDebug() << this << "Created";

    this->v_thread = new QThread();
    this->v_copyFile = new CopyFile();
     

    connect(v_thread,SIGNAL(started()),v_copyFile,SLOT(Copy()));
    connect(v_copyFile,SIGNAL(done()),v_thread,SLOT(quit()));
    connect(v_thread,SIGNAL(finished()),this,SLOT(finished()));

    this->v_copyFile->moveToThread(this->v_thread);
    this->v_thread->start();

}

ThreadCopyFile::~ThreadCopyFile()
{
    delete this->v_thread;
    delete this->v_copyFile;
}

public slots:


void ThreadCopyFile::finished()
{
    qDebug() << this << "Finished";
    this->~ThreadCopyFile();
    qDebug() << this << "Destroyed";
}



  • Class for actual work


CopyFile::CopyFile(QObject *parent) : QObject(parent)
{
    qDebug() << this << "Created";


}

CopyFile::~CopyFile()
{
    qDebug() << this << "Destroyed";
}


signals:


    void done();

public slots:

void CopyFile::Copy(void)
{

    QString src = "/media/data/torrent/linuxmint-17.2-mate-32bit.iso";
    QString dst = "/tmp/linuxmint-17.2-mate-32bit.iso";

    if(QFile::exists(dst))
    {

        qDebug() << "file exists";

        if(QFile::remove(dst))
        {
            qDebug() << "Files removed";
        }
        else
        {
            qDebug() << "Files  fail to remove";
        }
    }

    qDebug() << "Copy File started";

    if(QFile::copy(src,dst))
    {
        qDebug() << "Copy File finished";
    }
    else
    {
        qDebug() << "Copy File fail";
    }

    emit done();
}



UI runs on other thread, everything work nicely :)


No comments:

Post a Comment