어떻게 QLineEdit 위젯 프로그래밍 방식으로 텍스트를 설정하여 Esc 키에 응답 할 수 있습니까? 이벤트 필터 설치처럼 QLineEdit
의 자녀 또는 좀 더 "로컬"로 QWidget::event
가상 함수를 오버라이드
어느 :
class MyLineEditEventFilter : public QObject
{
public:
explicit MyLineEditEventFilter(QLineEdit *parent) : QObject(parent)
{}
bool eventFilter(QObject *obj, QEvent *e)
{
switch (e->type())
{
case QEvent::KeyPress:
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
if (keyEvent->key() == Qt::Key_Escape)
{
// or set the other text from the variable
reinterpret_cast<QLineEdit *>(parent())->setText("Escape!");
}
break;
}
}
// standard event processing
return QObject::eventFilter(obj, e);
}
};
호출자는 같다 :
m_pLineEditSearch = new QLineEdit;
auto* pLineEditEvtFilter = new MyLineEditEventFilter(m_pLineEditSearch);
m_pLineEditSearch->installEventFilter(pLineEditEvtFilter);
Escape 키를 눌러 이전 텍스트를 다시 가져 오려면 다른 방법을 사용할 수 있지만 어떻게 든 문자열을 유지하는 객체에 대한 포인터를 가져와야합니다. 코드를 보지 않고도 대답하기가 어렵습니다.
이것은 분명합니다. QLineEdit을 서브 클래 싱하여 이벤트 동작을 재정의하는 것이 좋습니다. 나는 그것이 이미 존재하기 때문에 그 행동을 재현하는이 물체에 대한 신호 또는 방법을 얻을 수 있기를 바랬다. 감사! –