qt中QtreeWidget与QstackWidget关联的问题

过程:要做一个图书管理系统,主界面是类似于这样的

左边是类似于树形空间的东西,当点击左边的左边的窗体的时候,右边的窗口也会跟着切换。
为了实现这个功能,必须要有两个控件,QTreeWidget和QstackWidget;
以下是具体代码
1.Widge.h头文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QStackedWidget>
#include<QTreeWidget>
#include<QTreeWidgetItem>
#include<QString>
#include<QLabel>
#include<QGridLayout>
#include<QHBoxLayout>
#include<QStringList>

class Widget : public QWidget
{
Q_OBJECT

public:
Widget(QWidget *parent = 0);
~Widget();
private:
QStackedWidget *stackWindow;
QHBoxLayout *mainLayout;
QTreeWidget *treeWidget;
QTreeWidgetItem *parentItem1;
QTreeWidgetItem *parentItem2;
QTreeWidgetItem *childItem1;
QTreeWidgetItem *childItem2;
QLabel *parentLable1;
QLabel *parentLable2;
QLabel *childLable1;
QLabel *childLable2;
public slots:
void change1(QTreeWidgetItem* item1,int count1);

};

#endif // WIDGET_H

2.Widget.cpp具体的实现

#include "widget.h"
#include<QObject>

Widget::Widget(QWidget *parent)
: QWidget(parent)
{

//connect(treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(change1(QTreeWidgetItem*,int)));

stackWindow =new QStackedWidget;
mainLayout =new QHBoxLayout;
treeWidget =new QTreeWidget(this);
parentItem1=new QTreeWidgetItem(treeWidget,QStringList("parent1"));
parentItem2=new QTreeWidgetItem(treeWidget,QStringList("parent2"));
childItem1=new QTreeWidgetItem(parentItem1,QStringList("child1"));
childItem2=new QTreeWidgetItem(parentItem2,QStringList("child2"));
parentLable1=new QLabel("parentWindow1");
parentLable2=new QLabel("parentWindow2");
childLable1=new QLabel("childLable1");
childLable2=new QLabel("childLable2");
stackWindow->addWidget(parentLable1);
stackWindow->addWidget(parentLable2);
stackWindow->addWidget(childLable1);
stackWindow->addWidget(childLable2);
mainLayout->addWidget(treeWidget);
mainLayout->addWidget(stackWindow);
// stackWindow->setCurrentIndex(2);

this->setLayout(mainLayout);
//QObject::connect(treeWidget,SIGNAL(itemPressed(QTreeWidgetItem*,int)),this,SLOT(change1(QTreeWidgetItem* ,int )));//注释1
QObject::connect(treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(change1(QTreeWidgetItem* ,int)));

}

Widget::~Widget()
{

}
void Widget::change1(QTreeWidgetItem *item1, int count1)
{
QTreeWidgetItem *item=item1;
if(item->text(count1)=="parent1")
{
stackWindow->setCurrentIndex(0);
}
else if(item->text(count1)=="parent2")
{
stackWindow->setCurrentIndex(1);
}
else if(item->text(count1)=="child1")
{
stackWindow->setCurrentIndex(2);
}
else if(item->text(count1)=="child2")
{
stackWindow->setCurrentIndex(3);
}

}

注释1:
这两个连接中的槽函数的参数只能给出类型,而不能给出形参名;
这两个连接必须写在窗口初始化之后
 
转自 https://blog.csdn.net/u013377068/article/details/78405158
posted @ 2018-08-16 16:57  学习随笔记  阅读(1411)  评论(0编辑  收藏  举报