Important: Please read the Qt Code of Conduct -

Correct way of manually deleting QNetworkAccessManager

  • I have a Mainwindow that uses the QNetworkAccessManager in the constructor to check if a new version is available. The Mainwindow will stay open for many hours and because of that I would like to delete the QNetworkAccessManager after it finished its task.

    This is my implementation:

    MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow){
    	manager = new QNetworkAccessManager();
    	connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileIsReady(QNetworkReply*)) );
    	QNetworkRequest request;
    	request.setRawHeader( "User-Agent" , "Mozilla Firefox" );
    void MainWindow::fileIsReady(QNetworkReply *reply){
    	QByteArray data = reply->readAll();
    	// and check data...		
    	delete manager;

    This seems to work fine. However, as soon as I start using a new QNetworkAccessManager in another Dialog I get all sorts of wierd program crashes. If I don't delete the QNetworkAccessManager manually but instead use manager = new QNetworkAccessManager(this) I don't get any crashes. Doing it that way would mean that the QNetworkAccessManager won't be deleted until the program closes which is not what I want.
    How can I manually delete the QNetworkAccessManager?

  • Two questions:

    1. Have you tried to use ?
    manager = nullptr;
    1. Why do you need more managers?

  • @mcosta
    Thank you for your answer. It seems that your suggestion is working without any crashes. Am I correct with my assumption that you shouldn't use delete with Qt pointers? Will your suggestion actually free up any memory?

    About your question on why I need more managers. The user has the option to open a new Dialog and submit files. This new Dialog has its own manager.

  • QObject::deleteLater() schedules the object to be deleted when there are no events related to it. So using it means "delete this object when is not used anymore".

    assigning to nullptr is to avoid to have dangling pointer so you can test

    if (manager) {
      // still used

Log in to reply