一、背景
面包屑导航是一种常见的导航方式,它可以让用户了解自己在工具的具体位置,并可以通过点击面包屑中的链接快速返回上一级或者任意父级页面。
用Qt实现面包屑界面类,如下图,面包屑支持添加一页(黑色 QLabel),点击面包屑(蓝色 QPushButton)支持跳转
对外接口:void AddPage(const QString &title, const QString &objectName)
主要功能:新增一页
输入参数:title: 是新增显示的面包屑标题,objectName: 是对应显示的Page的objectName
二、主要实现代码
void BreadcrumbForm::AddPage(const QString &title, const QString &objectName)
{
if (m_currentLabel != nullptr) {
auto *preButton = new QPushButton(m_currentLabel->text(), this);
preButton->setCursor(Qt::PointingHandCursor);
preButton->setProperty("pageObjectName", m_currentBreadcrumb.objectName);
connect(preButton, &QPushButton::clicked, this, &BreadcrumbForm::GoToPage);
m_ui->horizontalLayoutItems->removeWidget(m_currentLabel);
m_currentLabel->deleteLater();
m_ui->horizontalLayoutItems->addWidget(preButton);
auto *separator = new QLabel(">", this);
m_ui->horizontalLayoutItems->addWidget(separator);
}
m_currentBreadcrumb.objectName = objectName;
m_currentBreadcrumb.title = title;
m_currentLabel = new QLabel(title, this);
m_ui->horizontalLayoutItems->addWidget(m_currentLabel);
}
三、代码解释
检查当前标签(m_currentLabel)是否为空。如果不为空,说明已经有面包屑项存在,需要先处理这个项。
创建一个新的按钮(preButton),其文本为当前标签的文本,并将其添加到布局中。这个按钮的目的是当用户点击它时,可以返回到当前标签所代表的页面。
将当前标签从布局中移除,并删除它。
创建一个新的标签(separator),其文本为">",并将其添加到布局中。这个标签用于分隔不同的面包屑项。
更新当前面包屑项(m_currentBreadcrumb)的标题和对象名称。
创建一个新的标签(m_currentLabel),其文本为传入的标题,并将其添加到布局中。这个标签代表用户当前正在浏览的页面。
如果当前标签为空,说明还没有面包屑项存在,直接创建一个新的标签(m_currentLabel),并将其添加到布局中。
四、面包屑类调用
在主界面MainForm拖一个QWidget,右键点击提升为...,增加BreadcrumnForm类。
页面跳转
连接信号BreadcrumbForm::GoToPageWidget
,在主页面处理页面的跳转
connect(m_ui->widgetBreadcrumb, &BreadcrumbForm::GoToPageWidget, this, &MainForm::GotToPageWidget);
void MainForm::GotToPageWidget(const QString &objectName)
{
auto *page = m_ui->stackedWidget->findChild<QWidget *>(objectName);
if (page == nullptr) {
return;
}
m_ui->stackedWidget->setCurrentWidget(page);
}
新增一页
直接调用AddPage
m_ui->widgetBreadcrumb->AddPage("新的一页", m_ui->pageConnect->objectName());