1

我有一个QAbstractItemViewQListView设置selectionMode为的实例Qt::NoSelection。当我激活小部件时,我可以看到当前索引突出显示。但是,当我关注另一个小部件时,当前索引QListView不再突出显示。无论哪个小部件具有焦点,我都需要始终突出显示当前索引。

4

1 回答 1

1

您可以使用此事件过滤器执行此操作:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{

    if (obj == ui->listView && event->type() == QEvent::FocusOut)
    {
        //when view loses focus we highlight current item
        ui->listView->selectionModel()->select( ui->listView->currentIndex(), QItemSelectionModel::Select );
    }
    if (obj == ui->listView && event->type() == QEvent::FocusIn)
    {
        //when view gets focus we clear selection
        ui->listView->selectionModel()->clear();
        ui->listView->selectionModel()->select( ui->listView->currentIndex(), QItemSelectionModel::Select );
    }
    return QObject::eventFilter(obj, event);
}

要使用eventFilter,您还应该:

protected:
    bool eventFilter(QObject *obj, QEvent *event);//in header

qApp->installEventFilter(this);//in constructor

如果您不想使用事件过滤器,您可以子类化视图并重新实现focusInEvent ( QFocusEvent * event )focusOutEvent ( QFocusEvent * event )做同样的事情。

于 2014-11-10T19:03:53.683 回答