alphanumeric
alphanumeric

Reputation: 19339

How to center background image in QWidget

The code below creates a singe QTableView with the jpg image set as background.

I would like this background image to be centered instead of aligned with the left and top edges. How to position the background image at the center?

from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtCore import *

app = QApplication([])
view = QTableView()
view.resize(1000, 600)
bg_image = 'stackoverflow.jpg'
view.setStyleSheet("background-repeat:no-repeat;background-image:url(%s)" % bg_image)
view.show()
app.exec_()

enter image description here

Upvotes: 1

Views: 2375

Answers (1)

eyllanesc
eyllanesc

Reputation: 244093

Set the background-position property to center:

view.setStyleSheet(
    """
    background-repeat: no-repeat;
    background-position: center;
    background-image: url(%s);
    """
    % bg_image
)

Upvotes: 2

Related Questions