QLineEdit获取焦点后全选字符/失去焦点清除选择

一直觉得Chrome的地址栏的体验非常好,获取焦点后自动全选,无论是想复制地址还是重新输入新的地址都帮我们省掉了一步,如何用QLineEdit实现这个特点呢。

网上搜索了一下,发现一篇博客http://www.cnblogs.com/91program/p/5521420.html ,但是这篇博客讲述的方法有点复杂,最后还要通过延时来达到目的,有点怪异。

最后只得查看QLineEdit的类参考仿照Chrome实现,Chrome的地址栏在无焦点状态下鼠标按下不动的时候,地址栏获取了焦点,光标位于鼠标位置;鼠标无移动释放,全选地址栏字符;再次单击,清除全选;鼠标按下移动后释放,则不会全选,而是选择字符;地址栏失去焦点,清除选择。

看起来我们需要判断鼠标按下时的位置与鼠标释放时鼠标有没有移动,申请一个变量m_pressPos来存储鼠标按下时的位置。还需要知道鼠标单击的时候QLineEdit是否已获得焦点,我们用变量m_onFocus来记录。定义一个QLineEdit子类,然后重新实现mousePressEvent,mouseReleaseEvent,focusOutEvent。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#ifndef URLLINEEDIT_H
#define URLLINEEDIT_H

#include <QLineEdit>

class UrlLineEdit : public QLineEdit
{
Q_OBJECT
public:
UrlLineEdit(QWidget *parent = 0);
~UrlLineEdit();
protected:
void mouseReleaseEvent(QMouseEvent *e);
void mousePressEvent(QMouseEvent *e);
void focusOutEvent( QFocusEvent * e );
private:
bool m_onFocus;
QPoint m_pressPos;
};
#endif // URLLINEEDIT_H

#include "urllineedit.h"
#include <QFocusEvent>

UrlLineEdit::UrlLineEdit(QWidget *parent)
:QLineEdit(parent),
m_onFocus(false)
{

}

UrlLineEdit::~UrlLineEdit()
{

}
void UrlLineEdit::mouseReleaseEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton ){
if( e->pos() == m_pressPos && !m_onFocus){
m_onFocus = true;
selectAll();
update();
} else {
int start = cursorPositionAt(m_pressPos);
setSelection( start , cursorPositionAt(e->pos())-start );
}
}
QLineEdit::mouseReleaseEvent(e);

}

void UrlLineEdit::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton){
m_pressPos = e->pos();
setCursorPosition(cursorPositionAt(m_pressPos));
}
QLineEdit::mousePressEvent(e);
}

void UrlLineEdit::focusOutEvent(QFocusEvent *e)
{
m_onFocus = false;
if(!hasSelectedText()){
deselect();
}
QLineEdit::focusOutEvent(e);
}

通过测试基本上是实现了类似Chrome的这个特性。

QLineEdit获取焦点后全选字符/失去焦点清除选择

http://tux.red/2022/08/11/Qt/qt-qlineedit-focus/

作者

redtux

发布于

2022-08-11

更新于

2022-08-11

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.