2017-06-06 31 views
0

所以我試圖從我的電腦的文件系統中選擇隨機圖像,並使其在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涉及到我的問題,但對我來說這是行不通的。

+0

它不應該是'ChatWindow {背景圖像:網址(...)的''而不是{ChatWindow邊界圖像:網址(...)'? – wasthishelpful

+0

@wasthishelpful我試圖使用背景圖像,但它不起作用。 –

回答

0

根據documentation,沒有這樣的屬性,稱爲border-image:你正在尋找的是background-image

此外,由於您還指定了其他背景的參數,因此應使用background

此外,由於您的文件位於磁盤上,而不是資源中,因此網址不應以:url(" + filePath + ")而不是url(:" + filePath + ")開頭。

校正語法:

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

謝謝,現在它可以工作。下次我會更仔細地閱讀文檔。 –