KeyBoard Event in QListWidget



  • I want to use keyboard up down left right buttons .
    So i have re-implemented the QListWidget class
    @class qListWidget :
    public QListWidget
    {
    public:
    qListWidget(void)
    {
    }

    ~qListWidget(void)
    {
    }
    void keyPressEvent(QKeyEvent* event)
    {
    QListWidget::keyPressEvent(event);
    emit itemSelectionChanged();

    }
    }@
    Now What signal should i Emit
    I initially thought of emitting itemSelectionChanged()
    and but what slot should i connect it to
    Suppose i connect to a self defined function MyFunc()

    @ connect(listwidget,SIGNAL(itemSelectionChanged(),this,SLOT(MyFuc())) @

    what code should i put in MyFunc function to get current select item
    @
    QlistWidget* MyFuc()
    {
    ??
    }
    @



  • First of all, you have to get the ID of the pressed key:
    @
    class my_list : public QListWidget
    {
    Q_OBJECT
    private:
    int key_pressed = 0;

    public:
    my_list(QWidget* parent = 0);

    void keyPressEvent(QKeyEvent* event)
    {
    QListWidget::keyPressEvent(event);
    key_pressed = event->key(); // store Qt::Key value in variable key_pressed
    emit itemSelectionChanged();
    }

    public slots:
    void MyFunc();
    }
    @
    In function MyFunc(), you'll then have to check which key was pressed and react on that, if necessary:
    @my_list *list = new my_list();
    connect(list,SIGNAL(itemSelectionChanged(), list,SLOT(MyFuc()));

    void my_list::MyFunc()
    {
    int row = this->indexFromItem(this->currentItem())->row();
    int column = this->indexFromItem(this->currentItem())->column();

    if(key_pressed == Qt::Key_Left)
    column--;
    else if(key_pressed == Qt::Key_Right)
    column++;
    else if(key_pressed == Qt::Key_Down)
    row--;
    else if(key_pressed == Qt::Key_Up)
    row++;

    if(key_pressed != 0)
    this->setCurrentItem(itemAt(row, column));
    key_pressed = 0;
    }@
    I did not check this code, but maybe that gives you an idea how to handle that...


  • Lifetime Qt Champion

    Hi,

    Why do you need to reimplement keyPressEvent ? Keyboard navigation is already active on QListWidget ?

    currentItem looks like the function you need



  • @SGaist But how do we know when an item selection has changed


  • Lifetime Qt Champion

    Connect a slot to the itemSelectionChanged signal, or depending on your needs currentItemChanged. There's no need to reimplement anything keyboard wise, it's already working.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.