PyQt4: Marquesina python

De Cacauet Wiki
Salta a la navegació Salta a la cerca

Ale, aquí teniu més codi d'una marquesina o "missatge rodant". Val a dir que podeu millorar l'aspecte de tot plegat...

#!/usr/bin/python
# -*- coding: utf-8 -*-


from PyQt4 import QtCore,QtGui
import sys

class Pantalla(QtGui.QWidget):
    color = QtGui.QColor(255,255,255)
    frase = ""
    posx = 0
    posy = 0
    vel = -5
    
    def __init__(self):
        super(Pantalla,self).__init__()
        
    def actualitza_pos(self):
        self.posx = self.posx + self.vel
        self.posy = self.height()/2
        # control limits
        longitud = len(self.frase)*10
        
        if self.posx <= -longitud:
            self.posx = self.width()
        elif self.posx >= self.width():
            self.posx = -longitud+1
        
    def paintEvent(self,e):
        qp = QtGui.QPainter()
        qp.begin(self)

        self.actualitza_pos()
        
        qp.setBrush( self.color )
        qp.drawRect( 0, 0, self.width()-1, self.height()-1 )
        qp.drawText( self.posx, self.posy , self.frase )
        
        qp.end()

class Marquesina(QtGui.QWidget):
    def __init__(self):
        super(Marquesina,self).__init__()
        self.initUI()
    
    def initUI(self):
        # elements
        self.set = QtGui.QPushButton("Set", self)
        self.textview = QtGui.QLineEdit("posa text aqui...", self)
        self.slider = QtGui.QSlider(QtCore.Qt.Vertical, self)

        self.pantalla = Pantalla()
        
        # connexions SIGNALS i SLOTS
        self.set.clicked.connect( self.canvia_text )
        self.textview.returnPressed.connect( self.canvia_text )
        self.slider.valueChanged.connect( self.canvia_vel )
        
        self.grid = QtGui.QGridLayout()
        self.grid.addWidget(self.set,0,0)
        self.grid.addWidget(self.slider,1,0)
        self.grid.addWidget(self.textview,0,1)
        self.grid.addWidget(self.pantalla,1,1)
        
        self.setLayout( self.grid )
        
        self.setGeometry(150,150,700,600)
        self.show()
        
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect( self.pantalla.repaint )
        self.timer.setInterval(50)
        self.timer.start()
        
        # veiem text des del principi dels temps
        self.canvia_text()
        self.setFocus()

    def canvia_text(self):
        self.pantalla.frase = self.textview.text()
        self.setFocus()
    
    def canvia_vel(self):
        self.pantalla.vel = self.sender().value()
        self.setFocus()

    def keyPressEvent(self,e):
        if e.key() == QtCore.Qt.Key_Left:
            self.pantalla.vel = -abs(self.pantalla.vel)
        elif e.key() == QtCore.Qt.Key_Right:
            self.pantalla.vel = abs(self.pantalla.vel)
        

app = QtGui.QApplication([])
m = Marquesina()
sys.exit( app.exec_() )