In my Qt application I am saving some data when application is being closed. Saving data is performed in the closeEvent(QCloseEvent*) method. I wanted to change the cursor before the saving data and restore it back after saving.
From what I have read over the Internet the setCursor( const QCursor& ) doesn't work globally, but only in the scope of some specified widget. Therefore I tried to use SetCursor( HCURSOR ) from WinAPI.
The code looks like this:
void mainWin::closeEvent( QCloseEvent* e ) {
SetCursor( LoadCursor( GetModuleHandle( NULL ), ( LPCWSTR )IDC_WAIT ) );
saveData();
SetCursor( LoadCursor( GetModuleHandle( NULL ), ( LPCWSTR )IDC_ARROW ) );
e->accept();
}
However, the first SetCursor() method just hides the cursor for the time when the data is saving instead of changing it to some kind of hourglass. Why?
You should use QApplication::setOverrideCursor, it will change your cursor for your entire application.
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
saveData();
QApplication::restoreOverrideCursor();
You can of course provide your own pixmap when you create your cursor.
One other interesting thing that you can do is creating a RAII class to handle a custom cursor. You call setOverrideCursor in the constructor and the restoreOverrideCursor in the destructor. Doing so is quite handy when you have many places where you want to change the cursor and automatically restore it at the end of the scope. One other advantage is that if your saveData method throws, your cursor is reset anyway, which is quite nice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With