Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QT5.12 Qwidget cannot get focus



  • 在按键机上使用qt测试按键,窗口无法获取焦点,按键不生效,是不是我的代码写的不对?

    Widget::Widget(QWidget *parent)
        : QWidget(parent)
    {
        setFocusPolicy(Qt::StrongFocus);
        setFixedSize(800, 800);
        qDebug()<<"begin test"<<endl;
        btn = new QPushButton(tr("open"),this);
        if (hasFocus()) {
            qDebug() << "has focus" << endl;
        } else {
            qDebug() << "NO focus" << endl;
        }
    }
    
    Widget::~Widget()
    {
    }
    
    void Widget::keyPressEvent(QKeyEvent *event) {
        qDebug()<<"try"<<endl;
        if(event->key() == Qt::Key_1) {
            qDebug()<<"press 1"<<endl;
            btn->move(50, 50);
            
            if (hasFocus()) {
                qDebug() << "has focus" << endl;
            } else {
                qDebug() << "NO focus" << endl;
            }
        }
    }
    

Log in to reply