2017-03-13 203 views
3

我是PyQt5的新手,我找不到任何有關如何在加載圖像上繪製QPainter的解答(QPixmap(「myPic.png 「))。我試着在paintEvent方法中做它,但它不起作用。如果我想在下面的代碼片段中加載的圖片上繪製一條線,我該如何去做呢?在PyQt5(Python)中繪製圖像頂部

import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 

class Example(QWidget): 
    def __init__(self): 
     super().__init__() 
     self.setGeometry(30, 30, 500, 300) 
     self.initUI() 

    def initUI(self): 
     self.pixmap = QPixmap("myPic.png") 
     lbl = QLabel(self) 
     lbl.setPixmap(self.pixmap) 

     self.show() 

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    ex = Example() 
    sys.exit(app.exec_()) 
+0

你想用水平線顯示圖像,還是想用該改變保存圖像? – eyllanesc

+0

第一個。在像qpainter.drawLine() – Johan

回答

4

使用paintEventQPainter

import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 
from PyQt5.QtCore import * 

class Example(QWidget): 
    def __init__(self): 
     super().__init__() 
     self.setGeometry(30, 30, 500, 300) 

    def paintEvent(self, event): 
     painter = QPainter(self) 
     pixmap = QPixmap("myPic.png") 
     painter.drawPixmap(self.rect(), pixmap) 
     pen = QPen(Qt.red, 3) 
     painter.setPen(pen) 
     painter.drawLine(10, 10, self.rect().width() -10 , 10) 

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

myPic.png

enter image description here

輸出:

enter image description here

+0

圖像頂部顯示行正是我想要的,感謝您的快速回復! – Johan