How to destroy QProcess when it finishes and the class than contaed the slot

£可爱£侵袭症+ 提交于 2019-12-11 19:39:33

问题


I start a QProcess in member function of a class but that object (Pdf object below) will soon get destroyed after creating the process. I obviously want the slot function to be available and called when QProcess finishes. I pass QProcess pointer so when it finishes, it will destroy it as well. But actually it doesn't really is destroyed when it finishes.

void PDf::createPDF()
{
PdfSymlink * pdfSymlink = new PdfSymlink( fileName, linkName, myProcess );

connect(myProcess, SIGNAL(finished(int)), pdfSymlink, SLOT(createPdfLink(int)) );

myProcess->start("sh",args); // args is defined now shown in code
} 

This is a repetitive code which is called many many timesI want the QProcess to get destroyed when it finishes and likewise pdfSymlink should be destroyed as well. How can I do that?

Note my slot does get called and it does the job but I want to make sure I clean up after this object.


回答1:


Well, you seem to keep track of the process object. You could implement createPdfLink(int) like this:

void createPdfLink(int status)
{
    if(status != 0)
    {
       // Do error handling
    }
    else
    {
       // regular code
    }

    myProcess->deleteLater();
    deleteLater();
}

assuming myProcess is stored as myProcess inside the PdfSymlink object as well. It causes the process to be deleted by Qt as soon as it is allowed to be deleted by Qt (mainly to prevent random crashes) and causes the class itself to delete when allowed.

Extra:

As a more clean code, it might be better to include the connect function inside the constructor of the PdfSymlink class:

PdfSymlink::PdfSymlink(QString fileName, QString linkName, QProcess * myProcess)
{
    this->myProcess = myProcess;
    connect(myProcess, SIGNAL(finished(int)), SLOT(createPdfLink(int)));

    // More initialization code
}

This has the added benefit of keeping code relevant, and makes the "receiver" argument optional as the overloaded non-static member-function connect(sender,signal,method) is used.




回答2:


So if anyone runs into the same issue I fix it, I had to call deleteLater as a slot:

void PDf::createPDF()
{
        QProcess *myProcess= new QProcess();

        PdfSymlink * pdfSymlink = new PdfSymlink( fileName, linkName, myProcess ); // fileName and LinkName definition is omitted 

        connect(myProcess, SIGNAL(finished(int)), pdfSymlink, SLOT(createPdfLink(int))

        // Call deleteLater
        connect(myProcess, SIGNAL(finished(int)), myProcess, SLOT(deleteLater()) );

        myProcess->start("sh",args); // args is defined now shown in code
} 


来源:https://stackoverflow.com/questions/33530592/how-to-destroy-qprocess-when-it-finishes-and-the-class-than-contaed-the-slot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!