Reputation: 10847
I would like to toggle among QWidgets. In the code below, I'd like sceneWidget
to show either view1
or view2
, depending on which button has been pressed.
But the code hardly does that. What is wrong? (Aside from the very ugly global variables, which I leave for a next step.)
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsEllipseItem>
QGraphicsView* getView(int x, int y, int w, int h)
{
QGraphicsScene* scene = new QGraphicsScene;
scene->addItem(new QGraphicsEllipseItem(x,y,w,h));
QGraphicsView* view = new QGraphicsView(scene);
return view;
}
QVBoxLayout* rightVbox;
QGraphicsView* view1;
QGraphicsView* view2;
void c1() {
rightVbox->insertWidget(0, view1);
}
void c2() {
rightVbox->insertWidget(0, view2);
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
view1 = getView(0,0,100,50);
view2 = getView(0,0,50,100);
QWidget* mainWidget = new QWidget;
QHBoxLayout* hbox = new QHBoxLayout(mainWidget);
QWidget* buttonsWidget = new QWidget;
hbox->addWidget(buttonsWidget);
QVBoxLayout* leftVbox = new QVBoxLayout(buttonsWidget);
QPushButton* button1 = new QPushButton("Scene 1", buttonsWidget);
QPushButton* button2 = new QPushButton("Scene 2", buttonsWidget);
leftVbox->addWidget(button1);
leftVbox->addWidget(button2);
QWidget* sceneWidget = new QWidget;
hbox->addWidget(sceneWidget);
rightVbox = new QVBoxLayout(sceneWidget);
rightVbox->insertWidget(0, view1);
QObject::connect(button1, &QPushButton::clicked, c1);
QObject::connect(button2, &QPushButton::clicked, c2);
mainWidget->show();
return app.exec();
}
Upvotes: 0
Views: 81
Reputation: 5336
Use a QStackedWidget for that purpose.
http://doc.qt.io/qt-4.8/qstackedwidget.html
Upvotes: 2
Reputation: 2208
To do what you want, you should be able to simply use show
and hide
on the two items.
Quoting from the QBoxLayout
page:
Calling QWidget::hide() on a widget also effectively removes the widget from the layout until QWidget::show() is called.
I was able to switch between the two widgets with the buttons by doing this in main()
:
[...]
rightVbox = new QVBoxLayout(sceneWidget);
rightVbox->insertWidget(0, view1);
rightVbox->insertWidget(0, view2);
view2->hide();
[...]
and then change your two functions c1
and c2
to:
void c1() {
view1->show();
view2->hide();
}
void c2() {
view2->show();
view1->hide();
}
Does this do what you had in mind?
Upvotes: 0