473,785 Members | 2,435 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PyQt - clear widget for redraw


I want to draw some lines on a widget.
This works ok, but when I want to redraw, the old lines are still there.

How do I clear or refresh the widget, so I can draw a new set of lines?

Code snip below.

TIA

Peter
-------------------------
def paintLines(self , e):
p = QPainter(e)
mar = e.width()/100 # margin
vsp = 2 # vertical spacing
hrz = (e.width() - 2*mar)/100 # horizontal scalar
for i in range(100):
p.drawLine(mar, mar+vsp*i,hrz*( l1[i]+1),mar+vsp*i)
-------------------------

Jul 18 '05 #1
10 11716
Peter wrote:

I want to draw some lines on a widget.
This works ok, but when I want to redraw, the old lines are still there.

How do I clear or refresh the widget, so I can draw a new set of lines?


Call erase on your widget. Or redraw a rectangle yourself.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
Diez B. Roggisch wrote:

Call erase on your widget. Or redraw a rectangle yourself.


Thanks, that works fine.
I just started using pyqt yesterday, and having trouble finding a reference
- most Qt stuff is written for c++.

Peter

Jul 18 '05 #3
Jim
Peter wrote:
Diez B. Roggisch wrote:

Call erase on your widget. Or redraw a rectangle yourself.


Thanks, that works fine.
I just started using pyqt yesterday, and having trouble finding a
reference - most Qt stuff is written for c++.

Peter


Boudewijn Rempt's book _GUI Programming with Python: QT Edition_
might be helpful. It's available online at:

http://www.opendocspublishing.com/pyqt/

You can also post your questions at:
PyKDE mailing list Py***@mats.imk. fraunhofer.de

sign up for the list at:
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde

There's also a PyQt wiki at:
http://www.diotavelli.net/PyQtWiki
(it's fairly new and a little light on content, but there's already some
good stuff there).
Jim

Jul 18 '05 #4
Peter wrote:
Thanks, that works fine.
I just started using pyqt yesterday, and having trouble finding a
reference - most Qt stuff is written for c++.


The neat thing on pyqt is that usually you can directly translate c++
examples to python. So there is no need to have a separate documentation
and other resources. The erase I looked up in the qt standard
documentation.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #5
Diez B. Roggisch wrote:
Peter wrote:
Thanks, that works fine.
I just started using pyqt yesterday, and having trouble finding a
reference - most Qt stuff is written for c++.

The neat thing on pyqt is that usually you can directly translate c++
examples to python. So there is no need to have a separate documentation
and other resources. The erase I looked up in the qt standard
documentation.


Thanks
(and thanks to Jim for his response, too)

What I'm drawing is a series of lines (like a horizontal bar chart) and it
is updated several times a second. The problem is that it goes too fast.
I tried the time.sleep() function, but then it doesn't draw properly. It
seems to draw only part of the chart each time, and flickers.

Is there some way to make the display smoother?

TIA

Peter

Jul 18 '05 #6
> What I'm drawing is a series of lines (like a horizontal bar chart) and it
is updated several times a second. The problem is that it goes too fast.
I tried the time.sleep() function, but then it doesn't draw properly. It
seems to draw only part of the chart each time, and flickers.


Usually there is no "to fast" in graphics - so I've got to admit I'm not
sure what you are talking about.

Where does the data to draw come from, and how fast is it actually coming? A
flickering sensation usually stems from the redrawing done so fast it
interfers with the vertical retrace.

Maybe it helps to put your sleep not in the drawing code, but between the
arrival of different data sets to draw, thus limiting the redraws to an
amount of lets say 10/s.

If you'd fill us in with some more details, the suggestions might be better.
And I think it would be worth asking these qustions on the PyKDE list Jim
has mentioned - I'm also there :)

--
Regards,

Diez B. Roggisch
Jul 18 '05 #7
Diez B. Roggisch wrote:
Maybe it helps to put your sleep not in the drawing code, but between the
arrival of different data sets to draw, thus limiting the redraws to an
amount of lets say 10/s.
Yes - tried that, but gives incomplete draw / flicker.
If you'd fill us in with some more details, the suggestions might be
better. And I think it would be worth asking these qustions on the PyKDE
list Jim has mentioned - I'm also there :)


