Как изменить цвет окна pyqt5

Pyqt5 3 способа установить фон окна, Русские Блоги, лучший сайт для обмена техническими статьями программиста.

Контент взят из «PyQT5 Rapid Development and Actual Combat»
Фон окна в основном включает: цвет фона и фоновое изображение.

1. Используйте QSS, чтобы установить фон окна.

Если вы хотите установить фоновое изображение или изображение для элемента управления, вы можете использовать setIcon () или setPixmap () для завершения.

1.1 Используйте setStyleSheet (), чтобы установить фоновое изображение окна

# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys

app = QApplication(sys.argv)
window = QMainWindow()
window.setObjectName("MainWindow")
window.setStyleSheet("#MainWindow{border-image:url(background.jpg)}") # Используйте здесь относительный путь, вы также можете использовать абсолютный путь
window.show()
sys.exit(app.exec_())

Запускаем скриншот:

1.2 Используйте setStyleSheet (), чтобы установить цвет фона окна

# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys

app = QApplication(sys.argv)
window = QMainWindow()
window.setObjectName("MainWindow")
window.setStyleSheet("#MainWindow{background-color:green}")
window.show()
sys.exit(app.exec_())

Запускаем скриншот:

2. Используйте QPalette (палитру), чтобы установить фон окна.

2.1 Используйте QPalette, чтобы установить цвет фона окна

# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPalette
from PyQt5.QtCore import Qt
import sys

app = QApplication(sys.argv)
window = QMainWindow()
palette = QPalette()
palette.setColor(QPalette.Background, Qt.red)
window.setPalette(palette)
window.show()
sys.exit(app.exec_())

Запускаем скриншот:

2.2 Используйте QPalette для установки фонового изображения окна

Если размер фонового изображения больше, чем размер окна, изображение будет занимать окно мозаикой; в противном случае будет загружено несколько фоновых изображений. Вы можете настроить разрешение изображения или размер окна, чтобы добиться желаемого эффекта.

# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPalette, QBrush, QPixmap
import sys

app = QApplication(sys.argv)
window = QMainWindow()
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("./background.jpg")))
window.setPalette(palette)
window.show()
sys.exit(app.exec_())

Запускаем скриншот:

3. Используйте paintEvent, чтобы установить фон окна.

3.1 Используйте paintEvent, чтобы установить цвет фона окна

# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication,QWidget
from PyQt5.QtGui import QPalette, QBrush, QPixmap, QPainter
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
import sys


class Winform(QWidget):
    def __init__(self, parent=None):
        super(Winform, self).__init__(parent)
        self.setWindowTitle("Используйте QPaintEvent, чтобы установить цвет фона окна")

    def paintEvent(self, a0: QtGui.QPaintEvent) -> None:
        painter = QPainter(self)
        painter.setBrush(Qt.red)
        painter.drawRect(self.rect())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Winform()
    window.show()
    sys.exit(app.exec_())

Запускаем скриншот:

3.1 Используйте paintEvent для установки фонового изображения окна

# -*- coding=utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QApplication,QWidget
from PyQt5.QtGui import QPalette, QBrush, QPixmap, QPainter
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
import sys


class Winform(QWidget):
    def __init__(self, parent=None):
        super(Winform, self).__init__(parent)
        self.setWindowTitle("Используйте QPaintEvent, чтобы установить фоновое изображение окна")

    def paintEvent(self, a0: QtGui.QPaintEvent) -> None:
        painter = QPainter(self)
        pixmap = QPixmap("./background.jpg")
        painter.drawPixmap(self.rect(), pixmap)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Winform()
    window.show()
    sys.exit(app.exec_())

Запускаем скриншот:

Today, I tried to developed my go board application in PyQt5 while I was running the experiment. I tried many different window function in the process, so I put it into a note, so that I can read it in future.

Today should be divided into four parts: set the window title, set the Icon, set the background, hide the window title …… I feel that the last item almost erased all the previous works XDD

And then, let’s start it!


Set window title

First, this should be the look we made when we opened Qt Designer.

If we don’t do anything or add any components, save the UI file and turn it into a Python file.

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'QMainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(873, 705)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 873, 25))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

We can see, this UI file we generated this time is very naive. We just only defined components MainWindow, Menubar, Statusbar ……

And we should be create a new Python file to inherit this interface file.

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui
from QMainWindow import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Output:

We can see, nothing in this figure.

