PDA

View Full Version : QListWidget + Delete Key



bpetty
16th August 2006, 16:21
I was wondering what the best way to delete a QListWidget item when you press the delete key.

Should I write my own class that inherits QListWidget and overwrite the keyPressEvent() method to capture the delete key? There must be a better design.

Thanks!
Brandon P.

jpn
16th August 2006, 16:42
Either that or use an event filter (http://doc.trolltech.com/4.1/qobject.html#eventFilter).

jacek
16th August 2006, 16:46
Or QShortcut.

bpetty
16th August 2006, 19:11
Jacek, I like the idea of using QShortcut.

I noticed the example from the documentation:


shortcut = QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")), parent);


So instead of Ctrl+O I would use Qt::Key_Delete...
and instead of parent, I would use the name of my QListWidget object...
I would also most likely have to change the context to that of a Qt::WidgetShortcut

Is this correct? I guess I don't understand then what it returns and where the correct place to put this QShortcut would be.

jpn
16th August 2006, 19:48
Let's assume you have a list widget in a main window. Then, a natural place to create the shortcut would be in the constructor of the main window (or a function called from there). In addition, you'll need a slot (http://doc.trolltech.com/4.1/signalsandslots.html) where to react to the shortcut event.



class MainWindow...
{
...
private slots:
void deleteItem();

private:
QListWidget* listWidget;
};




MainWindow::MainWindow(...) : ...
{
// create the shortcut after the list widget has been created

// option A (pressing DEL anywhere in the main window activates the slot)
new QShortcut(QKeySequence(Qt::Key_Delete), this, SLOT(deleteItem()));

// option B (pressing DEL activates the slots only when list widget has focus)
QShortcut* shortcut = new QShortcut(QKeySequence(Qt::Key_Delete), listWidget);
connect(shortcut, SIGNAL(activated()), this, SLOT(deleteItem()));
}

void MainWindow::deleteItem()
{
delete listWidget->currentItem();
}

bpetty
16th August 2006, 20:38
Thanks a lot JPN. I guess I took it too literally. They said "shortcut = QShorcut(..)" and I was atleast expecting to see a new. I was also thinking that the new "shortcut" pointer gets destoyed... but I guess Qt knows what I want.

Thanks a lot.