[Qt-interest] Navigating QListView with arrow keys

Josiah Bryan jbryan at productiveconcepts.com
Fri Oct 30 15:56:29 CET 2009


Mario Signorino wrote:
> Hi all,
> 
> which is the best way to handle the up and down keys on a QListView?
> 
> I can use the clicked() or the activated() signal, to catch mouse
> activity.. but if the user navigate my listview with the up and down
> keys (without pressing space or Enter), I can't trap nothing.
> Should I use a installEventFilter() on the list?


I've ran into the same situation no less than three times in my project. 
I just substitute in this QListView-derivitive as a drop-in replacement 
for anywhere I need a QListView:

class MediaBrowserQListView : public QListView
{
public:
	MediaBrowserQListView(QWidget * parent) : QListView(parent) {}
protected:
	void keyPressEvent(QKeyEvent *event)
	{
		QModelIndex oldIdx = currentIndex();
		QListView::keyPressEvent(event);
		QModelIndex newIdx = currentIndex();
		if(oldIdx.row() != newIdx.row())
		{
			emit clicked(newIdx);
		}
	}
};



Then just connect to the QListView::clicked(const QModelIndex&) signal, 
and you'll get a signal when the row is clicked OR entered by key press. 
If you don't want to use the clicked() signal, change the signal emitted 
above, or just make this a proper class in its own header so its 
moc-able and emit your own custom signal.

Cheers!
-josiah




More information about the Qt-interest-old mailing list