需求:点击编辑框,默认全选文本
代码里直接使用QSpinBox::selectAll()方法发现无效;
解决方案:
封装一层QSpinBox
定义头文件 增加过滤事件
#include<QSpinBox>
class STOCKUTIL_EXPORT StockSpinBox : public QSpinBox
{
Q_OBJECT
public:
explicit StockSpinBox(QWidget *parent = nullptr);
~StockSpinBox();
protected:
bool eventFilter(QObject *watched, QEvent *event);
};
.cpp文件
#include "stockSpinBox.h"
StockSpinBox::StockSpinBox(QWidget *parent):QSpinBox(parent)
{
this->installEventFilter(this);
this->lineEdit()->installEventFilter(this);
}
StockSpinBox::~StockSpinBox()
{
}
bool StockSpinBox::eventFilter(QObject *watched, QEvent *event)
{
if (watched == this)
{
if (event->type() == QEvent::FocusIn)
{
QTimer::singleShot(0, [=]() mutable {
this->lineEdit()->selectAll();
});
}
}
return QSpinBox::eventFilter(watched, event);
}
调用封装后控件即可解决需求