Implement Shortcuts to select items in QComboBox
-
Hello,
can someone help me in adding Shortcuts to QComboBox? I don't understand very well ho to implement it and I don't find clear solution on other threads, so I'll try to write it in order to help future searches.
I reimplemented QComboBox like:
@
class BoxPopupMenu : public QComboBox
{public:
BoxPopupMenu(QWidget parent = 0) :
QComboBox(parent)
{
view()->installEventFilter(this);
};
@
I reimplemented the keyPressEvent(), to add new Shortcuts (technically, this is the area where I set the code to be executed when specific Key() are pressed):
@
void keyPressEvent(QKeyEvent e)
{
if (Qt::Key_Up == e->key() || Qt::Key_Down == e->key())
return;if (Qt::Key_Left == e->key()) { ..code.. } ... }
@
then I discovered that, to let the popup change the item, I have to create an eventFilter to be added to the method view()->installEventFilter(this);So I wrote:
@
bool eventFilter(QObject *t, QEvent *e)
{
if(e->type() == QEvent::KeyPress) //here I choose what kind of Event I'm interested in
{
QKeyEvent keyEvent = static_cast<QKeyEvent>(e); //here, I return what is the key pressed
int key = keyEvent->key();[...] } return ... }
@
Now, what I miss is how to fill [...] and what to return at the end.
Should I return a sendEvent? Is the receiver the QObject *t? What is the event to send?[andreyc EDIT]: Add '@' around code.
-
I'm sorry for the bad layout but the website set it automatically
-
This is what I have done, and in Linux it works.
I have implemented a CTRL+Tab which changes the item and the document associated to it.
@class BoxPopupMenu : public QComboBox
{public:
BoxPopupMenu(QWidget *parent = 0) :
QComboBox(parent)
{
view()->installEventFilter(this);
};private:
bool eventFilter(QObject *t, QEvent *e)
{
QKeyEvent keyEvent = static_cast<QKeyEvent>(e);
int key = keyEvent->key();if(e->type() == QEvent::KeyPress) { switch(key) { case Qt::Key_Backtab: //case Qt::Key_Up: { // changes the index int curIndex = this->currentIndex(); int nextIndex; if (this->currentIndex() == 0) nextIndex = this->count() -1; else { nextIndex = curIndex - 1; } this->setCurrentIndex(nextIndex); // changes the item selection QComboBox::keyPressEvent(keyEvent); break; } case Qt::Key_Tab: //case Qt::Key_Down: { int curIndex = this->currentIndex(); int nextIndex; if (this->currentIndex() == this->count() -1 ) nextIndex = 0; else { nextIndex = curIndex + 1; } this->setCurrentIndex(nextIndex); QComboBox::keyPressEvent(keyEvent); break; } } } if(e->type() == QEvent::KeyRelease) { switch(key) { case Qt::Key_Control: this->hidePopup(); } } return true; }
};@