我正在开发适用于 Windows 和 Mac 的应用程序。我注意到 Mac 和 Windows 的不同行为。
当我为 QComboBox 设置 QLIstView 并尝试从组合框的 PopUp 捕获 Enter/Return 按下事件时,eventFilter 从 Windows 上的 QListView 和 Mac 上的 QComboBox 获取事件,因此,相同的代码会导致不同的输出,因为这个的。
这是代码:
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QEvent>
#include<QComboBox>
#include<QListView>
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
bool eventFilter( QObject * inObject, QEvent * inEvent );
private:
Ui::MainWindow *ui;
QComboBox * mComboBox;
QListView * mListView;
};
#endif // MAINWINDOW_H
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QStandardItemModel>
#include<QStandardItem>
#include<QList>
#include<QDebug>
#include<QKeyEvent>
#include<QHBoxLayout>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui( new Ui::MainWindow ),
mComboBox( new QComboBox() ),
mListView( new QListView( mComboBox ) )
{
ui->setupUi(this);
mComboBox->setFixedSize( 200, 25 );
mListView->setFixedWidth( 200 );
QWidget * centralWidget = new QWidget( this );
QHBoxLayout * layout = new QHBoxLayout( centralWidget );
QStandardItem * font1 = new QStandardItem( "Item1" );
QStandardItem * font2 = new QStandardItem( "Item2" );
QStandardItem * font3 = new QStandardItem( "Item3" );
QStandardItem * font4 = new QStandardItem( "Item4" );
QStandardItem * font5 = new QStandardItem( "Item5" );
QStandardItemModel * model = new QStandardItemModel( mListView);
model->insertRow( 0, font1 );
model->insertRow( 1, font2 );
model->insertRow( 2, font3 );
model->insertRow( 3, font4 );
model->insertRow( 4, font5 );
mListView->setStyleSheet( "background-color: yellow" );
mComboBox->setModel( model );
mComboBox->setView( mListView );
layout->addWidget( mComboBox );
centralWidget->setLayout( layout );
setCentralWidget( centralWidget );
mListView->installEventFilter( this );
mComboBox->installEventFilter( this );
}
bool
MainWindow::eventFilter( QObject * inObject, QEvent * inEvent )
{
if( inObject == mListView )
{
if( inEvent->type() == QEvent::KeyPress )
{
QKeyEvent * keyEvent = static_cast< QKeyEvent * >( inEvent );
if( keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return )
{
qDebug() << " From mListView";
}
}
}
else if( inObject == mComboBox )
{
if( inEvent->type() == QEvent::KeyPress )
{
QKeyEvent * keyEvent = static_cast< QKeyEvent * >( inEvent );
if( keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return )
{
qDebug() << " From mComboBox";
}
}
}
return QObject::eventFilter( inObject, inEvent );
}
MainWindow::~MainWindow()
{
delete ui;
}
有关 Mac 和 Windows 的输出,请参见下图