创建界面时系统会自带一个标题栏,如果我们需要设计一个好看的界面,这个标题栏就会显得很突兀,所以我们需要自定义标题栏,隐藏原来的标题栏。
自定义标题栏,这些图标我们都可以自己设置,位置可以调整
具体步骤如下:
1.隐藏系统自带的标题栏
this->setWindowFlags(Qt::FramelessWindowHint);//隐藏边框
去掉标题栏会存在几个问题:
①界面会因为失去边框丢失调整大小的能力
②去除边框后,界面内容将无法移动
③原本自带的最小化、最大化、关闭按钮随着标题栏一起被隐藏了,所以接下来的步骤我们进行添加最小化、最大化、关闭按钮
2.创建最小化、最大化、关闭按钮
3.获取并设置按钮图标
4.设置按钮在界面的位置
5.设置提示信息,样式和信号槽
具体代码
//窗口标题栏设置
this->setWindowFlags(Qt::FramelessWindowHint);//隐藏边框
//构建最小化、最大化、关闭按钮
minButton = new QToolButton(this);
closeButton= new QToolButton(this);
maxButton= new QToolButton(this);
//获取最小化、关闭按钮图标
QPixmap minPix = style()->standardPixmap(QStyle::SP_TitleBarMinButton);
QPixmap closePix = style()->standardPixmap(QStyle::SP_TitleBarCloseButton);
maxPix = style()->standardPixmap(QStyle::SP_TitleBarMaxButton);//最大化需要在事件中进行判断更换图标所以设置成数据成员
//设置最小化、关闭按钮图标
minButton->setIcon(minPix);
closeButton->setIcon(closePix);
maxButton->setIcon(maxPix);
//设置最小化、关闭按钮在界面的位置
int wide = width();//获取界面的宽度
minButton->setGeometry(wide-65,5,20,20);
closeButton->setGeometry(wide-25,5,20,20);
maxButton->setGeometry(wide-45,5,20,20);
//设置鼠标移至按钮上的提示信息
minButton->setToolTip(tr("最小化"));
closeButton->setToolTip(tr("关闭"));
maxButton->setToolTip(tr("最大化"));
//设置最小化、关闭按钮的样式
minButton->setStyleSheet("background-color:transparent;");
closeButton->setStyleSheet("background-color:transparent;");
maxButton->setStyleSheet("background-color:transparent;");
//每个按钮对应的信号槽
connect(closeButton, SIGNAL(clicked()), this, SLOT(windowclosed()));
connect(minButton, SIGNAL(clicked()), this, SLOT(windowmin()));
connect(maxButton, SIGNAL(clicked()), this, SLOT(winmax()));
槽函数
public slots:
void windowclosed();//最小化 关闭
void windowmin();
void winmax();
//槽函数实现
void Logwin::windowclosed()
{
this->close();
}
void Logwin::windowmin()
{
this->showMinimized();//最小化
}
void Logwin::winmax()
{
if (this->isMaximized())
{
this->showNormal();//还原事件
maxPix = style()->standardPixmap(QStyle::SP_TitleBarMaxButton);
maxButton->setIcon(maxPix);
maxButton->setToolTip(tr("最大化"));
}
else
{
this->showMaximized();//最大化事件
restore = style()->standardPixmap(QStyle::SP_TitleBarNormalButton);
maxButton->setIcon(restore);
maxButton->setToolTip(tr("最大化还原"));
}
}
实现的效果
未放大时,鼠标移到最大化按钮上
放大时,鼠标移到上面,图标不同,内容也不同
QStyle::StandardPixmap枚举
获取的图标信息,如果觉得系统给的不好看,可以自己添加
参考QStyle(4):StandardPixmap和StyleHint枚举_hyongilfmmm的博客-CSDN博客
感谢观看!!!!
以上就是全部内容,如果对您有帮助,欢迎点赞评论,或者发现有哪里写错的,欢迎指正!