2017-09-04 58 views
1

QPainter的我不明白如何使QPainter的()画一个QLabel里面,这里是我跟会工作代码:里面怎么QLabel

import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import QPainter, QColor, QBrush 

class Labella(QLabel): 

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

     lb = QLabel('text', parent) 
     lb.setStyleSheet('QFrame {background-color:grey;}') 
     lb.resize(200, 200) 

     qp = QPainter(lb) 
     qp.begin(lb); 

     qp.setBrush(QColor(200, 0, 0)) 
     qp.drawRect(0,0,20,20); 
     qp.end(); 


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

    def drawRectangles(self, qp): 

     col = QColor(0, 0, 0) 
     col.setNamedColor('#040404') 
     qp.setPen(col) 

     qp.setBrush(QColor(200, 0, 0)) 
     qp.drawRect(10, 15, 200, 60) 


class Example(QWidget): 

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

     lb = Labella(self) 

     self.setGeometry(300, 300, 350, 300) 
     self.setWindowTitle('Colours') 
     self.show() 


if __name__ == '__main__': 

    app = QApplication(sys.argv) 
    ex = Example() 
    sys.exit(app.exec_()) 

我只能找到的例子在C++一样对于Qt文档,如果不在这里,请告诉我应该在哪里找到信息。

回答

2

documentation建议在paintEvent内使用QPainter

使用构造类似下面的方法paintEvent内,无需调用begin()end()

(你的类Labella只是错过参数初始化父)

的方法save()restore()能可以方便地存储QPainter的标准配置,允许在恢复设置之前画出不同的东西。

import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import QPainter, QColor, QBrush 

class Labella(QLabel): 

    def __init__(self, parent): 
     super().__init__(parent=parent) 

     self.setStyleSheet('QFrame {background-color:grey;}') 
     self.resize(200, 200) 

    def paintEvent(self, e): 
     qp = QPainter(self) 
     self.drawRectangles(qp) 
     qp.setBrush(QColor(200, 0, 0)) 
     qp.drawRect(0,0,20,20) 

    def drawRectangles(self, qp):  
     qp.setBrush(QColor(255, 0, 0, 100)) 
     qp.save() # save the QPainter config 

     qp.drawRect(10, 15, 20, 20) 

     qp.setBrush(QColor(0, 0, 255, 100)) 
     qp.drawRect(50, 15, 20, 20) 

     qp.restore() # restore the QPainter config    
     qp.drawRect(100, 15, 20, 20) 

class Example(QWidget): 

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

     lb = Labella(self) 

     self.setGeometry(300, 300, 350, 300) 
     self.setWindowTitle('Colours') 
     self.show() 

if __name__ == '__main__': 

    app = QApplication(sys.argv) 
    ex = Example() 
    sys.exit(app.exec_()) 
+0

谢谢,但它不可能使setText()与此设置一起使用吗?当画家在 – user3755529

+1

@ user3755529上时,似乎没有文字出现在标签中您是对的,抱歉,我没有首先理解您的问题的这一部分,我正在深入解释这种行为。为了重绘标签的背景,您的主要目标是什么? – PRMoureu

+0

我有一个QLabel中的HTML表子集(将有许多标签在QVBoxLayout中布局)。在表格下面,我想添加一个画布,在那里我会画一个指示我们处于QLabel识别的金融工具的52周​​价格范围内的条形图。 – user3755529

相关问题