2013-08-27 78 views
2

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

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

回答

0

从Qt的援助

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

所以通过指数是标识微件需要在特定时间点来显示在StackedLayout一个关键的事情。假设你的信号名称为 “激活(INT)” 的中mainWidget_和createGameWidget_

宣布

所以你需要象这样连接

//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 
    } 
+0

感谢,帮助了很多 – quique

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())); 
相关问题