More details:
the idea is to provide a graphics demo of sort algorithms for my 13 year old
son. A number of lines of differring lengths are shown on the screen, and
you can watch as these are sorted, step by step. So you can see the
difference between bubble sort, ripple sort, etc.
Code copied below.
Improving the smoothness of the display is the main thing I'm after.
Also, how can I write the counters to the form? It uses the LCD widget now,
but there must be another way.

TIA

Peter

-- sort1.py ---
#!/usr/bin/python
#
# demo of sort algorithms, using PyQt

import sys, random, time
from qt import *

from frmtest import frmTest

class dlgForm(frmTest ):

def __init__(self, parent=None):
frmTest.__init_ _(self, parent)
self.connect(se lf.cmdQuit, SIGNAL("clicked ()"),self,
SLOT("close()") )
self.connect(se lf.cmd2, SIGNAL("clicked ()"), self.reshuffle)
self.connect(se lf.cmdSort, SIGNAL("clicked ()"), self.sort1)
self.connect(se lf.cmdBubble, SIGNAL("clicked ()"), self.bubble)
self.connect(se lf.cmdRipple, SIGNAL("clicked ()"), self.ripple)
self.connect(se lf.cmdShell, SIGNAL("clicked ()"), self.shells)
self.refresh()

def reshuffle(self) :
global cComp, cSwap, b1, b2, r1, r2
cComp, cSwap, b1, b2 = [0,0,0,len(l1)]
random.shuffle( l1)
self.refresh()

def sort1(self):
global cComp, cSwap, b1, b2, r1, r2
cComp, cSwap, b1, b2 = [0,0,0,len(l1)]
l1.sort()
self.refresh()

def bubble(self): # simple bubble sort
global cComp, cSwap, b1, b2, r1, r2
cComp, cSwap, b1, b2 = [0,0,0,len(l1)]
b1 = 0
b2 = len(l1)
for i in range(len(l1)):
b2 = len(l1) - i
for j in range(b2-1):
cComp = cComp + 1
r1 = j
r2 = j+1
if l1[r1] > l1[r2]:
cSwap = cSwap + 1
l1[r1], l1[r2] = [l1[r2], l1[r1]]
self.refresh()
time.sleep(0.02 )

def ripple(self):
global cComp, cSwap, b1, b2, r1, r2
cComp, cSwap, b1, b2 = [0,0,0,len(l1)]
bDone =1
while bDone:
bDone = 0
for j in range(b1,b2-1):
cComp = cComp + 1
r1 = j
r2 = j + 1
if l1[r1] > l1[r2]:
cSwap = cSwap + 1
bDone = 1
l1[r1], l1[r2] = [l1[r2], l1[r1]]
self.refresh()
time.sleep(0.01 )
b2 = b2 - 1
for j in range(b2,b1,-1):
cComp = cComp + 1
r1 = j - 1
r2 = j
if l1[r1] > l1[r2]:
cSwap = cSwap + 1
bDone = 1
l1[r1], l1[r2] = [l1[r2], l1[r1]]
self.refresh()
time.sleep(0.01 )
b1 = b1 + 1
self.refresh()

def shells(self):
global cComp, cSwap, b1, b2, r1, r2
cComp, cSwap, b1, b2 = [0,0, 0, len(l1)]
bDone = 1
span = 64
while bDone:
bDone = 0
for i in range(b1,b2-span):
r1 = i
r2 = i + span
cComp = cComp + 1
if l1[r1] > l1[r2]:
cSwap = cSwap + 1
bDone = 1
l1[r1], l1[r2] = [l1[r2], l1[r1]]
self.refresh()
time.sleep(0.01 )

if not bDone: # if no changes that sweep, exit
break
bDone = 0
if span > 1:
span = int(span/2)

