How to connect my QToolButton to setIndexPage on my QStackedWidget in Qt?
I have a QStackedWidget
whose first page is set to Wgt1
. Wgt1
contains 3 buttons btn1,btn2
and
btn3
. I want to do following
- When widget starts it should setIndex as zero that is my first page on
QStackedWidget
. - When I press
btn1,btn2
andbtn3
, I should move to indexPage 1 , 2 and 3 respectively.
I wanted to use signal and slot so tried to connect the clicked()
signal of QToolButton
to setCurrentIndex(int)
slot of QStackedWidget
. But It does not work as click()
does not send any (int) value required by setCurrentIndex(int)
. So for this I thought to override the MousePressEvent(MouseEvent *e)
. I want to do something like to introduce a new signal(int)
in my Wgt1
so that it will emit some certain integer value on pressing the buttons on first page.
But to implement this I am not clear about following
- Which
MousePressEvent()
I should override? For myWgt1
(which contains the buttons) or for theQToolButtons
which is contained by myWgt1
? - If I want to override for
Wgt1
how I can detect whichQToolButton
is pressed in theQMousePressEvent
?- If I want to override for
QToolButton
how to write it? Should I create a new class deriving from QToolButton? or can I assign some function pointer or event handler toMousePressEvent()
?
- If I want to override for
If you can answer the above questions it will be helpful otherwise you can suggest any other way also to solve this problem. I don't know if I explained my problem clearly or not. Please r开发者_开发知识库evert back I will try to explain it more.
There are many possible solutions, but I recommend to use QSignalMapper. I think that overriding an event handler is more complex than necessary.
The code would look something like:
QSignalMapper* sm = new QSignalMapper(this);
// connect to `clicked' on all buttons
connect(btn1, SIGNAL(clicked()), sm, SLOT(map()));
connect(btn2, SIGNAL(clicked()), sm, SLOT(map()));
connect(btn3, SIGNAL(clicked()), sm, SLOT(map()));
// setMapping on each button to the QStackedWidget index we'd like to switch to
// note: this affects the value passed via QSignalMapper::mapped(int) signal
sm->setMapping(btn1, 1);
sm->setMapping(btn2, 2);
sm->setMapping(btn3, 3);
// finally, connect the mapper to the stacked widget
connect(sm, SIGNAL(mapped(int)), stackedWidget, SLOT(setCurrentIndex(int)));
精彩评论