要给这三个按钮设置背景图片,你可以使用 setStyleSheet
方法为每个按钮单独设置样式。你已经注释掉了一个示例代码,这个代码正好适合用来为按钮设置背景图片。以下是如何更新你的代码以包含背景图片的示例:
CustomTitleBar::CustomTitleBar(QWidget *parent) : QWidget(parent) {
setAutoFillBackground(true);
QPalette palette = this->palette();
palette.setColor(QPalette::Background, QColor(221, 222, 226)); // 设置背景色
setPalette(palette);
QPushButton* closeButton = new QPushButton(this);
QPushButton* maximizeButton = new QPushButton(this);
QPushButton* minimizeButton = new QPushButton(this);
// 为按钮设置图标路径
QString closePath = QCoreApplication::applicationDirPath() + "/img/close.svg";
QString maximizePath = QCoreApplication::applicationDirPath() + "/img/maximize.svg";
QString minimizePath = QCoreApplication::applicationDirPath() + "/img/minimize.svg";
// 设置样式表,添加背景图像
closeButton->setStyleSheet(QString("QPushButton {"
"background-image: url(%1);"
"background-repeat: no-repeat;"
"border: none; padding: 10px;"
"}").arg(closePath));
maximizeButton->setStyleSheet(QString("QPushButton {"
"background-image: url(%1);"
"background-repeat: no-repeat;"
"border: none; padding: 10px;"
"}").arg(maximizePath));
minimizeButton->setStyleSheet(QString("QPushButton {"
"background-image: url(%1);"
"background-repeat: no-repeat;"
"border: none; padding: 10px;"
"}").arg(minimizePath));
closeButton->setFixedSize(28, 28);
maximizeButton->setFixedSize(28, 28);
minimizeButton->setFixedSize(28, 28);
connect(closeButton, &QPushButton::clicked, parent, &QWidget::close);
connect(maximizeButton, &QPushButton::clicked, this, [=]() {
if (auto window = qobject_cast<QMainWindow*>(parent)) {
if (window->isMaximized()) {
window->showNormal();
} else {
window->showMaximized();
}
}
});
connect(minimizeButton, &QPushButton::clicked, parent, &QWidget::showMinimized);
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0); // 左、上、右、下边距均设为0
layout->addStretch(); // 添加弹性空间,使按钮靠右
layout->addWidget(minimizeButton);
layout->addWidget(maximizeButton);
layout->addWidget(closeButton);
setFixedHeight(30);
}
在这个代码中,我们分别为 close
, maximize
, 和 minimize
按钮设置了各自的背景图片路径,并应用到它们的样式表中。确保相应的图片文件存在于指定路径中,以便能够正确加载和显示。
内容由零声教学AI助手提供,问题来源于学员提问