QT获取控件焦点,判断对象类型,模拟发送按键消息

代码如下:

void MainWindow::keyPressEvent(QKeyEvent *event){
    if(event->type()==QKeyEvent::KeyPress)
    {
        if(event->key()==Qt::Key_Return)
        {
            QWidget *current_focus_w = this->focusWidget();//获取当前焦点的控件
            if(!current_focus_w)
                return;
            QPushButton * btn = qobject_cast<QPushButton*>(current_focus_w);
            if(btn)
                btn->click();
        }
    }
}

判断对象类型

T qobject_cast(QObject *object)
Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns 0. If object is 0 then it will also return 0.
The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.
A class is considered to inherit itself.

如果给定的object是T类型或者T的子类,那么该方法把object转换成T类型,否则返回0,空对象也返回0.
必要条件:要求T类型必须是继承自QObject 的对象

下面这个也可以用于判断

bool QObject::inherits(const char *className) const
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
A class is considered to inherit itself.

如果需要转换成T类,就用上面那个方法,如果只是判断用下面这个就可以。

pushButton要想接收默认键盘消息如Key_Return之类的,要勾选上其pushButton的default,autodefault属性

模拟键盘发送消息

   QKeyEvent *key_event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier,QString(QChar(key)));
    QCoreApplication::postEvent(QApplication::focusObject(), key_event);

注意:

  • 如果不设置QApplication::focusObject(),就会不正常。像一些方向键就不对了。

  • 当需要在QEditline之类的输入框中模拟输入字符时,QKeyEvent还要加上const QString &text参数再发送,

  • 使用postEvent时必须是QKeyEvent *类型变量,如果是sendEvent则可以QKeyEvent类型变量。因为如果用的是局部变量,postEvent可能还没操作完局部变量就失效了,导致失败。

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值