0
votes

I have a button with function onClicked. There is a C++ class Middle with function search_connection connected via qmlRegisterType.

What I want to do is to change the text of searchButton while the C++ function is calculating the return value and also disable the button for that time.

What happens is nothing. The button is enabled for the whole time with text "Search". I believe that what actually happens is, that search_connection function is executed first and than all the rest happens so fast I can't notice the change from "Search" to "Searching..." and back again.

TextField {
   id: startStop
}

TextField {
   id: finishStop
}

Button {
   id: searchButton
   text: qsTr("Search")

   onClicked: {
      text = qsTr("Searching...")
      enabled = false;
      searchResult.text = middle.search_connection(startStop.text,finishStop.text)
      enabled = true;
      text = qsTr("Search")
   }
}

Does anyone know how to make the Qt to call the function after it changes the text to "Searching..."?

1
Looks like you execute your task in the GUI thread an so block it until end of execution. You should move the task to a different thread. - folibis

1 Answers

1
votes

Your UI will repaint certain areas with the next call of the event loop. This never happen in your case, because the slot (your function) is called directly and blocks the application until it is finished. There are a few ways to avoid that blocking:

  • Move your task to another thread (QThread) and wait until finish
  • Start your task with an timer (QML-Timer). You can redraw the button before starting the method, but your GUI will still block until the method has finished (the change of enabled will be useless).
  • Call processEvents() within your method multiple times (not recommended, can cause problems).

If the method needs some time, I would use a new thread. So your gui isn't blocking and your button wil still receive events (painting, mouse, ...).

Edit 1:

If your C++-Code is simple and can be translated to JavaScript-Code, you can also use WorkerScript. It's the QML-Version of QThread. But it has some limitations. You can only use JavaScript and you can't interact with the Worker while running.

Thanks to folibis for the suggestion.