为了实现 QLineEdit 获取焦点/获取焦点后全选字符的功能,在网上先查了 QLineEdit 获取焦点的方法,有两种:
1 此方法只有在窗体从失去焦点到获取焦点时有作用:即窗体失去焦点后再次获取焦点时,将焦点置于某个 QLineEdit 中。
此功能明显不是偶想要的!!! 但由于网上现有的文章都是一样的,说的不是很清楚,所以只有试了才知道。
有三段代码:
1) 在窗体初始化时增加如下代码:
1 // QLineEdit 获取焦点 1 - 此方法错误: 只有在窗体从失去焦点到获取焦点时有作用 2 ui->ledSendStr->installEventFilter(this); 3 ui->ledSendFile->installEventFilter(this); 4 ui->ledSendPreTime->installEventFilter(this);
2) 在窗体的 .h 文件中声明 SLOT,如下:
1 public slots: 2 bool eventFilter(QObject *,QEvent *); // QLineEdit 获取焦点 2
3) 实现的代码
1 // QLineEdit 获取焦点 3 2 bool MainWindow::eventFilter(QObject *watched, QEvent *event) 3 { 4 if(watched == ledSendStr) 5 { 6 if(QEvent::FocusIn == event->type()) 7 { 8 qDebug() << "focus in"; 9 ledSendStr->selectAll(); // 不起使用,只有在窗体获取到焦点时才有功能 10 ledSendStr->setFocus(Qt::OtherFocusReason); 11 } 12 else if(QEvent::FocusOut == event->type()) 13 { 14 qDebug() << "focus out"; 15 } 16