Search code examples
c++qtqtwebkit

QtWebPage - loadFinished() called multiple times


In my application, I have list view. Selecting another item in it, triggers an event:

connect(listView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(item_changed(const QModelIndex &, const QModelIndex &)));

void MainWindow::item_changed(const QModelIndex & current, const QModelIndex & previous)
{
    qDebug() << "\n" << "item_changed(), caller: " << sender()->objectName();
    if (current.isValid())
    {
        /*
          not so important code
        */

        change_query(tokens.join("+"));
    }
}

This calls another slot - change_query().

void MainWindow::change_query(QString newquery)
{
    qDebug() << "change_query(), caller: " << sender()->objectName();

    QUrl query (newquery);

    frame->load(query);

    connect(frame, SIGNAL(loadFinished(bool)), this, SLOT(loading_finished()));
}

And finally, when page is fully loaded, it should call loading_finished()

void MainWindow::loading_finished()
{
    qDebug() << "loading_finished(), caller: " << sender()->objectName();
}

But, to my surprise, the output is:

item_changed(), caller:  "SelectionModel" 
change_query(), caller:  "SelectionModel"
loading_finished(), caller:  "frame" 

item_changed(), caller:  "SelectionModel" 
change_query(), caller:  "SelectionModel" 
loading_finished(), caller:  "frame" 
loading_finished(), caller:  "frame" 

item_changed(), caller:  "SelectionModel" 
change_query(), caller:  "SelectionModel" 
loading_finished(), caller:  "frame" 
loading_finished(), caller:  "frame" 
loading_finished(), caller:  "frame" 

item_changed(), caller:  "SelectionModel" 
change_query(), caller:  "SelectionModel" 
loading_finished(), caller:  "frame" 
loading_finished(), caller:  "frame" 
loading_finished(), caller:  "frame" 
loading_finished(), caller:  "frame" 

As you can see, each time i change selection, another instance (?) of WebFrame is created and loaded, or page is loaded +1 time each loop. I spent last 2 hours finding out where the problem is and I don't see anything.


Solution

  • You should connect signals to slots only once, possible in constructor.

    Oppositely, you call

    connect(frame, SIGNAL(loadFinished(bool)), this, SLOT(loading_finished()));
    

    evety time you change item. So, your slots gets called so many times, as you called connect.