QT实现自定义侧边导航栏
立即下载
资源介绍:
侧边导航栏是应用程序界面的一种常见布局,它通常位于页面或应用程序的侧边位置,用来展示导航菜单或功能链接,方便用户快速访问不同的页面或功能。本示例展示了在QT中,通过自定义QWidget来实现自定义的侧边导航栏。你可以根据需要修改样式、添加图标等来达到你想要的效果。
#include "qnavigationwidget.h"
#include
#include
QNavigationWidget::QNavigationWidget(QWidget *parent) : QWidget(parent)
{
backgroundColor = "#E4E4E4";
selectedColor = "#2CA7F8";
mouseInColor = "#C4C4C4";
rowHeight = 40;
currentIndex = 0;
mouseMoveIndex = -1;
setMouseTracking(true);
setFixedWidth(120);
}
QNavigationWidget::~QNavigationWidget()
{
}
void QNavigationWidget::addItem(const QString &iconPath,const QString &title)
{
listIcons << iconPath;
listItems << title;
update();
}
void QNavigationWidget::setWidth(const int &width)
{
setFixedWidth(width);
}
void QNavigationWidget::setBackgroundColor(const QColor &color)
{
backgroundColor = color;
update();
}
void QNavigationWidget::setSelectColor(const QColor &color)
{
selectedColor = color;
update();
}
void QNavigationWidget::setMouseInColor(const QColor &color)
{
mouseInColor = color;
update();
}
void QNavigationWidget::setRowHeight(const int &height)
{
rowHeight = height;
update();
}
void QNavigationWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
// Draw background color.
painter.setPen(Qt::NoPen);
painter.setBrush(backgroundColor);
painter.drawRect(rect());
// Draw Items
int count = 0;
for (const QString &str : listItems)
{
QPainterPath itemPath;
itemPath.addRect(QRect(0, count * rowHeight, width(), rowHeight));
if (currentIndex == count)
{
painter.setPen("#FFFFFF");
painter.fillPath(itemPath, selectedColor);
}
else if(mouseMoveIndex == count)
{
painter.setPen("#FFFFFF");
painter.fillPath(itemPath, mouseInColor);
}
else
{
painter.setPen("#202020");
painter.fillPath(itemPath, backgroundColor);
}
//painter.drawText(QRect(40, count * rowHeight, width()-40, rowHeight), Qt::AlignVCenter | Qt::AlignHCenter, str);
painter.drawPixmap(QRect(20, (count * rowHeight+(rowHeight-20)/2), 20, 20),QPixmap(listIcons[count]));
painter.drawText(QRect(45, count * rowHeight, width()-40, rowHeight), Qt::AlignVCenter, str);
++count;
}
}
void QNavigationWidget::mouseMoveEvent(QMouseEvent *e)
{
if (e->y() / rowHeight < listItems.count())
{
mouseMoveIndex = e->y() / rowHeight;
}
else
{
mouseMoveIndex = -1;
}
update();
}
void QNavigationWidget::mousePressEvent(QMouseEvent *e)
{
if (e->y() / rowHeight < listItems.count())
{
currentIndex = e->y() / rowHeight;
emit currentItemChanged(currentIndex);
update();
}
}
void QNavigationWidget::leaveEvent(QEvent *)
{
if(mouseMoveIndex !=-1 )
{
mouseMoveIndex = -1;
update();
}
}