简体   繁体   中英

How to draw tiled image with QT

I'm writing interface with C++/Qt in QtCreator's designer. What element to chose to make as a rect with some background image?

And the second question: how to draw tiled image? I have and image with size (1×50) and I want to render it for the parent width. Any ideas?


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

ui->graphicsView->setBackgroundBrush(mTopMenuBrush);

QBrush: Incorrect use of TexturePattern

If you just want to show an image you can use QImage . To make a background with the image tiled construct a QBrush with the QImage. Then, if you were using QGraphicsScene for example, you could set the bursh as the background brush.

Here is an example which fills the entire main window with the tiled image "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();
}

The resulting app:
屏幕截图

Alternatively, it seems that you could use style sheets with any widget and change the background-image property on the widget. This has more integration with QtDesigner as you can set the style sheet and image in QtDesigner .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM