簡體   English   中英

通過鼠標事件PyQt在PyQt窗口中創建一行

[英]Create a line in PyQt Window by Mouse Events PyQt

我正在嘗試創建一個場景,我需要從mousePressEvent位置繪制直到最新的鼠標moveposition位置,這意味着我需要從mousePressEvent調用paintEvent ,這可能嗎?

所以場景是這樣的:

1)使用paintEvent繪制2個黑色圓圈

2)鼠標按下事件等待事件並按下發生,我想將圓圈的顏色更改為綠色,是否可能?

import sys, random
from PyQt4 import QtGui, QtCore

class P(QtGui.QWidget):

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

        self.initUI()

    def initUI(self):
        q=self.frameGeometry()
        cp=QtGui.QDesktopWidget().availableGeometry().center()
        q.moveCenter(cp)
        self.setFixedSize(300,300)
        self.setWindowTitle('Points')
        self.show()

    def mousePressEvent(self, QMouseEvent):
        cursor =QtGui.QCursor(self)
        position = QMouseEvent.pos()
        xpos = QMouseEvent.x()
        ypos = QMouseEvent.y()

        #Trial ??????
        q = QtGui.QPainter()
        q.drawLine(30,30,90,90)

        print QMouseEvent.pos()

    def mouseReleaseEvent(self, QMouseEvent):
        cursor =QtGui.QCursor()
        print cursor.pos()

    def paintEvent(self,e):
        qp = QtGui.QPainter()
        qp.begin(self)

        E1 = qp.drawEllipse(30,30,20,20)
        E2 = qp.drawEllipse(30,130,20,20)

def main():

    app = QtGui.QApplication(sys.argv)
    ex = P()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

簡單來說,我需要知道我們可以從另一個事件中調用一個事件,即從鼠標按下事件中的Paint事件嗎?

paintEvent處理程序中完成所有繪制是一個更好的主意。

您應該使用鼠標事件處理程序來處理數據集合(起始點,長度等),然后在paintEvent進行實際重新繪制。

一旦在鼠標事件處理程序中收集了新數據,就可以通過調用update函數告訴QWidget需要重新繪制它。 這將調度將在程序返回事件循環時執行的繪制事件。

暫無
暫無

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

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