【问题标题】:Toggling among QWidgets在 QWidget 之间切换
【发布时间】:2016-01-16 03:46:16
【问题描述】:

我想在 QWidgets 之间切换。在下面的代码中,我希望 sceneWidget 显示 view1view2,具体取决于按下的按钮。

但代码几乎没有这样做。怎么了? (除了非常丑陋的全局变量,我留待下一步。)

#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();
}

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    为此目的使用 QStackedWidget。

    http://doc.qt.io/qt-4.8/qstackedwidget.html

    【讨论】:

    • QTabWidget 和 QStackedWidget 之间的通常比较让我想知道当一个选项卡或堆栈的数量没有上限时是否适合。如果小部件数量为数百或数千,您是否知道 QStackedWidget 是否适合?
    • 与标签小部件相比,堆叠小部件肯定能更好地扩展到多个小部件。试试看,应该可以的。
    【解决方案2】:

    要做你想做的,你应该能够简单地在这两个项目上使用showhide。 引用QBoxLayout 页面:

    在小部件上调用 QWidget::hide() 也会有效地从布局中删除小部件,直到调用 QWidget::show()。

    通过在main() 中执行此操作,我能够使用按钮在两个小部件之间切换:

    [...]
    rightVbox = new QVBoxLayout(sceneWidget);
    rightVbox->insertWidget(0, view1);
    rightVbox->insertWidget(0, view2);
    view2->hide();
    [...]
    

    然后将你的两个函数c1c2改为:

    void c1() {
      view1->show();
      view2->hide();
    }
    
    void c2() {
      view2->show();
      view1->hide();
    
    }
    

    这是否符合您的想法?

    【讨论】:

      猜你喜欢
      • 2023-02-07
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多