使用QStackedLayout创建一个小部件

时间:2013-08-27 04:17:50

标签: qt layout widget

大家好我对Qt编程很新,我想用QStackedLayout创建一个小部件。我已经使用Qt Creator设计了一些小部件,将它们添加到QStackedLayout并将其设置为主小部件。但现在我想使用setCurrentIndex方法使用添加的小部件内的按钮更改小部件。现在我必须使用connect函数,但在主窗口小部件类中,我无法访问其他窗口小部件中的组件来连接它们。那我怎么能这样做呢?

#include "mainwindowwidget.h"
#include "ui_mainwindowwidget.h"


MainWindowWidget::MainWindowWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWindowWidget)
{


    qApp->setStyleSheet("MainWindowWidget {background-color : red}");

    //initializing widgets
    this->mainWidget_ = new MainWidget;
    this->createGameWidget_ = new CreateGameWidget;
    this->widgets_ = new QStackedLayout;


    //adding widgets to QstackedLayout
    this->widgets_->addWidget(this->mainWidget_);
    this->widgets_->addWidget(this->createGameWidget_);

    this->setLayout(this->widgets_);
    this->showFullScreen();
    // I would like to connect the qstackedlayout
    // = widgets_ with a button placed in mainwidget_
    ui->setupUi(this);

}

MainWindowWidget::~MainWindowWidget()
{
    delete ui;
}

2 个答案:

答案 0 :(得分:1)

这里有几个选项。如果您的按钮是MainWidget的公开成员,则只需将按钮的clicked()信号连接到MainWindow的插槽即可。

//mainwindow.h
...
public slots:
   void buttonClicked();

//mainwindow.cpp
...
   connect(mainWidget_->button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
...
void buttonClicked()
{
   //do what you want to do here...
}

另一种选择是在MainWidget课程中创建自定义信号。然后将按钮的clicked()信号连接到此自定义信号:

//mainwidget.h
...
signals:
   void buttonClickedSignal();

//mainwidget.cpp
   connect(button, SIGNAL(clicked()), this, SIGNAL(buttonClickedSignal()));

然后将buttonClickedSignal()信号连接到MainWindow

中的一个插槽
//mainwindow.cpp
   connect(mainWidget_, SIGNAL(buttonClickedSignal()), this, SLOT(buttonClicked()));

第三个选项是向MainWidget类添加一个函数,该函数返回指向按钮的指针。然后在MainWindow类中调用此函数,并使用该指针将按钮连接到插槽。

//mainwidget.h
...
public:
   QPushButton* getButton();
...

//mainwdiget.cpp
...
QPushButton* getButton()
{
   return button;
}
...

//mainwindow.cpp
...
   QPushButton *button = mainWidget_->getButton();
   connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()));

答案 1 :(得分:0)

来自Qt援助

The QStackedLayout class provides a stack of widgets where only one widget is visible at a time.

因此,传递索引是识别需要在特定时间点在StackedLayout上显示的窗口小部件的关键。假设您的信号名称在mainWidget_和createGameWidget中声明为“activate(int)”_

所以你需要像这样连接

//MainWindowWidget class.
connect(MainWidget, SIGNAL(activated(int)), widgets_ , SLOT(setCurrentIndex(int)));
connect(createGameWidget_, SIGNAL(activated(int)), widgets_ , SLOT(setCurrentIndex(int)));
   //In MainWidget class you need to emit signal
    MainWidget::ChangeLayout()
    {
        emit activated(1); //createGameWidget_will be displayed
    }

   //In createGameWidget_class you need to emit signal
    createGameWidget_::ChangeLayout()
    {
        emit activated(0); //MainWidget will be displayed
    }