PyQt 在现有的前面动态添加小部件

PyQt adding widget dynamically in front of existing ones

我想要存档的是创建一个(像素图-)小部件,然后在主小部件前面可见。稍后,这个小部件应该会跟随鼠标。

所以我的主要问题是在按下空格键时动态创建一个小部件,然后在其他小部件前面可见,而不创建单独的 window。

import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt


class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        self.label = QtWidgets.QLabel()
        canvas = QtGui.QPixmap(1200, 800)
        canvas.fill(QtGui.QColor('#ffffff')) # Fill entire canvas.
        self.label.setPixmap(canvas)
        self.setCentralWidget(self.label)

        self.last_x, self.last_y = None, None


    def mouseMoveEvent(self, e):
        if self.last_x is None: # First event.
            self.last_x = e.x()
            self.last_y = e.y()
            return # Ignore the first time.

        painter = QtGui.QPainter(self.label.pixmap())
        painter.drawLine(self.last_x, self.last_y, e.x(), e.y())
        painter.end()
        self.update()

        # Update the origin for next time.
        self.last_x = e.x()
        self.last_y = e.y()

    def mouseReleaseEvent(self, e):
        self.last_x = None
        self.last_y = None

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == Qt.Key_Space:
            block = QtGui.QPixmap(20, 20)
            block.fill(QtGui.QColor('blue'))
            self.image = QtWidgets.QLabel()
            self.image.setPixmap(block)
            self.image.move(20,20)
            # self.image.raise_()
            # self.image.show()

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

如果我在哪里调用图像上的 .show(),将打开带有此小部件的单独 window。但这不是我想要存档的。 _raise 似乎什么都没做。

编辑:我可以使用 QStackedLayout 实现吗?

没有父级的小部件将显示为 window,因此解决方案是将父级传递给它并调用 show() 方法来显示它:

def keyPressEvent(self, QKeyEvent):
    if QKeyEvent.key() == Qt.Key_Space:
        block = QtGui.QPixmap(20, 20)
        block.fill(QtGui.QColor('blue'))
        self.image = QtWidgets.QLabel(self.label)
        self.image.setPixmap(block)
        self.image.move(20,20)
        self.image.show()