Domanda

I am working on a project in Qt 4.7 where a have a QListWidget which needs to perform a certain function when an item from the list is selected. The particular function isn't important here, so for this example let's say it is to print the value to std::cout. I have it right now so that it does this when a value is double-clicked, like so:

connect(ui->myList, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(printChoice(QModelIndex))); ... void MyClass::printChoice(QModelIndex index) { std::cout << ui->myList->model()->data(index).toString(); }

This code works perfectly. However, my project lead said they would like it to enter this slot for whatever row of the list is currently selected when the user clicked the F2 key. I do not know of any signals that are emitted for these keys, and looking around the web hasn't helped much. Does anyone know of a way to do this? Thanks!

EDIT: I've found that hitting F2 while a value is selected automatically puts that row into edit mode (it must be built in to Qt) but I still need to know how to trigger a slot when that occurs.

EDIT 2: I'm getting closer. I found I could make a slot in MyClass called keyPressEvent(QKeyEvent *event) that will register whenever certain keys are hit, including the fX keys. However, I still cannot find a way to differentiate which key triggered it, and how to make sure it was F2

È stato utile?

Soluzione

Implement the virtual function keyPressEvent from base class QWidget:

void YourWidget::keyPressEvent(QKeyEvent *event)
{
    if( event->key() == Qt::Key_F2 )
    {
        emit F2isPressed(/* some signature */); // connected elsewhere
    }
}

OP Note: While this answer doesn't quite work correctly for the particular case I was trying to figure out (the F2 key being pressed), it does work for pretty much any other key that will trigger that function (e.g the other Fx keys, etc.). It turns out F2 is a really weird case for Qt and requires some workaround to get to work. To see how the original post was solved by myself and the poster of this question, you can look in the chat here. I'm going to mark this answer as accepted, because although it doesn't work for this one particular case, it is in general the correct answer for this type of problem.

Altri suggerimenti

You can use QShortcut to invoke a slot :

QShortcut * shortcut = new QShortcut(QKeySequence(Qt::Key_F2),this,SLOT(printChoice()));
shortcut->setAutoRepeat(false);

In the slot printChoice() you can print the contents of the selected row.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top