Qt动态多级导航菜单(二)

前文链接:Qt动态多级导航菜单
针对上个版本存在的一些问题进行修复,并着重改进菜单伸缩方式,由压缩改为平移。
效果图
Qt动态多级导航菜单(二)_第1张图片
核心代码

NavItem *QWHNavTreeView::addChildItem(const QString &text, NavItem *parent)
{
    NavItem *navBtn = new NavItem(text, parent);
	navBtn->setView(this);
    navBtn->m_level = parent->m_level + 1;
    navBtn->m_parent = parent;
    m_navItems.append(navBtn);
	parent->addChild(navBtn);

    if (!parent->m_container)
    {// parent节点无容器,即parent节点从未有过孩子节点
		parent->m_container = new QScrollArea(this);
		parent->m_container->setFrameShape(QFrame::NoFrame);
		parent->m_container->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
		parent->m_container->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

		QHBoxLayout *hLayout = new QHBoxLayout(parent->m_container);
		hLayout->setContentsMargins(0, 0, 0, 0);
		parent->m_container->setLayout(hLayout);

        QWidget *widget = new QWidget(parent->m_container);
        QVBoxLayout *vLayout = new QVBoxLayout(widget);
        vLayout->setContentsMargins(0, 0, 0, 0);
        vLayout->setSpacing(0);
        widget->setLayout(vLayout);

        vLayout->addWidget(navBtn);
		QVBoxLayout *parentVLayout = (QVBoxLayout *)(parent->parentWidget())->layout();
		int index = parentVLayout->indexOf(parent);
		
		parent->m_container->setWidget(widget);
		hLayout->addWidget(widget);
		widget->setFixedHeight(NavItem::HEIGHT);
		parent->m_container->setFixedHeight(NavItem::HEIGHT);
		parentVLayout->insertWidget(index + 1, parent->m_container);
    }
    else {// parent节点有/有过孩子节点
        QWidget *widget = parent->m_container->widget();
        QVBoxLayout *vLayout = (QVBoxLayout *)widget->layout();
        vLayout->addWidget(navBtn);

		widget->setFixedHeight(vLayout->count() * NavItem::HEIGHT);
		parent->m_container->setFixedHeight(vLayout->count() * NavItem::HEIGHT);
    }

	// 父节点窗口调整高度
	while (parent->m_parent)
	{
		QWidget *widget = parent->m_parent->m_container->widget();
		widget->setFixedHeight(widget->height() + NavItem::HEIGHT);
		parent->m_parent->m_container->setFixedHeight(widget->height());

		parent = parent->m_parent;
	}

	connect(navBtn, &QPushButton::clicked, this, &QWHNavTreeView::onItemClicked);

    return navBtn;
}

你可能感兴趣的:(自定义控件,qt,开发语言)