for i in range(b2-1,b1+span,-1):
r1 = i - span
r2 = i
cComp = cComp + 1
if l1[r1] > l1[r2]:
cSwap = cSwap + 1
bDone = 1
l1[r1], l1[r2] = [l1[r2], l1[r1]]
self.refresh()
time.sleep(0.01 )
if span > 1:
span = int(span/2)
self.refresh()

def refresh(self):
self.LCDcount.d isplay('%3d' % cComp) # update counters
self.LCDswap.di splay('%3d' % cSwap)
self.frame4.era se() # clear any old lines
p = QPainter(self.f rame4)
mar = self.frame4.wid th()/100 # margin
vsp = 2 # vertical spacing
hrz = (self.frame4.wi dth()-2*mar)/100 # horizontal scalar
p.setPen(QColor ("black"))
for i in range(100):
p.drawLine(mar, mar+vsp*i,hrz*( l1[i]+1),mar+vsp*i)
p.setPen(QColor ("blue"))
p.drawLine(mar, mar+vsp*b1-1,hrz*100,mar+v sp*b1-1)
p.drawLine(mar, mar+vsp*b2-1,hrz*100,mar+v sp*b2-1)
p.setPen(QColor ("red"))
p.drawLine(mar, mar+vsp*r1+1,hr z*100,mar+vsp*r 1+1)
p.drawLine(mar, mar+vsp*r2+1,hr z*100,mar+vsp*r 2+1)

if __name__ == '__main__':
l1 = range(100) # numbers 0 to 99
b1 = 0 # blue line 1
b2 = 100 # blue line 2
r1 = 1 # red line 1
r2 = 1 # red line 2
cComp = 0 # count of compares
cSwap = 0 # count of swaps
app = QApplication(sy s.argv)
QObject.connect (app, SIGNAL('lastWin dowClosed()'),
app, SLOT('quit()'))
win = dlgForm()
app.setMainWidg et(win)
win.show()
app.exec_loop()
-------------------------------------------------------
-------- frmtest.py --------------------------
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'frmtest.ui'
#
# Created: Sun Aug 1 15:55:11 2004
# by: The PyQt User Interface Compiler (pyuic) 3.8
#
# WARNING! All changes made in this file will be lost!

from qt import *

class frmTest(QMainWi ndow):
def __init__(self,p arent = None,name = None,fl = 0):
QMainWindow.__i nit__(self,pare nt,name,fl)
self.statusBar( )

if not name:
self.setName("f rmTest")

self.setCentral Widget(QWidget( self,"qt_centra l_widget"))

self.frame4 = QFrame(self.cen tralWidget(),"f rame4")
self.frame4.set Geometry(QRect( 40,109,441,210) )
self.frame4.set MinimumSize(QSi ze(440,210))
self.frame4.set FrameShape(QFra me.StyledPanel)
self.frame4.set FrameShadow(QFr ame.Raised)
self.frame4.set Margin(1)

self.cmd2 = QPushButton(sel f.centralWidget (),"cmd2")
self.cmd2.setGe ometry(QRect(21 0,330,100,50))

self.cmdSort = QPushButton(sel f.centralWidget (),"cmdSort")
self.cmdSort.se tGeometry(QRect (350,330,100,50 ))

self.cmdQuit = QPushButton(sel f.centralWidget (),"cmdQuit")
self.cmdQuit.se tGeometry(QRect (70,330,100,50) )

self.txtHello = QLabel(self.cen tralWidget(),"t xtHello")
self.txtHello.s etGeometry(QRec t(50,20,450,76) )
txtHello_font = QFont(self.txtH ello.font())
txtHello_font.s etPointSize(48)
self.txtHello.s etFont(txtHello _font)
self.txtHello.s etAlignment(QLa bel.AlignCenter )

self.cmdBubble = QPushButton(sel f.centralWidget (),"cmdBubble" )
self.cmdBubble. setGeometry(QRe ct(500,109,80,4 0))

self.cmdRipple = QPushButton(sel f.centralWidget (),"cmdRipple" )
self.cmdRipple. setGeometry(QRe ct(500,160,80,4 0))

