效果
代码
头文件:
class CustomLineEditProxyStyle;
class QtLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit QtLineEdit(QWidget *parent = nullptr);
~QtLineEdit();
private slots:
void sltUpdateCursorRect();
void sltTextEdit(const QString &text);
private:
CustomLineEditProxyStyle *m_proxyStyle;
QTimer *m_timer;
protected:
bool m_bShowCursor;
void paintEvent(QPaintEvent *e) override;
};
CPP文件:
class CustomLineEditProxyStyle : public QProxyStyle
{
public:
virtual int pixelMetric(PixelMetric metric, const QStyleOption* option = 0, const QWidget* widget = 0) const
{
if (metric == QStyle::PM_TextCursorWidth)
{
return 0;
}
return QProxyStyle::pixelMetric(metric, option, widget);
}
};
QtLineEdit::QtLineEdit(QWidget *parent) : QLineEdit(parent)
{
m_proxyStyle = new CustomLineEditProxyStyle();
this->setStyle(m_proxyStyle);
m_bShowCursor = false;
m_timer = new QTimer(this);
m_timer->setInterval(QGuiApplication::styleHints()->cursorFlashTime() / 2);
connect(m_timer, SIGNAL(timeout()), this, SLOT(sltUpdateCursorRect()));
m_timer->start();
connect(this, SIGNAL(textEdited(QString)), this, SLOT(sltTextEdit(QString)));
}
QtLineEdit::~QtLineEdit()
{
delete m_proxyStyle;
m_proxyStyle = Q_NULLPTR;
}
void QtLineEdit::sltUpdateCursorRect()
{
m_bShowCursor = !m_bShowCursor;
QRect rect = cursorRect();
rect.setX(rect.x() + 2);
rect.setWidth(rect.width() + 5);
this->update(rect);
}
void QtLineEdit::sltTextEdit(const QString &)
{
m_bShowCursor = true;
}
void QtLineEdit::paintEvent(QPaintEvent *e)
{
QLineEdit::paintEvent(e);
if (this->hasFocus() && m_bShowCursor)
{
QPainter painter(this);
QRect rect = this->cursorRect();
rect.setX(rect.x() + 2);
rect.setWidth(rect.width() + 5);
painter.fillRect(QRect(rect.center().x(), rect.y(), 5, rect.height()), QColor(0, 0, 255));
}
}