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

来源:互联网 发布:informix查看数据库 编辑:程序博客网 时间:2024/06/06 04:46

代码如下:

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可能还没操作完局部变量就失效了,导致失败。

原创粉丝点击