self.cmdShell = QPushButton(sel f.centralWidget (),"cmdShell")
self.cmdShell.s etGeometry(QRec t(500,210,80,40 ))

self.txtCopyrig ht = QLabel(self.cen tralWidget(),"t xtCopyright")
self.txtCopyrig ht.setGeometry( QRect(40,380,40 0,21))

self.LCDswap = QLCDNumber(self .centralWidget( ),"LCDswap")
self.LCDswap.se tGeometry(QRect (490,370,91,31) )
self.LCDswap.se tSegmentStyle(Q LCDNumber.Flat)

self.LCDcount = QLCDNumber(self .centralWidget( ),"LCDcount")
self.LCDcount.s etGeometry(QRec t(490,329,91,31 ))
self.LCDcount.s etMode(QLCDNumb er.Dec)
self.LCDcount.s etSegmentStyle( QLCDNumber.Flat )

self.languageCh ange()

self.resize(QSi ze(603,438).exp andedTo(self.mi nimumSizeHint() ))
self.clearWStat e(Qt.WState_Pol ished)

def languageChange( self):
self.setCaption (self.__tr("tes t form"))
self.cmd2.setTe xt(self.__tr("R eshuffle"))
self.cmdSort.se tText(self.__tr ("Sort"))
self.cmdQuit.se tText(self.__tr ("Quit"))
self.txtHello.s etText(self.__t r("Sort Demo"))
self.cmdBubble. setText(self.__ tr("Bubble"))
self.cmdRipple. setText(self.__ tr("Ripple"))
self.cmdShell.s etText(self.__t r("Shell"))
self.txtCopyrig ht.setText(self .__tr("Copyrigh t 2004 GPL Peter"))

def __tr(self,s,c = None):
return qApp.translate( "frmTest",s ,c)
---------------------------------------------------------

Jul 18 '05 #8
On Tuesday 03 August 2004 8:19 pm, Peter wrote:
Diez B. Roggisch wrote:
Maybe it helps to put your sleep not in the drawing code, but between the
arrival of different data sets to draw, thus limiting the redraws to an
amount of lets say 10/s.


Yes - tried that, but gives incomplete draw / flicker.


There are lots of standard graphics techniques for eliminating flicker when
drawing that you can exploit with PyQt. Double buffering for example - draw
to a QPixmap and then blit it to the QWidget.

Phil
Jul 18 '05 #9
Peter wrote:
Yes - tried that, but gives incomplete draw / flicker.

More details:
the idea is to provide a graphics demo of sort algorithms for my 13 year old
son. A number of lines of differring lengths are shown on the screen, and
you can watch as these are sorted, step by step. So you can see the
difference between bubble sort, ripple sort, etc.
Code copied below.
Improving the smoothness of the display is the main thing I'm after.

def refresh(self):
self.LCDcount.d isplay('%3d' % cComp) # update counters
self.LCDswap.di splay('%3d' % cSwap)
self.frame4.era se() # clear any old lines
p = QPainter(self.f rame4)
mar = self.frame4.wid th()/100 # margin
vsp = 2 # vertical spacing
hrz = (self.frame4.wi dth()-2*mar)/100 # horizontal scalar
p.setPen(QColor ("black"))
for i in range(100):
p.drawLine(mar, mar+vsp*i,hrz*( l1[i]+1),mar+vsp*i)
p.setPen(QColor ("blue"))
p.drawLine(mar, mar+vsp*b1-1,hrz*100,mar+v sp*b1-1)
p.drawLine(mar, mar+vsp*b2-1,hrz*100,mar+v sp*b2-1)
p.setPen(QColor ("red"))
p.drawLine(mar, mar+vsp*r1+1,hr z*100,mar+vsp*r 1+1)
p.drawLine(mar, mar+vsp*r2+1,hr z*100,mar+vsp*r 2+1)


To me it would seem the problems lies in the refresh routine,
you're erasing and then redrawing, a viewed object, this will
cause it to flicker around, even worse if using sizers.
There's probally a better way to do this, but when I've
been faced with this type of problem here's what I would try
and maybe it will help you or give you a different way to
look at it.

