A
A
Alexey Poloz2017-10-08 19:47:37
Python
Alexey Poloz, 2017-10-08 19:47:37

Python PyQt5 How to make window background?

The code:

import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QHBoxLayout, QVBoxLayout, QDesktopWidget, QLabel
from PyQt5.QtGui import QPixmap

class first(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
#Считывание контента
        with open('set.txt', 'r') as file:
            win = file.read()

        try:
            with open(win + '.txt', 'r') as file:
                self.x = file.read().split('\n')
        except:
            with open('main.txt', 'r') as file:
                self.x = file.read().split('\n')

        #print(self.x)

        self.b = []
        for i in self.x:
#Кнопки
            if i[:7] == '@button':
                self.b.append(QPushButton(i[8:-1], self))
                self.b[len(self.b) - 1].clicked.connect(self.click)
#Изображения
            elif i[:6] == '@image':
                lbl = QLabel(self)
                lbl.setPixmap(QPixmap(i[7:-1]))
                self.b.append(lbl)
#Текст
            else:
                lbl = QLabel(i)
                self.b.append(lbl)

#Разметка страницы
        hbox = QVBoxLayout()
        for i in range(len(self.b)):
            hbox.addWidget(self.b[i])
        vbox = QHBoxLayout()
        vbox.addLayout(hbox)
        self.setLayout(vbox)

#Параметры окна
        q = QDesktopWidget().availableGeometry()
        self.setGeometry(0, 0, q.width(), q.height())
        self.setWindowTitle('Goncharov Lox')
        self.show()

...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-10-08
@kosyachniy

You can tile a window like this:

class MainWindow(QWidget):
    window_height = 600
    window_width = 600

    def __init__(self):
       super(QWidget, self).__init__()
       self.setGeometry(100, 100, self.window_height, self.window_width)

       oImage = QImage("image.jpg")
       sImage = oImage.scaled(QSize(self.window_height, self.window_width))
       palette = QPalette()
       palette.setBrush(QPalette.Window, QBrush(sImage))
       self.setPalette(palette)

Scaling the background while maintaining proportions is a little more difficult:
class MainWindow(QWidget):
    def __init__(self):
       super(QWidget, self).__init__()

    def resizeEvent(self, event):
        palette = QPalette()
        img = QImage('image.jpg')
        scaled = img.scaled(self.size(), Qt.KeepAspectRatioByExpanding, transformMode = Qt.SmoothTransformation)
        palette.setBrush(QPalette.Window, QBrush(scaled))
        self.setPalette(palette)

And if you don't need to keep the proportions, then instead of KeepAspectRatioByExpanding, you need to pass IgnoreAspectRatio.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question