Last active
October 29, 2018 03:24
-
-
Save xyz1001/ee3ca7750b14e02a155a71055a6da327 to your computer and use it in GitHub Desktop.
自定义光标颜色的QLineEdit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* -*- 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