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?
Click the Start button or press the Windows key. 'Change cursor blink rate' should be the (first) search result. Select it. Drag the 'Cursor blink rate' slider all the way to the left to None.
Control Panel => Keyboard, and under 'Cursor blink rate' : move the slider all the way to the left. Would you try this please : Control Panel => Keyboard, and under 'Cursor blink rate' : move the slider all the way to the left.
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);
}
As a workaround you can create a single line QTextEdit
and set the width of the cursor to zero by setCursorWidth
.
For a single line QTextEdit
you should subclass QTextEdit
and do the following:
setTabChangesFocus(true)
.QSizePolicy::Expanding
, QSizePolicy::Fixed
)keyPressEvent()
to ignore the event when Enter/Return is hitsizeHint
to return size depending on the font.The implementation is :
#include <QTextEdit>
#include <QKeyEvent>
#include <QStyleOption>
#include <QApplication>
class TextEdit : public QTextEdit
{
public:
TextEdit()
{
setTabChangesFocus(true);
setWordWrapMode(QTextOption::NoWrap);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setFixedHeight(sizeHint().height());
}
void keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
event->ignore();
else
QTextEdit::keyPressEvent(event);
}
QSize sizeHint() const
{
QFontMetrics fm(font());
int h = qMax(fm.height(), 14) + 4;
int w = fm.width(QLatin1Char('x')) * 17 + 4;
QStyleOptionFrameV2 opt;
opt.initFrom(this);
return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
expandedTo(QApplication::globalStrut()), this));
}
};
Now you can create an instance of TextEdit
and set the cursor width to zero :
textEdit->setCursorWidth(0);
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