简体   繁体   中英

How to get correct mouse position in Python Qt5?

I'm trying to get correct mouse position in mouseReleaseEvent, but the mouse position I got is wrong.The ev.position() is not relative position on Widget.

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.pad = ChessPad()
        w = QtWidgets.QWidget()
        l = QtWidgets.QVBoxLayout()
        w.setLayout(l)
        l.addWidget(self.pad)
        self.setCentralWidget(w)


class ChessPad(QtWidgets.QLabel):
    def __init__(self):
        super().__init__()

        pad = QtGui.QPixmap(700, 300)
        pad.fill(Qt.white)
        self.setPixmap(pad)        

    def mouseReleaseEvent(self, ev):
        
        ev_x = ev.position().x()
        ev_y = ev.position().y()
        print(ev_x, ev_y)

I get a workaround to solve this issue. I add a label in vboxlayout, the ev.position() will return relative position.

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.pad = ChessPad()

        label = QtWidgets.QLabel("Chess Pad")
        w = QtWidgets.QWidget()
        l = QtWidgets.QVBoxLayout()
        w.setLayout(l)
        l.addWidget(label)
        l.addWidget(self.pad)
        self.setCentralWidget(w)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM