1

What I want to archive is to create an (pixmap-)widget that is then visible in front of the main widget. Later on, this widget is supposed to follow the mouse.

So my main problem is to create an widget dynamically when the spacebar is pressed that is then visible in front of the other widgets, without creating a seperate 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_()

If I where to call .show() on the image a seperate window with this widget would be opened. But that is not what I want to archive. _raise doesn't seem to do anything at all.

Edit: can i achive this by using a QStackedLayout?

1 Answer 1

2

A widget that does not have a parent will be shown as a window, so the solution is to pass it a parent and call the show() method to show it:

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.