If you want to set the name of the program above, we can modify it with a simple program.

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui
from QMainWindow import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MainWindow Title
        self.setWindowTitle('QIcon Test!!')


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Output:

We change the window title name!

Because the new class we defined is inherited from the original MainWindow class, we only need to call our own setWindowTitle() to modify the title we want.

We can also define the status bar below StatusBar.

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui
from QMainWindow import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MainWindow Title
        self.setWindowTitle('QIcon Test!!')

        # StatusBar
        self.statusBar().showMessage('TEST Again!!!')


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Output:

The text we set is also displayed in the lower left corner.

How is it possible to set it up very easily?


Set Icon

Next, we set the window icon.

Basically we only need one line of instructions.

self.setWindowIcon(QtGui.QIcon('pic/Python_PyQt5.png'))
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui
from QMainWindow import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MainWindow Title
        self.setWindowTitle('QIcon Test!!')

        # StatusBar
        self.statusBar().showMessage('TEST Again!!!')

        # Set Window Icon
        self.setWindowIcon(QtGui.QIcon('pic/Python_PyQt5.png'))


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Output:

We can compare the above figures. Do you find that the Icon (upper left corner) has changed the icon?

Of course, I feel a little humble, a little embarrassed Hahahahaha.

The original picture is like this:

If fact, It’s the picture I put at the beginning.


Set background

Then, let’s come to the background that I have been tossing for a long time! In fact, the background is unexpectedly set, but we need to introduce two new components: QPalette, QPixmap.

As the name suggests, QPixmap is a pixmap, we can read the image in. And QPalette is the palette, we can place any color on it.

In here I will pass the image read by QPixmap to QPalette, and then pass the QPalette object to our MainWindow.

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui
from QMainWindow import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MainWindow Title
        self.setWindowTitle('QIcon Test!!')

        # StatusBar
        self.statusBar().showMessage('TEST Again!!!')

        # Set Window Icon
        self.setWindowIcon(QtGui.QIcon('pic/Python_PyQt5.png'))

        # Pixmap
        image = QtGui.QPixmap()
        image.load('pic/Python_PyQt5.png')
        image = image.scaled(self.width(), self.height())

        # Palette
        palette = QtGui.QPalette()
        palette.setBrush(self.backgroundRole(), QtGui.QBrush(image))
        self.setPalette(palette)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Output:

Among:

image.scaled(self.width(), self.height())

This line of instructions I made the size of the picture, to avoid the picture can not be placed up to the window, of course you will see, maybe the picture has little distorted.

By the way, if you want to set a background color instead of placing a picture:

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui
from QMainWindow import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MainWindow Title
        self.setWindowTitle('QIcon Test!!')

        # StatusBar
        self.statusBar().showMessage('TEST Again!!!')

        # Set Window Icon
        self.setWindowIcon(QtGui.QIcon('pic/Python_PyQt5.png'))

        # Pixmap
        # image = QtGui.QPixmap()
        # image.load('pic/Python_PyQt5.png')
        # image = image.scaled(self.width(), self.height())
        #
        # Palette
        palette = QtGui.QPalette()
        palette.setBrush(self.backgroundRole(), QtGui.QColor(150, 200, 100))
        self.setPalette(palette)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Output:

Like this!

We change the object passed in palette.setBrush() to QtGui.QColor(), and then fill in the RGB three primary colors, you can color the background.


Hide the window title

Yes! finally come to the part to waste all of our works!

We can easily hide our window title with just one instruction:

# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets, QtGui, QtCore
from QMainWindow import Ui_MainWindow
import sys


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # MainWindow Title
        self.setWindowTitle('QIcon Test!!')

        # StatusBar
        self.statusBar().showMessage('TEST Again!!!')

        # Set Window Icon
        self.setWindowIcon(QtGui.QIcon('pic/Python_PyQt5.png'))

        # Pixmap
        image = QtGui.QPixmap()
        image.load('pic/Python_PyQt5.png')
        image = image.scaled(self.width(), self.height())

        # Palette
        palette = QtGui.QPalette()
        palette.setBrush(self.backgroundRole(), QtGui.QBrush(image))
        self.setPalette(palette)

        # Hide Window Title
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Output:

How is it? Did you really get rid of the annoying frame? If we optimize for the corners, a fashion interface will be made!

Maybe after the completion of my notation program, I will try to optimize the interface again, and then record the notes!


References

  • https://www.riverbankcomputing.com/static/Docs/PyQt5/index.html?highlight=qicon

