要使背景图片居中显示,可以使用 background-position
属性。在 Qt 的样式表中,可以将其设置为 center
,这样可以确保背景图像在标签中居中显示。以下是修改后的代码:
QString currentPath = QCoreApplication::applicationDirPath();
QString imagePath = currentPath + "/img/class.png";
ui->label_10->setStyleSheet(QString(
"QLabel { "
"background-image: url(%1); "
"background-color: rgb(231, 231, 231); "
"border-radius: 5px; "
"background-repeat: no-repeat; "
"background-position: center; " // 添加此行以使图片居中
"}"
).arg(imagePath));
// ui->label_10->setFixedSize(48, 48);
ui->label_10->setToolTip("班级");
ui->label_10->installEventFilter(this);
注意,在使用背景属性时,可能还需要确保 QLabel
的大小能够容纳这个背景图像。如果你希望图像的具体尺寸符合标签的尺寸,那么可以通过设置标签的固定大小来实现。例如,取消注释 setFixedSize
的代码,以确保标签具有特定的宽度和高度。
如果你想保持图片的原始比例并让它自动适应标签大小,也可以考虑使用其他方法,例如使用 QPixmap
加载图片并将其绘制到标签上。这种方式能提供更多控制,包括缩放、裁剪等效果。
内容由零声教学AI助手提供,问题来源于学员提问