views:

84

answers:

1

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();

}
A: 

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.

Arnold Spence
Ok, thank you!!