Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching between one QToolButton to another in QT

I want to switch from one QToolButton to another in QToolBar. I have used QStackedWidget, their it is too simple to move from one widget to other but here I am not able to get how to move via using keyReleaseEvent.

mywindow::mywindow() : QMainWindow()
{   
    widget = new QWidget();
    setCentralWidget(widget);

    tool = new QToolBar();
    vertical = new QVBoxLayout();
    button1 = new QToolButton();
    connect( button1, SIGNAL(clicked()), this, SLOT(fileNew()) );

    button2 = new QToolButton();
    button3 = new QToolButton();

    button1->setIcon(QIcon("download.jpg"));
    button1->setGeometry(0,0,100,200);
    button2->setIcon(QIcon("images.jpg"));
    button3->setIcon(QIcon("settings-icon.jpg"));

    //stack1->addWidget(button1);
    //stack1->addWidget(button2);
    //stack1->addWidget(button3);

    tool->addWidget(button1);
    tool->addWidget(button2);
    tool->addWidget(button3);
    //tool->addWidget(stack1);

    vertical->addWidget(tool);
    widget->setLayout(vertical);
}

void mywindow::keyReleaseEvent(KeyEvent *event)
{
    switch(event->key())
    {
        case:Qt::Key_Left:


    }
}
like image 367
Suresh Avatar asked Oct 21 '22 16:10

Suresh


1 Answers

You need to check against the focus, and shift that as appropriate. I would write something like this:

void mywindow::keyReleaseEvent(KeyEvent *event)
{
    switch(event->key())
    {
        case:Qt::Key_Left:
            if (button3->hasFocus())
                button2->setFocus();
            else if (button2->hasFocus())
                button1->setFocus();
            break;
        case:Qt::Key_Right:
            if (button1->hasFocus())
                button2->setFocus();
            else if (button2->hasFocus())
                button3->setFocus();
            break;
    }
}

Note that this code can go tedious easily if you keep adding further buttons. I would place them into a container. Then, I would iterate through that container forward and reverse order depending on the focus switching logic.

See the documentation for further details:

focus : const bool

This property holds whether this widget (or its focus proxy) has the keyboard input focus.

By default, this property is false.

Note: Obtaining the value of this property for a widget is effectively equivalent to checking whether QApplication::focusWidget() refers to the widget.

Access functions: bool hasFocus() const

like image 177
lpapp Avatar answered Nov 15 '22 06:11

lpapp