首页 > 代码库 > MyWidget【简单自制控件】

MyWidget【简单自制控件】

#coding=gbk

from PyQt4 import QtGui,QtCore

import random

class MyWidget(QtGui.QWidget):

    def __init__(self,parent=None):

        if parent is None:

            self.app=QtGui.QApplication([])

        super(MyWidget,self).__init__(parent)

        self.setToolTip(‘双击控件改变线条颜色‘.decode(‘gbk‘))

        if parent is None:

            self.show()

            self.app.exec_()

    def paintEvent(self,event):

        colors=[QtCore.Qt.blue,QtCore.Qt.black,QtCore.Qt.red,

                QtCore.Qt.green,QtCore.Qt.darkRed,QtCore.Qt.yellow]

        p=QtGui.QPainter(self)

        p.setPen(QtGui.QColor(colors[random.randint(0,5)]))

        p.drawLine(0,0,self.width(),self.height())

        p.save()

    def mouseDoubleClickEvent(self,event):

        self.repaint()

 

class TestMyWidget(QtGui.QWidget):

    def __init__(self,parent=None):

        self.app=QtGui.QApplication([])

        super(TestMyWidget,self).__init__(parent)

        self.setGeometry(200,300,200,300)

        self.setWindowTitle(‘自制控件试验‘.decode(‘gbk‘))

        layv=QtGui.QVBoxLayout()

        self.setLayout(layv)

        gp=QtGui.QGroupBox()

        layv.addWidget(gp)

        laygp=QtGui.QGridLayout()

        gp.setLayout(laygp)

        mw=MyWidget(gp)

        laygp.addWidget(mw)

        btn=QtGui.QPushButton(‘Ok‘)

        btn.clicked.connect(self.close)

        layv.addWidget(btn)

        self.show()

        self.app.exec_()

 

if __name__==‘__main__‘:

    TestMyWidget()