首页 文章

如何在不同的qt QMainWindow上传播keyPressEvent

提问于
浏览
1

我有2个不同的QMainWindow,第一个是第二个的父 . 我想按下子窗口中的一些键并在父窗口中传播事件 . 我为每个人创建了函数void keyPressEvent(QKeyEvent * event);但是当我按下孩子的钥匙时,事件不会传播给父母 . 为什么?

这是代码......

//父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

//父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();
}

//儿童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

//儿童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 回答

  • 1

    QMainWindow 是顶级窗口,通常是事件传播结束的位置 . 我'm not entirely clear what may be the rule though when a top-level window is parented. By your results, I' ll必须假设它代表 .

    在任何情况下,您都应该能够通过在 MainWindow 类中定义过滤器方法并在 test 类上安装它来获取事件 . 请参阅this documentation .

    您还可以选择覆盖 QApplicationevent() 方法 .

相关问题