PDA

View Full Version : keyPressEvent() not working for a tab within QTabWidget



sadastronaut
7th August 2014, 17:56
I have a tab within a QTabWidget. I have a keyPressEvent() override defined in my class managing the tab but the key press events are not recognized (I have a cout call to verify that the function isn't even called).

I have tried activeWindow(), setFocusPolicy(QtFocusPolicy::StrongFocus), and setFocus() both on the tab and the widget itself, but that doesn't seem to help.

When I implement a keyPressEvent() on the main window widget containing the tab widget, it seems to work, but I'd rather do it on the individual tabs if possible.

Code for main window

QtPlotsMain::QtPlotsMain()
: ui( new Ui::QtPlotsMain() ),
help_ui( new Ui::Help()),
help_dialog(new QDialog())
{
//Setup plot
ui->setupUi( this );
tabWidget = new QTabWidget(ui->centralwidget);
tabWidget->setObjectName(QString::fromUtf8("tabWidget"));
tabWidget->setIconSize(QSize(16, 16));
tabWidget->setTabsClosable(true);
tabWidget->setMovable(true);
QWidget * tab_2 = new QWidget();

tabWidget->addTab(tab_2, "Altitude vs Time");

ui->gridLayout->addWidget(tabWidget, 0, 0, 1, 1);

shared_ptr<QtPlotsTab> alt_tab(make_shared<AltVsTimeTab>(tab_2));
plot_objects.push_back(alt_tab);

Code for tab:

QtPlotsTab::QtPlotsTab(QWidget *tab_in,
const QString & title_in,
const QString & x_label_in,
const QString & y_label_in)
: map_src_curve(make_shared<SensorPlotCollection>())
{
QGridLayout *gridLayout_2 = new QGridLayout(tab_in);
//Setup plot
plot = new QwtPlot(tab_in);
gridLayout_2->addWidget(plot, 0, 0, 1, 1);

// have tried a variety of things here
activateWindow();
setFocusPolicy(Qt::FocusPolicy::StrongFocus);
setFocus();

}



void QtPlotsTab::keyPressEvent(QKeyEvent *e)
{
cout << FILE_LINE << endl;
}

d_stranz
8th August 2014, 20:13
Your QwtPlot is probably eating the key events. Try implementing an event filter method in your QtPlotTab class (see QObject::eventFilter()) and installing it on the QwtPlot instance (QObject::installEventFilter()), and look for the key events there.

If you do that, be sure to pass the other events along if you aren't handling them. See the installEventFilter() docs for an example of how to do it correctly.

I also notice that you aren't initializing the base class of QtPlotsTab in the constructor. This could be part of your problem if the event loop isn't being set up properly for your class instance.