2017-07-10 48 views
-1

我是Pyqt的新手,我正在嘗試創建一個在我們給出像素位置時在圖像上打印一個圓(使用QPainter)的UI(QLabel)。對於測試,我使用鼠標跟蹤事件,但我想我有圖像或標籤調整大小的問題。下面從我實現圖像:如何在PyQt5上正確設置Pixmap的縮放比例?

結果:

看看指針和圓的位置。這是我想要解決的。

下面你可以看到代碼(我使用PIL(加載圖像)和PyQt5):

...  

    self.image = Image.open("Images/Quart_top_View_draw.jpg") 
    self.MainWindow.TennisCourtImage.setMouseTracking(True) 
    self.MainWindow.TennisCourtImage.mouseMoveEvent = self.get_mouse_pos 

def get_mouse_pos(self,event):  
    x = event.pos().x() 
    y = event.pos().y() 
    print("Position: ", x,y) 

    img = self.image 
    width, height = img.size 
    print("Image Size: ", width, height) 

    img = ImageQt(img) 
    pixmap_image = QtGui.QPixmap.fromImage(img) 

    self.painterInstance = QtGui.QPainter(pixmap_image) 
    self.painterInstance.setPen(QPen(Qt.red, 15, Qt.SolidLine)) 
    self.painterInstance.drawEllipse(x,y,15,15) 
    self.painterInstance.end() 

    myScaledPixmap = pixmap_image.scaled(self.MainWindow.TennisCourtImage.size(), Qt.KeepAspectRatio) 
    self.MainWindow.TennisCourtImage.setPixmap(myScaledPixmap) 

    ... 

有人可以幫助我,好嗎?

問候,

百利:d

+0

爲什麼使用PIL? – eyllanesc

+0

你的問題是什麼?你想得到什麼? – eyllanesc

+0

PIL沒有必要。我可以改變我在哪裏使用PIL的線\t \t pixmap_image = QtGui.QPixmap(「Images/Quart_top_View_draw.jpg」)。我需要的是繪製我的指針所在的圓圈。 –

回答

0

而不是使用QLabel,你可以創建一個執行此任務自定義部件如下表所示:

class Stadium(QWidget): 
    def __init__(self, pixmap, parent=None): 
     QWidget.__init__(self, parent=parent) 
     self.pixmap = pixmap 
     self.pos = None 
     self.setMouseTracking(True) 

    def paintEvent(self, event): 
     painter = QPainter(self) 
     painter.drawPixmap(self.rect(), self.pixmap) 
     painter.setPen(QPen(Qt.red, 15, Qt.SolidLine)) 
     if self.pos: 
      painter.drawEllipse(self.pos, 15, 15) 

    def mouseMoveEvent(self, event): 
     self.pos = event.pos() 
     self.update() 

例子:

class Widget(QWidget): 
    def __init__(self, parent=None): 
     QWidget.__init__(self, parent=parent) 
     self.setLayout(QVBoxLayout()) 
     label = Stadium(QPixmap("475776182987.png")) 
     self.layout().addWidget(label) 
     self.resize(640, 480) 

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    w = Widget() 
    w.show() 
    sys.exit(app.exec_()) 

屏幕截圖:

enter image description here

+0

嗨eyllanesc。你的回答很好。我在我的mainWindow中添加QWidget。非常感謝。 –

+0

你好@eyllanesc。可以保持圖像尺寸比例?如果是的話,你能幫我嗎? –

+0

如果標籤的關係與您想要顯示的圖像的關係不匹配? – eyllanesc

相關問題