【问题标题】:PyQt user logo in center of MDI Area位于 MDI 区域中心的 PyQt 用户徽标
【发布时间】:2020-11-25 17:58:27
【问题描述】:

我一直在研究 PyQt QMainWindow QMdiArea 类。我已经能够根据我的应用程序的需要更改背景颜色。 但是,我无法在窗口中心添加徽标​​。

我尝试过 QBrush,但只是插入完整的徽标QMdiArea。 此外,我尝试过 paintEvent 覆盖的方法,但这似乎不起作用。

请在下面找到我的代码和代码输出的快照:

# Import necessary libraries
import sys

from PyQt5 import QtWidgets, QtGui
from PyQt5.QtGui import QColor, QBrush, QPainter
from PyQt5.QtWidgets import QStyleFactory, QWidget, QMainWindow, QMdiArea


class MDI_Window(QMainWindow, QWidget):
    def __init__(self):
        super().__init__()
        self.centralWidget = QWidget(self)
        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)

        self.window_initialize()
        self.show()

    def window_initialize(self):
        title = 'MDI'
        self.setWindowTitle(title)
        self.setWindowIcon(QtGui.QIcon("Some_Icon.png"))
        self.setMinimumSize(800, 600)

        self.mdi.setBackground(QBrush(QColor(169, 169, 169)))

        self.showMaximized()

    def paintEvent(self, event):
        self.mdi.paintEvent(event)
        self.painter = QPainter(self)
        # For testing logo
        self.painter.drawPixmap(500, 500, 500, 500, QtGui.QPixmap("KDS_Main-Window.png"))


if __name__ == "__main__":
    # Create App with the design
    LMS_App = QtWidgets.QApplication(sys.argv)
    LMS_App.setStyle(QStyleFactory.create('Fusion'))

    a = MDI_Window()
    # Exit application when system is terminated
    sys.exit(LMS_App.exec_())

【问题讨论】:

    标签: python python-3.x image pyqt5 qmdiarea


    【解决方案1】:

    你不能像那样实现paintEvent,主要是因为Qt 必须为正在绘制的特定小部件调用paintEvent。绘制事件必须在小部件中实现。

    最简单的解决方案是对 QMdiArea 进行子类化:

    class MdiArea(QMdiArea):
        def paintEvent(self, event):
            # call the base implementation to draw the default colored background
            super().paintEvent(event)
            # create the painter *on the viewport*
            painter = QPainter(self.viewport())
            painter.drawPixmap(500, 500, 500, 500, QtGui.QPixmap("KDS_Main-Window.png"))
    

    注意:

    1. 你现在应该删除主窗口的paintEvent
    2. 如您所见,在 viewport 上调用了painter:这对于 所有 QAbstractScrollArea 子类是强制性的;
    3. paintEvent 中使用的 QPainter 实例应该设置为实例属性(如您所见,我没有使用self.painter),因为最后必须销毁painter功能,否则您将面临性能和绘图问题;从理论上讲,您可以通过手动调用 painter.end() 来避免这个问题,但是,由于新的 QPainter 实例很可能会很快且非常频繁地重新创建,因此每次将其设置为持久属性确实没有用。

    【讨论】:

    • 非常感谢您的宝贵帮助并详细解释解决方案。将来会牢记这些细节。
    猜你喜欢
    • 1970-01-01
    • 2015-12-27
    • 2012-11-08
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多