Skip to content

Instantly share code, notes, and snippets.

@xyz1001
Last active October 29, 2018 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xyz1001/ee3ca7750b14e02a155a71055a6da327 to your computer and use it in GitHub Desktop.
Save xyz1001/ee3ca7750b14e02a155a71055a6da327 to your computer and use it in GitHub Desktop.
自定义光标颜色的QLineEdit
/*
* -*- coding: uft-8 -*-
*/
#include "input_box.h"
#include <QPainter>
InputBox::InputBox(QWidget *parent) : QLineEdit(parent) {
setReadOnly(true);
blink_timer_.setInterval(500);
connect(&blink_timer_, &QTimer::timeout, this, &InputBox::Blink);
connect(this, &InputBox::textChanged, [this] { blink_timer_.start(); });
connect(this, &InputBox::cursorPositionChanged, this,
&InputBox::DrawCursor);
}
void InputBox::paintEvent(QPaintEvent *event) {
QLineEdit::paintEvent(event);
if (cursor_visibility_) {
QPainter painter(this);
QRect rect = cursorRect();
painter.fillRect(
QRect(rect.x() + rect.width() / 2, rect.y(), 2, rect.height()),
Qt::red);
}
}
void InputBox::showEvent(QShowEvent *event) {
QLineEdit::showEvent(event);
blink_timer_.start();
}
void InputBox::hideEvent(QHideEvent *event) {
QLineEdit::hideEvent(event);
blink_timer_.stop();
}
// 移除默认光标
void InputBox::keyPressEvent(QKeyEvent *event) {
setReadOnly(false);
QLineEdit::keyPressEvent(event);
setReadOnly(true);
}
void InputBox::Blink() {
cursor_visibility_ = !cursor_visibility_;
update();
}
void InputBox::DrawCursor() {
cursor_visibility_ = true;
update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment