wxPython DrawRectangle Not Filled with Black Background - python

I am using python 2.7 and the most up to date version of wxpython for it (3.0).
I am trying to draw a rectangle that is not filled. When I run the code below, it draws a red rectangle with the proper thickness, but the inside is white and not my background color (black).
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="Maze")
self.SetBackgroundColour('black')
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, event=None):
self.dc = wx.PaintDC(self)
self.dc.Clear()
self.dc.SetPen(wx.Pen(wx.RED, 2))
self.dc.DrawRectangle(50, 50, 50, 50)
I don't really understand why I am having this problem and any help would be greatly appreciated. I apologize if this is a trivial answer, as I am new to wxpython.

DrawRectangle is drawed with the current pen and filled with the current brush. So you must also call self.dc.SetBrush.

Related

Persistent drawing + temporary overlay with wx.PaintDC

I'm trying to make something of a Microsoft Paint-esque app using wxPython.
Currently, the app 'draws' onto the screen with a circular brush during a mouse left-down event. This is great, and the desired behavior. But I also need a circle of the same radius to 'follow' the mouse, without it drawing persistently onto wx.PaintDC.
That is, a circle of some radius follows the mouse around the screen, but only when the left mouse button is held, should the circle be 'permanently' drawn onto the buffer.
The approaches I've taken either (1) have a circle following the mouse around, but draw onto the PaintDC instance regardless of mouse-down, (2) follow the mouse around but never draw persistently onto the PaintDC instance, or (3) do not follow the mouse around, but appear and are drawn persistently on left-mouse down (see the example below).
Thank you!
import wx
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self.draw = False
self.radius = 50
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_MOTION, self.Draw)
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
def OnPaint(self, event):
dc = wx.PaintDC(self)
def Draw(self, event):
if self.draw == True:
x = event.GetX()
y = event.GetY()
dc = wx.ClientDC(self)
pen = wx.Pen(wx.Colour(192,192,192,128), 2)
brush = wx.Brush(wx.Colour(192,192,192,128))
dc.SetPen(pen)
dc.SetBrush(brush)
dc.DrawCircle(x,y,self.radius)
def OnLeftDown(self, event):
self.draw = True
def OnLeftUp(self, event):
self.draw = False
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Test",style=wx.DEFAULT_FRAME_STYLE,size=wx.Size(400, 300))
self.main_panel = MyPanel(self)
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
There is the wx.Overlay class that does a pretty good job assisting with drawing temporary things on top of more permanent stuff. See the Overlay sample in the demo: https://github.com/wxWidgets/Phoenix/blob/master/demo/Overlay.py

Improve wxPython OnPaint

I have the following wx.Window:
class SketchWindow(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent, -1)
self.SetBackgroundColour('White')
# Window event binding
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_IDLE, self.OnIdle)
# run
self.Run()
def OnPaint(self, evt):
self.DrawEntities(wx.PaintDC(self))
def DrawEntities(self, dc):
dc.SetPen(wx.Pen('Black', 1, wx.SOLID))
dc.SetBrush(wx.Brush('Green', wx.SOLID))
# draw all
for e in self.entities:
x, y = e.location
dc.DrawCircle(x, y, 4)
def OnIdle(self, event):
self.Refresh(False)
def Run(self):
# update self.entities ...
# call this method again later
wx.CallLater(50, self.Run)
I need to draw on my window a number of circles [0, 2000] every N milliseconds (50 in my example), where at each step these circles may update their location.
The method I wrote works (the circles are anti-aliased too) but it's quite slow.
Is there a way to improve my solution?
I think the basic idea for better performance is to draw to memory offscreen, then blit the result to the screen. You could use the BufferedCanvas to accomplish this (example given at bottom of link page).
You should better explain why you characterize this as quite slow. (This code looks like it could be part of a billiard table simulation). Some time profiling would help you there. I had to add a lot of code to make your code snippet run, but some quick observations is 1) you probably need a dc.Clear() in your OnPaint() routine or you will get "trails" of all the prior drawn circles. Also, you may be able to use a Buffered DC to get smoother graphic updates, by changing
def OnPaint(self, evt):
self.DrawEntities(wx.PaintDC(self))
to
def OnPaint(self, evt):
self.DrawEntities(wx.BufferedPaintDC(self))

How to detect mouse click on ellipse drawn in pyside?

