Hide QLineEdit blinking cursor

Asheesh picture Asheesh · Aug 7, 2014 · Viewed 7.6k times · Source

I am working on QT v5.2

I need to hide the blinking cursor (caret) of QLineEdit permanently. But at the same time, I want the QLineEdit to be editable (so readOnly and/or setting editable false is not an option for me).

I am already changing the Background color of the QLineEdit when it is in focus, so I will know which QLineEdit widget is getting edited. For my requirement, cursor (the blinking text cursor) display should not be there.

I have tried styleSheets, but I can't get the cursor hidden ( {color:transparent; text-shadow:0px 0px 0px black;} )

Can someone please let me know how can I achieve this?

Answer

Ezee picture Ezee · Aug 7, 2014

There is no standard way to do that, but you can use setReadOnly method which hides the cursor. When you call this method it disables processing of keys so you'll need to force it. Inherit from QLineEdit and reimplement keyPressEvent.

LineEdit::LineEdit(QWidget* parent)
 : QLineEdit(parent)
{
  setReadOnly(true);      
}

void LineEdit::keyPressEvent(QKeyEvent* e)
{
  setReadOnly(false);
  __super::keyPressEvent(e);
  setReadOnly(true);
}