在qt中回车切换焦点的问题?

bad_alloc 2008-06-30 12:11:46
一个QWidget是主窗口,上面有一些QLineEdit QComboBox等等,用Tab切换太麻烦了,想换成回车切换焦点,代码如下:

///@brief 回车切换焦点
void MyWidget::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Enter) {
QKeyEvent* convertEvent =
new QKeyEvent(QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
keyPressEvent(convertEvent);
return;
}
QWidget::keyPressEvent(event);
}

这样写为什么不行啊,跟踪下来发现event->key()是空的,有知道的或者给个正确的办法也行,最好也帮我解释下为什么event->key()是空的?
是不是因为这个event是在QLineEdit或者QComboBox上产生的,没有传递到QWidget上去?
...全文
1489 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
一个QWidget是主窗口,上面有一些QLineEdit QComboBox等等,用Tab切换太麻烦了,想换成回车切换焦点,代码如下:


很久以前我也有类似想法,只是当时我不知道tab这么方便。
其实你应该好好研究下QT的事件过滤器,搞清event传递的先后顺序,你说的功能可以实现,但是很久没QT了,我具体不记得了。
反正你去研究下事件过滤器应该就会少些困惑了。
goodname 2009-07-23
  • 打赏
  • 举报
回复
这个问题我觉得可以参考如下函数.

bool QObject::eventFilter ( QObject * watched, QEvent * event ) [virtual]
Filters events if this object has been installed as an event filter for the watched object.
In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.
Example:
class MainWindow : public QMainWindow
{
public:
MainWindow();

protected:
bool eventFilter(QObject *obj, QEvent *ev);

private:
QTextEdit *textEdit;
};

MainWindow::MainWindow()
{
textEdit = new QTextEdit;
setCentralWidget(textEdit);

textEdit->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == textEdit) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}
Notice in the example above that unhandled events are passed to the base class's eventFilter() function, since the base class might have reimplemented eventFilter() for its own internal purposes.
Warning: If you delete the receiver object in this function, be sure to return true. Otherwise, Qt will forward the event to the deleted object and the program might crash.
See also installEventFilter().

bxfq 2009-07-23
  • 打赏
  • 举报
回复
如果环境是qt3,直接使用
bool QWidget::focusNextPrevChild ( bool next ) [virtual protected]
设置成TRUE,事先调整好焦点的顺序就好了
bad_alloc 2008-07-01
  • 打赏
  • 举报
回复
现在郁闷的是,就算我敲了回车,event->key()也是空的啊,根本进不了 if 语句
hai040 2008-06-30
  • 打赏
  • 举报
回复
key_enter换成key_return
bitxinhai 2008-06-30
  • 打赏
  • 举报
回复
思想:
获取回车键事件,
处理事件让焦点移动到下一个控件上!!!
babyvox1999 2008-06-30
  • 打赏
  • 举报
回复

if (event->key() == Qt::Key_Enter)
{
focusNextChild();
}
bad_alloc 2008-06-30
  • 打赏
  • 举报
回复
弟兄们,帮个忙啊

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