I am using QPainter within a QWidget to draw a bunch of ellipses on a black background as follows:
paint = QPainter()
paint.begin(self)
paint.setBrush(Qt.black)
paint.drawRect(event.rect())
brush = ...
paint.setBrush(brush)
paint.drawEllipse(center, rad, rad)
After a bunch of ellipses were drawn, and then I want to detect a mouse click on one of such an existing ellipse. I did not find any obvious in the documentation for QPainter.
In case there is something else to be used instead of QPainter, please provide an example that shows my above example in the other framework.
You will need to detect the custom area yourself as follows:
def mousePressEvent(self, event):
''' You will have to implement the contain algorithm yourself'''
if sel.fo(even.pos()):
self.myMethod()
QGraphicsEllipseItem.contains()
Alternatively, you could look into the QGraphicsEllipseItem because it has the contains-logic implemented and offered.
def mousePressEvent(self, event):
if self.contains(event.pos()):
self.myMethod()
and you create your object with the corresponding parameters:
scene = QGraphicsScene()
ellipseItem = MyGraphicsEllipseItem(centerx, centery, rad, rad)
scene.addItem(ellipseItem)
view = QGraphicsView(scene)
view.show()
scene.setBackgroundBrush(Qt.black)

How do I stop paintEvent from painting children widgets?

I'm trying to add rounded corners to a QDialog. I'm defining my own paintEvent method to create rounded corners. It's working, but it's adding rounded borders to everything. Even the cursor is getting a border. Is there any way to disable this behavior?
Example code:
from PySide import QtCore, QtGui
class RenameDialog(QtGui.QDialog):
def __init__(self, parent=None, **kwargs):
super(RenameDialog, self).__init__(
parent=parent, f=QtCore.Qt.CustomizeWindowHint)
self.fieldA = QtGui.QLineEdit(self)
self.fieldB = QtGui.QLineEdit(self)
self.setLayout(QtGui.QHBoxLayout())
self.layout().addWidget(self.fieldA)
self.layout().addWidget(self.fieldB)
# Set background transparent. Only items drawn in paintEvent
# will be visible.
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Base, QtCore.Qt.transparent)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
self.setPalette(palette)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
fillColor = QtGui.QColor(75, 75, 75, 255)
lineColor = QtCore.Qt.gray
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(QtGui.QPen(QtGui.QBrush(lineColor), 2.0))
painter.setBrush(QtGui.QBrush(fillColor))
painter.drawRoundedRect(event.rect(), 15, 15)
I'm trying to do this with a paintEvent because:
QDialog stylesheets cannot use border-radius. Curved borders do show up, but corners are still visible.
QDialogs.setMask() works, but there is no way (that I know of) to anti-alias the mask.
Here is what that looks like:
Paint events are sent to a window/widget with the precise rectangle that needs updating not the whole bounding rectangle of the widget. When you call event.rect() it returns the rectangle that needs updating (As far as I know)
Try changing this line
painter.drawRoundedRect(event.rect(), 15, 15)
To this
painter.drawRoundedRect(self.rect(), 15, 15)
EDIT:
You also need to add this line anywhere in the constructor
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
Hope this helps.
I've found a work-around for now. You can hide the extra borders by using QPainter.eraseRect on the children and having the correct stylesheet set. I've also found that painting over the offending area with QPainter.fillRect works too.
def paintEvent(self, event):
painter = QtGui.QPainter(self)
fillColor = QtGui.QColor(75, 75, 75, 255)
lineColor = QtCore.Qt.gray
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(QtGui.QPen(QtGui.QBrush(lineColor), 2.0))
painter.setBrush(QtGui.QBrush(fillColor))
painter.drawRoundedRect(event.rect(), 15, 15)
# Sketchy fix:
painter.eraseRect(self.childrenRect())
# OR
painter.fillRect(self.childrenRect(), QtGui.QBrush(fillColor))
This doesn't answer my original question though. I'd like to avoid this behavior rather than masking it. So I'm not going to mark this as the answer.

How to draw non-transparent text on an icon (not bitmap) using wxpython?

