How to propagate keyPressEvent on different qt QMainWindow

ⅰ亾dé卋堺 提交于 2019-12-24 07:59:38

问题


I have 2 different QMainWindow, the first is the parent of the second. I want press some keys in the children windows and propagate the event in the parent. I create for everyone the function void keyPressEvent(QKeyEvent* event); but when i press key on the children the event is not propagate to the parent. Why?

This is the code...

//Parent class.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QKeyEvent>
#include "test.h"
#include <QDebug>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
protected:
    void keyPressEvent(QKeyEvent* event);
private:
    Ui::MainWindow *ui;
    test *form;

private slots:
    void on_pushButton_clicked();
};

#endif // MAINWINDOW_H

//Parent class.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    form = new test(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::keyPressEvent(QKeyEvent* event)
{
    qDebug() << event->text();
}

void MainWindow::on_pushButton_clicked()
{
    form->show();
}

//Children class.h

#ifndef TEST_H
#define TEST_H

#include <QMainWindow>
#include <QKeyEvent>
namespace Ui {
    class test;
}

class test : public QMainWindow
{
    Q_OBJECT

public:
    explicit test(QWidget *parent = 0);
    ~test();
protected:
    void keyPressEvent(QKeyEvent* event);
private:
    Ui::test *ui;
};

#endif // TEST_H

//Children class.cpp

#include "test.h"
#include "ui_test.h"

test::test(QWidget *parent) :  QMainWindow(parent),  ui(new Ui::test)
{
    ui->setupUi(this);
}

test::~test()
{
    delete ui;
}

void test::keyPressEvent(QKeyEvent* event)
{
  qDebug() << event->text();
  event->ignore();

}

回答1:


A QMainWindow is a top-level window and that is usually where event propagation ends. I'm not entirely clear what may be the rule though when a top-level window is parented. By your results, I'll have to assume that it stands.

In any case, you should be able to get the event by defining a filter method in your MainWindow class and installing it on test class. Refer to this documentation.

You also have the option of overriding the event() method of QApplication.



来源:https://stackoverflow.com/questions/3914809/how-to-propagate-keypressevent-on-different-qt-qmainwindow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!