如何在QWidget内切换两个QGraphicsView。

huangapple go评论49阅读模式
英文:

How to switch between two QGraphicsView inside a QWidget

问题

以下是代码部分的翻译:

我有两个不同的视图需要在一个QWidget窗口内显示。每个视图都有一个单独的QGraphicsScene
我想要在按钮点击时在这两个视图之间切换。

这是我的当前实现:

void toggleUi(bool type){
    QGraphicsView* currentView;
    
    if(bool){
        currentView = getFirstView(); // 返回第一类型的QGraphicsView
    }
    else{
        currentView = getSecondView(); // 返回第二类型的QGraphicsView
    }

    QLayout* layout = widget->layout();
    if (layout != 0)
    {
        QLayoutItem *item;
        while ((item = layout->takeAt(0)) != 0)
            layout->removeItem (item);
        delete layout;
    }

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(currentView);
}

问题:在切换时两个视图重叠显示,即使删除了布局并添加了新布局。没有切换时,两个视图都正常显示。是否有更好/另一种方法来实现它?

英文:

I have two different views to display inside a QWidget window. Each view has a separate QGraphicsScene.
I want to toggle between the two views on button click.

This is my current implementation:

    void toggleUi(bool type){
    QGraphicsView* currentView;
    
    if(bool){
     currentView = getFirstView(); // returns QGraphicsView of first type
    }
    else{
     currentView = getSecondView(); // returns QGraphicsView of second type
    }

    QLayout* layout = widget->layout ();
    if (layout != 0)
    {
    QLayoutItem *item;
    while ((item = layout->takeAt(0)) != 0)
        layout->removeItem (item);
    delete layout;
    }

   QVBoxLayout *layout = new QVBoxLayout(this);
   layout->addWidget(currentView);
}

Issue: Both views are displayed over one another on toggle, even after deleting the layout and adding a new one.
Both views are rendered fine without toggle.
Is there a better/another way to do it?

答案1

得分: 1

使用 QStackedWidget!使用 addWidget 函数来添加小部件:

QStackedWidget *stackedWidget = new QStackedWidget(this);
stackedWidget->addWidget(getFirstView());
stackedWidget->addWidget(getSecoundView());

QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(stackedWidget);
setLayout(layout);

这是如何在小部件之间切换的方式:

void toggleUi(bool type){
    if(condition)
        stackedWidget->setCurrentIndex(0)
    else
        stackedWidget->setCurrentIndex(1)

希望对你有帮助!

英文:

Use QStackedWidget! Use the addWidget function to add widgets:

QStackedWidget *stackedWidget = new QStackedWidget(this);
stackedWidget->addWidget(getFirstView());
stackedWidget->addWidget(getSecoundView());

QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(stackedWidget);
setLayout(layout);

Here's how to switch between the widgets:

void toggleUi(bool type){
    if(condition)
        stackedWidget->setCurrentindex(0)
    else
        stackedWidget->setCurrentindex(1)

I hope it helps!

huangapple
  • 本文由 发表于 2023年2月7日 02:37:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定