QStackedWidget
可放入多个widget控件,通过设置当前控件,来做到切换显示不同内容的效果
函数:
int addWidget(QWidget * w); 将给定的控件追加到QStackedWidget并返回索引位置。小部件的所有权被传递给QStackedWidget
QWidget * currentWidget() const; 返回当前QStackedWidget中的控件
void setCurrentWidget(QWidget *widget); 设置当前要显示的控件
int currentIndex() const;
void setCurrentIndex(int index); 同上
代码:
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::Widget *ui;
QListWidget * widget_1;
QListWidget * widget_2;
};
构造函数
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
widget_1 = new QListWidget(ui->stackedWidget);
widget_1->addItem("widget_1");
widget_2 = new QListWidget(ui->stackedWidget);
widget_2->addItem("widget_2");
ui->stackedWidget->addWidget(widget_1);
ui->stackedWidget->addWidget(widget_2);
ui->stackedWidget->setCurrentWidget(widget_1);
}
两个button的槽函数:
void Widget::on_pushButton_clicked()
{
if(ui->stackedWidget->currentWidget() != widget_1){
ui->stackedWidget->setCurrentWidget(widget_1);
}
}
void Widget::on_pushButton_2_clicked()
{
if(ui->stackedWidget->currentWidget() != widget_2){
ui->stackedWidget->setCurrentWidget(widget_2);
}
}
ui界面截图: