Two-widgets stacked widget switching when mouse hovers it.
-
I would like to create a 2-widgets stacked widget with the following property:
if the mouse hovers the stacked widget then the current index is set to 0
else the current index is set to 1
The following code produce SIGSEGV. Note also that this->setCurrentIndex(1) in the constructor is ineffective.<code> MyQStackedWidget::MyQStackedWidget(QWidget *parent) : QStackedWidget(parent) { setAttribute(Qt::WA_Hover); fprintf(stderr,"Creator Stacked\n"); this->setCurrentIndex(1); // THIS HAS NO EFFECT !! } bool MyQStackedWidget::event(QEvent* e) { switch(e->type()) { case QEvent::HoverEnter: hoverEnter(static_cast<QHoverEvent*>(e)); return true; case QEvent::HoverLeave: hoverLeave(static_cast<QHoverEvent*>(e)); return true; default: break; } return QWidget::event(e); } void MyQStackedWidget::enterEvent(QEvent* e) { fprintf(stderr,"enterEvent MyQStackedWidget\n"); } void MyQStackedWidget::leaveEvent(QEvent* e) { fprintf(stderr,"leaveEvent MyQStackedWidget\n"); } void MyQStackedWidget::hoverEnter(QHoverEvent* event) { fprintf(stderr,"hoverEnter MyQStackedWidget\n"); int i = (this->currentIndex()+1)%2; this->setCurrentIndex(i); } void MyQStackedWidget::hoverLeave(QHoverEvent* event) { fprintf(stderr,"hoverLeave MyQStackedWidget\n"); int i = (this->currentIndex()+1)%2; this->setCurrentIndex(i); } </code>
-
@dauriac said in Two-widgets stacked widget switching when mouse hovers it.:
Note also that this->setCurrentIndex(1) in the constructor is ineffective.
You cannot set the current index in a
QStackedWidget
to more than the number of widgets you have added to it. In the constructor that will be 0, hence notsetCurrentIndex(1)
. Since you never add any widgets anywhere you won't ever be able to move the index off -1.For a
SIGSEGV
run under debugger and look at stack trace to see where it emanates from. -
@JonB
Thank you for your answer !
Concerning the ineffective setindex it is clear (sorry I shoud have think a little more!).
Concerning my real problem I add below the code of the setting of the MyQStackedWidgetMyQStackedWidget* sw = new MyQStackedWidget(); QLabel* lab = new QLabel("stacked label"); QTextEdit* textE = new QTextEdit("textEdit"); sw->addWidget(textE); // index 0 sw->addWidget(lab); // index 1 mainLayout->addWidget(sw,1,1);
-
@dauriac
Then with the code above, which in itself will work and not crash, what is the problem? You can change the index after they have been added. If it's the crash I said what to do. If it's the index not changing, make sure theQStackedWidget
itself is getting those hover etc. events, maybe they only occur on the widgets placed on it, I don't know. -
@JonB
I understood : this NOT the QStackedWidget which is hovered or not, but it is the selected widget. And my callback function changes the selected widget, so it generates a new event and so on and so forth ... At the end there is a stack overflow. Easy to prevent with an extra bool variable. -