I'd create a clone of frame4, maybe frame5, only viewing
one at a time.

In my refresh routine I'd create some type of loop
and alternate them using .hide() .show() and only
do my drawing/erasing on the hidden object.

I think anyway you do it, you should only draw/erase
on a hidden object, you could also have frame4 and 5
be the same, but in the routine that calls refresh, .hide()
4, .show() 5, refresh then redraws 4, and on returning from
refresh, .hide() 5, .show()4. Anyway I thing you get the idea.

Just something I'd try.

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
7768
by: Vamsi Mudrageda | last post by:
I am kind of new to Python, and after trying and using wxPython, I found it kind of lacking in easy-to-read documentation, speed at loading, and GUI response-time. So I am looking for an another GUI toolkit that is cross-platform for Python, and am leaning toward PyQt (PyGTK is kind of dull looking in comparison). Unfortunately, although TrollTech says Qt is cross-platform, its license strategy has me a bit confused. So here is to...
2
7959
by: Leif B. Kristensen | last post by:
Can somebody point me to a quick example on how to display the result of an SQL query in a PyQt QListBox? I've googled in vain for this. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est
4
7146
by: Adrian Casey | last post by:
I'm using a QTimer object to expire certain password protected GUI options in my application after 2 minutes. Currently, the timer is reset each time the user presses the 'OK' button. This is not ideal. A user may spend 2 minutes entering data into the GUI before pressing OK in which case the timer expires before they have pressed OK. I want the timer to timeout after 2 minutes of keyboard inactivity (i.e. no events sent) instead of 2...
1
2191
by: Chump Wad | last post by:
I will now die. I am too ignorant to make it work. 10.2.setEventCB.py segfaults for me. It is almost there, but it is not there. SoQt.init returns a string, which I can't use as the parent widget of my PyQt derived class. SoQt.show and mainLoop need a string as a parameter, so my PyQt derived class can't go there.
3
2073
by: Fabio | last post by:
Hi all, I'm about to write an application, and I'd like to use PyQt, but before choosing this toolkit I would like to clarify some particular licensing issues; if some user has already touched these, I would like to hear from his experiences. This app should be cross-platform, so, given qt licensing policies, I would buy a commercial PyQt license and a commercial Qt license. Could I license the application under the GPL for Gnu/Linux...
1
1610
by: Michael McGarry | last post by:
Hi, I am having a problem making a widget appear. I have 5 widgets which are windows with no parents. 3 of the widgets appear without a problem the other 2 widgets will not appear when I invoke widget.show() from within a handler for another widget. I am completely clueless as to why these 2 widgets will not draw. One of them is simply a wait window I want to appear while I am performing a time consuming task. Here is a snippet of...
0
1255
by: Volker Lenhardt | last post by:
Once again a maybe silly question, but I find no solution, neither in the documentation nor in examples. I have got some different layouts to change place by the help of a QGridLayout in its parent widget. To make it nice I use row/col spacing and stretch respectively as well as multicell widgets. There is no problem if the layout next to come uses more rows and columns than the former one. But if it is the other way round, the grid...
2
3456
by: skawaii | last post by:
Ok, here's what's going on. I've just created a custom widget. it works great. I'm having some trouble, however, figuring out how to allow the said widget to resize. For example, when I throw the widget into a new dialog (using Qt Designer), I want to be able to drag it larger/smaller and have widget expand/shrink to that size. Right now, I can drag the widget bigger/smaller all I want, but it doesn't actually change size. I'm pretty...
7
3229
by: Alex Gusarov | last post by:
Hello, I have strong .NET background with C# and want to do some familiar things from it with Python, but don't know how. For example, I created form in qt designer with QCalendarWidget, translated it into Python module and want to overload virtual method paintCell of QCalendarWidget. In C# I can write following (abstract) code: this.calendar.PaintCell += new PaintEventHandler(myPaintCellHandler); void myPaintCellHandler(object sender,...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.