开发者

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:

How to draw tiled image with QT

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