Short question:
I know how to draw text on a wx.Bitmap, but how can I draw text on a wx.Icon in wxpython so that it does not appear transparent?
Long question:
I have a wxpython based GUI application, that has a taskbar icon, which I set using mytaskbaricon.SetIcon("myicon.ico").
Now I would like to dynamically put some text on the icon, so I tried to use the wx .DrawText method as explained here.This works fine if I test this for bitmaps (which I use in menu items).
However, the taskbar requires an wxIcon instead of a wxBitmap. So I figured I'll convert the icon to a bitmap, draw the text, and then convert it back to an icon. This works, except that the text is not shown transparent. Why ? And how can I make the text NOT transparent ?
My code is as roughly follows:
import wx
class MyTaskBarIcon(wx.TaskBarIcon):
...
icon = wx.Icon("myicon.ico", wx.BITMAP_TYPE_ICO)
bmp = wx.Bitmap("myicon.ico", wx.BITMAP_TYPE_ICO)
memDC = wx.MemoryDC()
memDC.SetTextForeground(wx.RED)
memDC.SelectObject(bmp)
memDC.DrawText("A", 0, 0)
icon.CopyFromBitmap(bmp)
self.SetIcon(icon, APP_NAME_WITH_VERSION)
...
So, no errors raised and myicon.ico is shown, but the letter A is transparant (instead of red). If I use a .bmp file to start with (myicon.bmp) the text appears in the correct color (but the borders are jagged). I've played around with masks, foreground and background colors, but that didn't help.
(I am using Windows 7, Python 2.6, wxpython 2.8)
Edit: I've shortened my explanation, and made the code more self-contained
Short answer: It seems to me that there is a bug in this particular piece of wx code. I am going to report it and see what comes out of it.
Long answer: You can hack your way around. Setup a color, which is not used in the image. Then draw using that color and when done, fix alpha values and color of those pixels to match your expectation:
import wx
from wx import ImageFromStream, BitmapFromImage, EmptyIcon
import cStringIO, zlib
# ================================ ICON ======================================
def getData():
return zlib.decompress(
'x\xda\x01\x97\x03h\xfc\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\
\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\
\x08\x08\x08|\x08d\x88\x00\x00\x03NIDAT8\x8dm\xd2ML\x9bu\x00\xc7\xf1\xef\xf3\
<\xed\xda><\xa3#\xcb\x8a\x0cp\xac8\x15\x87\x89/ \x11\xd1d&:5&#n\xc9\\\xa2\
\xc6\xc3b\xe2\xd1y0Y2\xa3q^\xcc\xb8\x9a\xb9\xf9rQc\xc6\x0es\xa4\xd1\x91\xe98\
\xc8\x96\xb98H\xc3\x8b\xc0\xc6\x00\x91\xd2\xb2\xa7}\xda\xe7\xa5\xcf\xd3\xf6\
\xf9{0\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
def getBitmap():
return BitmapFromImage(getImage())
def getImage():
stream = cStringIO.StringIO(getData())
return ImageFromStream(stream)
def getIcon():
icon = EmptyIcon()
icon.CopyFromBitmap(getBitmap())
return icon
# ============================================================================
class MainWindow(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.number = 0
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.panel = wx.Panel(self)
self.button = wx.Button(self.panel, label="Test")
self.button.Bind(wx.EVT_BUTTON, self.OnButton)
self.tbicon = wx.TaskBarIcon()
self.tbicon.SetIcon(getIcon(), "Test")
self.sizer = wx.BoxSizer()
self.sizer.Add(self.button)
self.panel.SetSizerAndFit(self.sizer)
self.Show()
# --------------------------------------------------------------------------
def OnClose(self, e):
self.tbicon.Destroy()
self.Destroy()
wx.Exit()
# --------------------------------------------------------------------------
def OnButton(self, e):
# HERE WE GO!
self.number += 1
bitmap = getBitmap()
# Find unused color
image = bitmap.ConvertToImage()
my_solid_color = wx.Color(*image.FindFirstUnusedColour(0, 0, 0)[1:])
# Use the unused *unique* color to draw
dc = wx.MemoryDC()
dc.SetTextForeground(my_solid_color)
dc.SelectObject(bitmap)
dc.DrawText(str(self.number), 0, 0)
dc.SelectObject(wx.NullBitmap)
# Convert the bitmap to Image again
# and fix the alpha of pixels with that color
image = bitmap.ConvertToImage()
for x in range(image.GetWidth()):
for y in range(image.GetHeight()):
p = wx.Colour(image.GetRed(x, y),
image.GetGreen(x, y),
image.GetBlue(x, y))
if p == my_solid_color:
image.SetAlpha(x, y, 255) # Clear the alpha
image.SetRGB(x, y, 0, 0, 0) # Set the color that we want
# Convert back to Bitmap and save to Icon
bitmap = image.ConvertToBitmap()
icon = wx.IconFromBitmap(bitmap)
self.tbicon.SetIcon(icon, "Test")
app = wx.App(False)
win = MainWindow(None)
app.MainLoop()
Note: A had to add some icon. You can ignore that part of the code.
Just a guess, but perhaps create your initial icon as an "EmptyIcon", then copy the bmp to it.
import wx
class MyTaskBarIcon(wx.TaskBarIcon):
...
icon = wx.EmptyIcon()
bmp = wx.Bitmap("myicon.ico", wx.BITMAP_TYPE_ICO)
bmp = WriteTextOnBitmap("A", bmp, color=wx.RED) #this function is as in the link above
icon.CopyFromBitmap(bmp)
self.SetIcon(icon, APP_NAME_WITH_VERSION)
...

Categories

Resources