簡體   English   中英

為什么我放大Windows的尺寸時,筆在pyqt5的鼠標坐標點上不作畫

[英]why When I large the size of Windows, the pen does not painting at the coordinate point of the mouse in pyqt5

你好所有親愛的教授。 我用筆寫了以下程序,當window的大小為900x600時,筆在鼠標坐標點上寫這是正確的,但是當我把程序放大window時。 筆寫得離鼠標cursor點比較遠,一般? 當我將像素圖添加到標簽時,為什么我們不能在鼠標單擊點繪制?

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(900, 600)
        canvas.fill(Qt.white)
        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


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

QLabel 的alignment()屬性文檔對此進行了解釋:

默認情況下,label 的內容是左對齊和垂直居中的。

在任何情況下,即使忽略 alignment,任何基於鼠標的繪圖都應該在小部件坐標中完成,而您嘗試使用parent的坐標進行繪制。

更好的方法應該使用 QLabel 的子類,使用以下實現:

class MyLabel(QtWidgets.QLabel):
    def __init__(self):
        super().__init__()
        canvas = QtGui.QPixmap(900, 600)
        canvas.fill(Qt.white)
        self.setPixmap(canvas)
        self.last_x, self.last_y = None, None
        self.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)

    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.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

class MainWindow(QtWidgets.QMainWindow):

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

        self.label = MyLabel()
        self.setCentralWidget(self.label)

另外,請參閱此相關問題: Mouse position on mouse move event is set on parent 而不是 child

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM