如何在QT中设置样式表来为wiget背景选择随机图片?
问题描述:
所以我试图从我的电脑的文件系统中选择随机图像,并使其在wiget中的背景。所以这就是为什么我打开QFileDialog并使用它。 qDebug为我提供了正确的图像路径,但它仍然不起作用。如何在QT中设置样式表来为wiget背景选择随机图片?
void ChatWindow::on_actionImage_triggered()
{
QString fileName = QFileDialog::getOpenFileName(
this, tr("Open file"), "/home", tr("Images(*.jpg)")
);
QString filePath(fileName);
qDebug() << filePath;
setStyleSheet(
"ChatWindow{border-image:url(:" +
filePath +
") 0 0 0 0 stretch stretch;}"
);
QGraphicsOpacityEffect * effect1 =
new QGraphicsOpacityEffect(ui->messageHistory);
effect1->setOpacity(0.8);
ui->messageHistory->setGraphicsEffect(effect1);
ui->messageHistory->setStyleSheet("background-color: white;");
QGraphicsOpacityEffect * effect2 =
new QGraphicsOpacityEffect(ui->roomTree);
effect2->setOpacity(0.8);
ui->roomTree->setGraphicsEffect(effect2);
ui->roomTree->setStyleSheet("background-color: white;");
QGraphicsOpacityEffect * effect3 =
new QGraphicsOpacityEffect(ui->messageInput);
effect3->setOpacity(0.8);
ui->messageInput->setGraphicsEffect(effect3);
ui->sendButton->setStyleSheet("background-color: none;");
}
我已经看到了这一个Unable to set the background image in Qt Stylesheet涉及到我的问题,但对我来说这是行不通的。
答
根据documentation,没有这样的属性,称为border-image
:你正在寻找的是background-image
。
此外,由于您还指定了其他背景的参数,因此应使用background
。
此外,由于您的文件位于磁盘上,而不是资源中,因此网址不应以:
:url(" + filePath + ")
而不是url(:" + filePath + ")
开头。
校正语法:
setStyleSheet(
"ChatWindow{background:url(" +
filePath +
") 0 0 0 0 stretch stretch;}"
);
+0
谢谢,现在它可以工作。下次我会更仔细地阅读文档。 –
它不应该是'ChatWindow {背景图像:网址(...)的''而不是{ChatWindow边界图像:网址(...)'? – wasthishelpful
@wasthishelpful我试图使用背景图像,但它不起作用。 –