C++ 在QWidget之间切换
我想在QWidgets之间切换。在下面的代码中,我希望C++ 在QWidget之间切换,c++,qt,C++,Qt,我想在QWidgets之间切换。在下面的代码中,我希望sceneWidget根据按下的按钮显示view1或view2 但《守则》几乎没有做到这一点。怎么了?(除了非常难看的全局变量,我将其留到下一步。) #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 QGraphicsView*getView(整数x,整数y,整数w,整数h) { Qgraphicscene*场景=新的Qgraphicscene; 场景->添加项(新的QGraphicsSellipseitem(x,y,w,h
sceneWidget
根据按下的按钮显示view1
或view2
但《守则》几乎没有做到这一点。怎么了?(除了非常难看的全局变量,我将其留到下一步。)
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
QGraphicsView*getView(整数x,整数y,整数w,整数h)
{
Qgraphicscene*场景=新的Qgraphicscene;
场景->添加项(新的QGraphicsSellipseitem(x,y,w,h));
QGraphicsView*视图=新的QGraphicsView(场景);
返回视图;
}
QVBoxLayout*右VBox;
QGraphicsView*视图1;
QGraphicsView*视图2;
无效c1(){
rightVbox->insertWidget(0,视图1);
}
无效c2(){
rightVbox->insertWidget(0,视图2);
}
int main(int argc,char*argv[])
{
QApplication应用程序(argc、argv);
view1=getView(0,0100,50);
view2=getView(0,0,50100);
QWidget*mainWidget=新的QWidget;
QHBoxLayout*hbox=新的QHBoxLayout(mainWidget);
QWidget*按钮Widget=新的QWidget;
hbox->addWidget(按钮widget);
QVBoxLayout*leftVbox=新的QVBoxLayout(按钮小部件);
QPushButton*button1=新的QPushButton(“场景1”,buttonsWidget);
QPushButton*button2=新的QPushButton(“场景2”,buttonsWidget);
leftVbox->addWidget(按钮1);
leftVbox->addWidget(按钮2);
QWidget*sceneWidget=新的QWidget;
hbox->addWidget(场景窗口);
rightVbox=新的QVBoxLayout(sceneWidget);
rightVbox->insertWidget(0,视图1);
QObject::connect(按钮1,&QPushButton::单击,c1);
QObject::connect(按钮2和QPushButton::单击,c2);
mainWidget->show();
返回app.exec();
}
要想做你想做的事,你只需在这两个项目上使用show
和hide
。
从QBoxLayout
页面引用:
在小部件上调用QWidget::hide()也可以有效地从布局中删除小部件,直到调用QWidget::show()
通过在main()
中执行此操作,我可以使用按钮在两个小部件之间切换:
然后将两个功能c1
和c2
更改为:
void c1() {
view1->show();
view2->hide();
}
void c2() {
view2->show();
view1->hide();
}
这符合你的想法吗 为此使用QStackedWidget
QTabWidget和QStackedWidget之间的通常比较让我想知道,当标签或堆栈数量没有上限时,两者是否合适。你知道如果小部件的数量是成百上千,QStackedWidget是否合适吗?与tab小部件相比,堆叠小部件显然可以更好地扩展到多个小部件。试试看,应该行得通。
[...]
rightVbox = new QVBoxLayout(sceneWidget);
rightVbox->insertWidget(0, view1);
rightVbox->insertWidget(0, view2);
view2->hide();
[...]
void c1() {
view1->show();
view2->hide();
}
void c2() {
view2->show();
view1->hide();
}