[macOS] How to hide the mouse cursor while typing in a text box?
-
On macOS, the mouse is hidden when you start typing into a text box. The mouse is shown again after you move it. This is to stop the mouse from covering the text you're trying to type. I'm trying to reproduce this in my Qt app but I'm having a bit of trouble. Here's a gif that demonstrates the desired behaviour using a native mac app (iTerm2).
First off, I don't know how to globally hide the mouse cursor.
QApplication::setOverrideCursor(Qt::BlankCursor);
isn't quite enough. It will hide the cursor when it's within the window but not when it's outside the window.Secondly, I don't know if it's possible to get mouse events when the mouse is outside the window. It seems like I'll probably have to write some Objective-C to get this work. Who knows, maybe there's a
hideTheMouseUntilItMoves
function buried in Cocoa somewhere!I'm wondering if anyone that's familiar with native mac development knows of an easy way to accomplish this. Should I just settle for
setCursor
? -
This has just blown my mind!
There isn't a function called
hideTheMouseUntilItMoves
but there issetHiddenUntilMouseMoves
that does exactly what I want it to do!All I had to do was write this Objective-C++ code:
#import <AppKit/NSCursor.h> void hideMouseUntilMouseMoves() { [NSCursor setHiddenUntilMouseMoves:true]; }
Then I just call that function when a key is pressed.
#include <QtWidgets/qlineedit.h> #include <QtWidgets/qmainwindow.h> #include <QtWidgets/qapplication.h> void hideMouseUntilMouseMoves(); class LineEdit final : public QLineEdit { public: explicit LineEdit(QWidget *parent) : QLineEdit{parent} {} private: void keyPressEvent(QKeyEvent *event) override { QLineEdit::keyPressEvent(event); hideMouseUntilMouseMoves(); } }; int main(int argc, char **argv) { QApplication app{argc, argv}; QMainWindow window; LineEdit box{&window}; window.show(); return app.exec(); }
I definitely feel that this should be a feature of Qt. I might post a feature request to the bug tracker.
-
I made a post on the bug reporter.
-
Hi,
Nice one ! Thanks for sharing !