Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw tiled image with QT

Tags:

c++

image

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

like image 652
Max Frai Avatar asked Oct 27 '25 06:10

Max Frai


1 Answers

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:
screen shot

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.

like image 162
Dusty Campbell Avatar answered Oct 28 '25 20:10

Dusty Campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!