【问题标题】:How to set up stylesheet in QT to choose random image for wiget background?如何在 QT 中设置样式表以选择随机图像作为 wiget 背景?
【发布时间】:2017-11-07 09:04:02
【问题描述】:

所以我试图从我的电脑的文件系统中选择随机图像并将其设置为 wiget 中的背景。所以这就是我打开 QFileDialog 并使用它的原因。 qDebug 为我提供了正确的图像路径,但它仍然不起作用。

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 与我的问题有关,但在我的情况下它不起作用。

【问题讨论】:

  • 不应该是ChatWindow{background-image:url(...)而不是ChatWindow{border-image:url(...)吗?
  • @wasthishelpful 我尝试使用背景图像,但它不起作用。

标签: c++ qt qstylesheet


【解决方案1】:

根据documentation,不存在名为border-image的此类属性:您要搜索的是background-image

此外,由于您还指定了其他背景的参数,因此您应该使用background

此外,由于您的文件在磁盘上而不是在资源中,因此 url 不应以 : 开头:输入 url(" + filePath + ") 而不是 url(:" + filePath + ")

更正的语法:

setStyleSheet(
    "ChatWindow{background:url(" +
        filePath +
    ") 0 0 0 0 stretch stretch;}"
);

【讨论】:

  • 谢谢,现在可以了。下次我会更仔细地阅读文档。
猜你喜欢
  • 2011-05-26
  • 2014-03-11
  • 1970-01-01
  • 2023-03-31
  • 2011-06-17
  • 1970-01-01
相关资源
最近更新 更多