2011-04-25 146 views
3

我在QtCreator的設計器中用C++/Qt編寫接口。選擇什麼元素作爲背景圖像的矩形?如何用QT繪製平鋪圖像

第二個問題:如何繪製平鋪圖像?我有和圖像的大小(1×50),我想呈現它的父寬度。有任何想法嗎?


mTopMenuBg = QPixmap("images/top_menu_bg.png"); 
mTopMenuBrush = QBrush(mTopMenuBg); 
mTopMenuBrush.setStyle(Qt::TexturePattern); 
mTopMenuBrush.setTexture(mTopMenuBg); 

ui->graphicsView->setBackgroundBrush(mTopMenuBrush); 

QBrush:不正確地使用 TexturePattern的

回答

7

如果你只是想顯示的圖像可以使用QImage。用圖像平鋪構建一個帶有QImage的QBrush的背景。然後,例如,如果您使用的是QGraphicsScene,則可以將背景刷設置爲背景刷。

這裏是填補與平鋪圖像「document.png」整個主窗口的例子:

int main(int argc, char *argv[]) { 
    QApplication app(argc, argv); 
    QMainWindow *mainWindow = new QMainWindow(); 

    QGraphicsScene *scene = new QGraphicsScene(100, 100, 100, 100); 
    QGraphicsView *view = new QGraphicsView(scene); 
    mainWindow->setCentralWidget(view); 

    QImage *image = new QImage("document.png"); 
    if(image->isNull()) { 
     std::cout << "Failed to load the image." <<std::endl; 
    } else { 
     QBrush *brush = new QBrush(*image); 
     view->setBackgroundBrush(*brush); 
    } 

    mainWindow->show(); 
    return app.exec(); 
} 

生成的應用程序:
screen shot

另外,似乎你可以使用style sheets與任何小部件並更改小部件上的background-image屬性。這與QtDesigner更加集成,因爲您可以在QtDesigner中設置樣式表和圖像。

+0

對不起,無法理解如何使用該筆刷填充窗口中的確切矩形。並在哪裏畫?在'paintEvent'中? – Ockonal 2011-04-25 16:32:01

+0

你只是想用平鋪圖像填滿一個窗口嗎?你想要把圖像放在什麼樣的小部件上? – 2011-04-25 17:01:53

+0

@ dusty-campbell是的,我只需要在平鋪紋理的主窗口填充一些矩形。我不在乎使用什麼幫助小工具。 – Ockonal 2011-04-25 17:04:48