加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 绘制PyQt小部件背景时出现意外消息

发布时间:2020-12-20 11:32:23 所属栏目:Python 来源:网络整理
导读:为什么我收到此消息QPainter :: begin:当我运行此代码时,Painter已在控制台中处于活动状态: from PyQt4.QtGui import * from PyQt4.QtCore import * import sysclass MyRoundWidget(QWidget): def __init__(self,master=None): super(MyRoundWidget,self).
为什么我收到此消息QPainter :: begin:当我运行此代码时,Painter已在控制台中处于活动状态:

from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
import sys


class MyRoundWidget(QWidget):

    def __init__(self,master=None):
        super(MyRoundWidget,self).__init__(master)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle("QLinearGradient Vertical Gradient ")
        self.setAttribute(Qt.WA_TranslucentBackground)        

    def paintEvent(self,ev):
        painter = QPainter(self)
        painter.begin(self)
        gradient = QLinearGradient(QRectF(self.rect()).topLeft(),QRectF(self.rect()).bottomLeft())
        gradient.setColorAt(0.0,Qt.black)
        gradient.setColorAt(0.4,Qt.gray)
        gradient.setColorAt(0.7,Qt.black)
        painter.setBrush(gradient)
        painter.drawRoundedRect(self.rect(),10.0,10.0)
        painter.end()


def main():    
    app     = QApplication(sys.argv)
    widget = MyRoundWidget()    
    widget.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

我的代码有问题吗?

解决方法

def paintEvent(self,ev):
    painter = QPainter(self)
    gradient = QLinearGradient(QRectF(self.rect()).topLeft(),QRectF(self.rect()).bottomLeft())
    gradient.setColorAt(0.0,Qt.black)
    gradient.setColorAt(0.4,Qt.gray)
    gradient.setColorAt(0.7,Qt.black)
    painter.setBrush(gradient)
    painter.drawRoundedRect(self.rect(),10.0)

删除painter.begin(self)和painter.end().

根据Qt docs:

Note that most of the time,you can use one of the constructors
instead of begin(),and that end() is automatically done at
destruction.

Warning: A paint device can only be painted by one painter at a time.

所以,如果你使用painter = QPainter(self)来构造一个画家,那么就没有必要调用begin()和end().这将是重复的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读