Qt中添加图片
Qt中样式表的使用
Qt 样式表是一种强大的 Qt 机制,它允许自定义小部件的外观。Qt 样式表的概念、术语和语法 HTML 层叠样式表 (CSS) 类似。
标签显示图片活或文字,调整颜色和字体大小。
在label中通过样式表添加文字或图片
QFrame, QLabel, QToolTip {
border: 2px solid green;
border-radius: 4px;
padding: 2px;
background-image: url(images/welcome.png);
}
//样式表格式在帮助中查找 border按控件大小填充
QLabel{
border-image:url(:/images/C:/Users/m1519/Desktop/QT/image/01_bg.png);
} //设置lable图片
QLabel{
color :red;
font-size:30px
} //设置lable字体颜色和大小
QWidget{
background-color :red;
} //设置窗口背景颜色
通过代码更改样式表
#include "widget.h"
#include "ui_widget.h"
#include <QLabel>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
// 通过代码更改样式表
this->setStyleSheet("QWidget{background-color:blue}");
QLabel *lable = new QLabel(this);
lable->setGeometry(0, 0, 100, 100);
lable->setStyleSheet("QLabel{background-color:red}");
this->resize(800, 480);
// ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
添加 qss文件。 QSS文件是使用 Qt程序相关联的样式表文件。它由 GUI元素的外观和感
觉,包括布局,颜色,鼠标的行为,大小和字体。它的风格,一个可以合并到一个。
添加 命名style.qss文件
将文件中的代码删除,增加修改样式表的代码填入,如下:
style.qss文件
QWidget{background-color:blue}
QLabel{background-color:red}
QLabel#lable2{background-color:green}
main.cpp文件
#include "widget.h"
#include <QApplication>
#include <QFile>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
/* 指定文件 */
QFile file(":/style.qss");
/* 判断文件是否存在 */
if (file.exists()) {
/* 以只读的方式打开 */
file.open(QFile::ReadOnly);
/* 以字符串的方式保存读出的结果 */
QString styleSheet = QLatin1String(file.readAll());
/* 设置全局样式 */
qApp->setStyleSheet(styleSheet);
/* 关闭文件 */
file.close();
}
Widget w;
w.show();
return a.exec();
}
widget.cpp文件
#include "widget.h"
#include "ui_widget.h"
#include <QLabel>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
// 通过代码更改样式表
// this->setStyleSheet("QWidget{background-color:blue}");
QLabel *lable = new QLabel(this);
lable->setGeometry(0, 0, 100, 100);
QLabel *lable2 = new QLabel(this);
lable2->setGeometry(100, 100, 100, 100);
lable2->setObjectName("lable2");
// lable->setStyleSheet("QLabel{background-color:red}");
this->resize(800, 480);
// ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}