Read More

  • [PyQt5] Tutorial(1) Install PyQt5 and print «Hello World!»
  • [PyQt5] Tutorial(2) QLabel, QLineEdit, QPushButton
  • [PyQt5] Tutorial(3) QMainWindow, QIcon, QPixmap, QPalette
  • [PyQt5] Tutorial(4) Menu, Toolbar
  • [PyQt5] Tutorial(5) ProgressBar, HorizontalSlider, QDial
  • [PyQt5] Tutorial(6) comboBox、BoxLayout
  • [PyQt5] Tutorial(7) hide, show, auto fit window size
  • [PyQt5] Tutorial(8) QTimer, QlcdNumber
  • [PyQt5] Tutorial(9) Use QCalendar to create a calendar component
  • [PyQt5] Tutorial(10) Use keyboard to enter command and listen mouse clicked
  • [PyQt5] Tutorial(11) Use QColorDialog to let user select color

Привет, Хабр! Сегодня я вас хочу научить делать интерфейс на Python 3&PyQt5.

Установка PyQt5

Для того, чтобы установить PyQt5 в Windows или MacOS, откройте Командную строку или Терминал и введите:

pip3 install PyQt5

Для Linux, откройте Терминал и введите:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python3-pyqt5

Hello, World!

А сейчас сделаем Hello World приложение. Создайте файл Python, откройте его и введите такой код:

from PyQt5.QtWidgets import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('Hello, world!!!', self)
        self.lbl.move(30, 30)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Когда вы запустите, должна получится примерно такая картина:

Окно Hello, world на Ubuntu

Окно Hello, world на Ubuntu

Меняем шрифт надписи

А теперь поменяем шрифт надписи. Теперь код станет таким:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('Hello, world!!!', self)
        self.lbl.move(30, 30)
        self.font = QFont() # создаём объект шрифта
        self.font.setFamily("Rubik") # название шрифта
        self.font.setPointSize(12) # размер шрифта
        self.font.setUnderline(True) # подчёркивание
        self.lbl.setFont(self.font) # задаём шрифт метке


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Пример рассчитан на то, что у вас уже установлен шрифт Rubik от Google Fonts. Если нет, его всегда можно скачать отсюда.

Более продвинутая разметка с XHTML

А теперь добавим XHTML. Например, так:

from PyQt5.QtWidgets import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('<i>Hello</i>, <b>world</b>!!! <s><b>123</b></s>', self)
        self.lbl.move(30, 30)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Те, кто хотя бы немного знают XHTML, заметят, что надпись Hello сделана курсивом, слово world — жирным, а 123 — и вычеркнуто, и жирное.

Шпаргалка по XHTML

<b>123</b>

Жирный текст

<i>123</i>

Курив

<u>123</u>

Подчёркивание

<s>123</s>

Вычёркивание

<code>123</code>

Код (моноширным шрифтом)

<sup>123</sup>

Надстрочный текст

<sub>123</sub>

Подстрочный текст

<span style=»font-size:16pt;»>123</span>

Размер текста 16 пунктов

<span style=»color:#cc0000;»>123</span>

Красный текст

<span style=» background-color:#00ff00;»>123</span>

Текст на ярко-зелёном фоне.

<span align=»center»>123</span>

Выравнивание по центру

Кстати, я знаю такой конструктор HTML. Лично мне он по душе. Только сложно вставлять свои тэги.

Больше надписей!

А теперь сделаем 2 надписи:

from PyQt5.QtWidgets import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('<i>Hello</i>, <b>world</b>!!!', self)
        self.lbl.move(30, 30)
        self.lbl2 = QLabel('<u>Ещё одна метка</u>', self)
        self.lbl2.move(50, 50)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

На вторую я тоже добавил форматирование (подчёркивание), а у первой убрал 123.

Окно без resize()

Все предыдущие примеры использовали такую конструкцию:

self.resize(200, 200)

Но без этой конструкции можно обойтись, так как виджеты будут сами себе расчищать место.

Подсказки

Ко всем виджетам можно добавить подсказку. Например (привожу только важную для понимания часть кода):

self.lbl.setToolTip('This is a <b>QLabel</b>')

Эпилог

Вот и всё. В следующей части я постараюсь описать кнопки, меню и события.

До новых встреч!

Понравилась статья? Поделить с друзьями:
  • Как изменить цвет молнии
  • Как изменить цвет меда
  • Как изменить цвет линии корал
  • Как изменить цвет корабля варфрейм
  • Как изменить цвет кожи магия