pyqt and weak/strong ref: how to proceed - python

[edit]
It seems I solved the problem... In fact, I now do that:
class Gameboard(QGraphicsScene):
def deletePawn(self, num):
pawnToDelete = self.pawns.pop(num)
pawnToDelete.delete()
class Pawn(QGraphicsItem):
def delete(self):
child.prepareGemotryChange()
child.setParent(None)
#idem for each child
self.gameboard.removeItem(self)
self.gameboard = None
[/edit]
What is the good way to implement references in a pyqt QGraphicsScene?
I made a class Gameboard which inherits QGraphicsScene, and this gameboard contains a variable number of pawns (wich inherit QGraphicsPolygonItem)
Pawns can be created or deleted dynamically, creation is ok but deletion sometimes crash...
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtOpenGL
class Gameboard(QGraphicsScene):
def __init__(self):
super(Gameboard, self).__init__()
self.pawns = {}
self.currentPawn = None
def createSquares(self):
#create the polygons of the squares and affect their coordinates x,y
def createPawn(self):
pawn = Pawn(self)
num = len(self.pawns)
self.pawns[num] = pawn
self.addItem(self.pawns[num])
def deletePawn(self, num):
self.currentPawn = None
self.pawns[num].beforeDelete()
self.pawns[num].prepareGeometryChange()
self.removeItem(self.pawns[num])
del self.pawns[num]
def selectPawn(self, pawn):
#a pawn is selected, by click for example
self.currentPawn = pawn
def keyPressEvent(self, event):
ekey = event.key()
if ekey == Qt.Key_Delete and self.currentPawn != None:
num = self.currentPawn.number
self.deletePawn(num)
class Pawn(QGraphicsItem):
def __init__(self, gameboard):
super(Pawn, self).__init__()
self.gameboard = gameboard
self.number = 0
self.pos = (-1,-1)
self.name = ""
def create(self, x, y, num):
#create a QGraphicsPolygonItem, a QGraphixPixmapItem and a QGraphicsTextItem which are child of the QGraphicsItem Pawn, and set position
self.number = num
self.pos = (x,y)
self.gameboard.squares[(x,y)].occupiedBy = self
def move(self, newPos):
self.gameboard.squares[self.pos].occupiedBy = None
self.pos = newPos
self.gameboard.squares[self.pos].occupiedBy = None
def beforeDelete(self):
#a function I add trying to get rid of the crash
self.gameboard = None
self.graphicsPolygon.setParent = None
self.graphicsPix.setParent = None
self.text.setParent = None
def mousePressEvent(self, event):
super(Pawn, self).mousePressEvent(event)
if event.button() == 1:
self.gameboard.currentPawn = self
event.accept()
class Square(QGraphicsPolygonItem):
def __init__(self, gameboard):
self.coordinates = (x,y)
self.occupiedBy = None
What is the proper way to proceed, should I use deleteLater?
Or maybe something with the weakref lib?
Is it because of the variable gameboard in Pawn?

Related

Mouse not drawing in pyglet

My custom mouse image is not showing up in pyglet. It loads normally(When you create the window outside a class), but when i make the window in a class and try yo add the custom mouse cursor nothing happens
class x:
def __init__(self):
self.game_window = pyglet.window.Window()
self.on_mouse_press = self.game_window.event(self.on_mouse_press)
self.game_cursor = pyglet.image.load('image.png')
self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
self.game_window.set_mouse_cursor(self.cursor)
I have tried printing every one of the lines of code (for mouse image loading)
When i print - self.game_cursor = pyglet.image.load('image.png') - This is the result:
ImageData 85x82
When i print - self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70) - This is the result:
pyglet.window.ImageMouseCursor object at 0x7f4dad76b390
When i print - self.game_window.set_mouse_cursor(self.cursor) - This is the result:
None
How do I fix make the mouse show?
I strongly suggest you inherit the window class in to your class instead of keeping it as a internal value if possible. So you can use override hooks to replace the on_ functions. Perhaps this is an outdated approach, but for the time I've learned to work with these things - it's reommended.
class x(pyglet.window.Window):
def __init__(self):
super(x, self).__init__()
self.game_cursor = pyglet.image.load('image.png')
self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
self.set_mouse_cursor(self.cursor)
def on_mouse_press():
# Your code handling on_mouse_press
Here's a working example:
from pyglet import *
from pyglet.gl import *
key = pyglet.window.key
class main(pyglet.window.Window):
def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
super(main, self).__init__(width, height, *args, **kwargs)
self.game_cursor = pyglet.image.load('image.png')
self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
self.set_mouse_cursor(self.cursor)
self.x, self.y = 0, 0
self.keys = {}
self.mouse_x = 0
self.mouse_y = 0
self.alive = 1
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_x = x
def on_key_release(self, symbol, modifiers):
try:
del self.keys[symbol]
except:
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
self.keys[symbol] = True
def render(self):
self.clear()
## Add stuff you want to render here.
## Preferably in the form of a batch.
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
if __name__ == '__main__':
x = main()
x.run()
According to pyglet documentation for ImageMouseCursor class link method draw(x, y) is abstract. So I've tried sub-classing ImageMouseCursor and implementing draw method like this:
import pyglet
pyglet.resource.path = ['resources']
pyglet.resource.reindex()
# subclass definition
class GameMouse(pyglet.window.ImageMouseCursor):
# class initialization
def __init__(self):
self.game_cursor = pyglet.resource.image('game_cursor.png')
super().__init__(self.game_cursor, 0, 34)
# method override
def draw(self, x, y):
self.game_cursor.blit(x, y)
However, this will not work if gl blending is not enabled. gl blending is needed to display alpha channels. I've managed to enable it by sub-classing Window class, and using glEnable / glBlendFunc functions. This is the part of the code that does as described:
# subclass definition:
class GameApp(pyglet.window.Window):
# class initialization
def __init__(self):
super(GameApp, self).__init__()
pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA,
pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
Hope this helps

animate a QGraphicsPixmapItem

I am trying to animate a QGraphicsPixmapItem in PyQt5.
The program as is crashes without any error message, and removing the lines about the variable 'anime' makes the program work normally.
here is the QGraphicsPixMapItem:
class QStone(QGraphicsPixmapItem,QGraphicsObject):
def __init__(self, color, movable):
QGraphicsPixmapItem.__init__(self)
QGraphicsObject.__init__(self)
if movable:
self.setFlag(QGraphicsItem.ItemIsMovable)
white = QPixmap("ressources/white2.png")
black = QPixmap("ressources/black_stone.png")
empty = QPixmap("ressources/no_stone.jpg")
if color == Player.white:
self.setPixmap(white.scaled(60, 60, Qt.KeepAspectRatio))
elif color == Player.black:
self.setPixmap(black.scaled(60, 60, Qt.KeepAspectRatio))
self.w = self.boundingRect().width()
self.h = self.boundingRect().height()
def hoverEnterEvent(self, event):
self.setCursor(Qt.OpenHandCursor)
self.setOpacity(0.5)
event.accept()
def hoverLeaveEvent(self, event):
self.setCursor(Qt.ArrowCursor)
self.setOpacity(1.)
event.accept()
the QGraphicsObject inheritance seems to be required for using QPropertyAnimation.
here is the code containing this animation:(this method belongs to a QGraphicsView's subclass):
def display_stone(self, x, y, color=None):
stone = ""
# if color is None:
# stone = QStone("", True)
if color == Player.white:
stone = QStone(Player.white, False)
elif color == Player.black:
stone = QStone(Player.black, False)
stone.setOpacity(0.0)
anime = QPropertyAnimation(stone, b"opacity",self)
anime.setDuration(800)
anime.setStartValue(0.0)
anime.setEndValue(1.0)
anime.start()
stone.setPos(x - stone.w / 2, y - stone.h / 2)
self.scene.addItem(stone)
stone.setZValue(10)
any idea?
thank you
Unlike the Qt C++ API, PyQt does not allow double inheritance (except in exceptional cases(1)) so you cannot implement a class that inherits from QGraphicsPixmapItem and QGraphicsObject.
In this case there are the following options:
1. In this case it is to create a QObject that handles the property you want to modify, and that is the object that is handled by the QPropertyAnimation:
class OpacityManager(QObject):
opacityChanged = pyqtSignal(float)
def __init__(self, initial_opacity, parent=None):
super(OpacityManager, self).__init__(parent)
self._opacity = initial_opacity
#pyqtProperty(float, notify=opacityChanged)
def opacity(self):
return self._opacity
#opacity.setter
def opacity(self, v):
if self._opacity != v:
self._opacity = v
self.opacityChanged.emit(self._opacity)
class QStone(QGraphicsPixmapItem):
def __init__(self, color, movable=False):
QGraphicsPixmapItem.__init__(self)
self.manager = OpacityManager(self.opacity())
self.manager.opacityChanged.connect(self.setOpacity)
if movable:
self.setFlag(QGraphicsItem.ItemIsMovable)
# ...
# ...
anime = QPropertyAnimation(stone.manager, b"opacity", stone.manager)
# ...
2. Another option is QVariantAnimation:
# ...
anime = QVariantAnimation(self)
anime.valueChanged.connect(stone.setOpacity)
anime.setDuration(800)
# ...
(1) https://www.riverbankcomputing.com/static/Docs/PyQt5/qt_interfaces.html

tkinter, How can you drag across buttons?

So I have a simple program where when you click a button from a grid it will be filled a colour. I wish to be able to drag across over the buttons and they get filled, unlike at the moment where you have to click every single button. Can this be done?
Here's my code that probably isn't the best:
from tkinter import *
root=Tk()
grid= Frame(root)
grid.pack()
img0=PhotoImage(file="0.png")
img1=PhotoImage(file="1.png")
img2=PhotoImage(file="2.png")
fill = 1
class button:
def __init__(self, x, y):
self.type=0
self.but=Button(grid,command=self.change, image=img0, borderwidth=0)
self.but.grid(row=y, column=x)
def change(self):
if self.type==fill:
self.but.config(image=img0)
self.type=0
else:
self.but.config(image=eval("img"+str(fill)))
self.type=fill
def create(x,y):
grid_buttons = []
for Y in range(y):
grid_buttons.append([])
for X in range(x):
grid_buttons[Y].append(button(X, Y))
create(15,15)
root.mainloop()
Here's one way:
from tkinter import *
root=Tk()
grid= Frame(root)
grid.pack()
img0=PhotoImage(file="0.png")
img1=PhotoImage(file="1.png")
img2=PhotoImage(file="2.png")
fill = 1
class button:
def __init__(self, x, y):
self.type=0
self.but=Button(grid,command=self.change, image=img0, borderwidth=0)
self.but.grid(row=y, column=x)
#Changed
self.already_changed = False
def change(self):
if self.type==fill:
self.but.config(image=img0)
self.type=0
else:
self.but.config(image=eval("img"+str(fill))) #I left this in here, but you should NEVER use eval(). It's unsafe.
self.type=fill
#Changed
def mouse_entered(self):
if not self.already_changed:
self.change()
self.already_changed = True
def mouse_up(self):
self.already_changed = False
#Changed
class Container:
def __init__(self, x, y):
grid_buttons = []
for Y in range(y):
grid_buttons.append([])
for X in range(x):
grid_buttons[Y].append(button(X, Y))
self.buttons = grid_buttons
grid.bind_all("<Button-1>", self.mouse_down)
grid.bind_all("<ButtonRelease-1>", self.mouse_up)
grid.bind_all("<B1-Motion>", self.mouse_motion)
self.mouse_pressed = False
def mouse_down(self, e):
self.mouse_pressed = True
def mouse_up(self, e):
self.mouse_pressed = False
for row in self.buttons:
for but in row:
but.mouse_up()
def mouse_motion(self, e):
for row in self.buttons:
for but in row:
if grid.winfo_containing(e.x_root, e.y_root) is but.but:
but.mouse_entered()
container = Container(15,15)
root.mainloop()
Now, I noticed that some of the things you did aren't quite Python style. So here's a version that more closely follows Python convention. Be warned that it's quite different.
from tkinter import *
root = Tk()
images = {0: PhotoImage(file="0.png"),
1: PhotoImage(file="1.png"),
2: PhotoImage(file="2.png")}
fill = 1
class MyButton(Button): #Convention is for class names to start with uppercase letters
def __init__(self, master):
super(MyButton, self).__init__(master, image = images[0], borderwidth = 0)
self.type = 0
self.already_changed = False
def change(self):
if self.type == fill:
self.type = 0
else:
self.type = fill
self.config(image=images[self.type])
def mouse_entered(self):
if not self.already_changed:
self.change()
self.already_changed = True
def mouse_up(self):
self.already_changed = False
class Container(Frame):
def __init__(self, master, width, height):
super(Container, self).__init__(master)
buttons = []
for y in range(height):
buttons.append([])
for x in range(width):
button = MyButton(self)
button.grid(row = x, column = y)
buttons[y].append(button)
self.buttons = buttons
self.bind_all("<Button-1>", self.mouse_down)
self.bind_all("<ButtonRelease-1>", self.mouse_up)
self.bind_all("<B1-Motion>", self.mouse_motion)
self.mouse_pressed = False
def mouse_down(self, e):
self.update_containing_button(e)
self.mouse_pressed = True
def mouse_up(self, e):
self.mouse_pressed = False
for row in self.buttons:
for button in row:
button.mouse_up()
def mouse_motion(self, e):
self.update_containing_button(e)
def update_containing_button(self, e):
for row in self.buttons:
for button in row:
if self.winfo_containing(e.x_root, e.y_root) is button:
button.mouse_entered()
grid = Container(root, 15, 15)
grid.pack()
root.mainloop()
Why post both? Because it looks like you have more code in the actual application (that's good, it's a minimal example). I didn't want to force you to rewrite my code to make it work with the rest of your code, or vice versa.
Functionality differences between the two versions:
The second version has been modified so it uses object-oriented features instead of global variables, making it more flexible and easier to change.
The second version removes the binding on the buttons themselves, instead having the container handle everything.

Button commands in Tkinter

I'm trying to make a text adventure with tkinter and I'm slowly getting something together. I'm trying to display commands as they come from room to room but even though the buttons appear, nothing happens when I press them.
game.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import world
from player import Player
from ui import *
def main():
gui = Window(root())
while True:
gui.mainloop()
else:
pass
if __name__ == '__main__':
main()
ui.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
import world, tiles, action
from player import Player
class Window(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master=master)
self.master = master
self.player = Player()
self.init_ui()
def init_ui(self):
self.master.title("****")
self.tabs = Tabs(self.master)
world.load_tiles()
self.world = world.tile_exists(self.player.location_x, self.player.location_y)
self.update_main()
def update_main(self):
self.world.scene_init()
self.world.modify_player(self.player)
self.tabs.update_tab(self.world, self.player)
def _label(self, master, text, side=None, anchor=None):
new_label = tk.Label(master, text=text)
new_label.pack(side=side, anchor=anchor)
def _button(self, master, text, command, side=None, anchor=None):
new_button = tk.Button(master, text=text, command=command)
new_button.pack(side=side, anchor=anchor)
class Tabs(Window):
def __init__(self, master):
self.master = master
self.nb = ttk.Notebook(self.master)
nb_1 = ttk.Frame(self.nb)
self.frame_1 = tk.Frame(nb_1, bg='red', bd=2, relief=tk.SUNKEN, padx=5, pady=5)
self.frame_1.pack(expand=1, fill='both', side=tk.LEFT)
self.nb.add(nb_1, text='Game')
self.nb.pack(expand=1, fill='both', side=tk.LEFT)
def update_tab(self, world, player):
avaliable_actions = world.avaliable_actions()
self._label(self.frame_1, world.display_text(), side=tk.LEFT, anchor=tk.N)
for action in avaliable_actions:
self._button(self.frame_1, text=action, command=player.do_action(action, **action.kwargs), side=tk.BOTTOM, anchor=tk.E)
def root():
root = tk.Tk()
root.geometry("600x350+200+200")
return root
world.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
_world = {}
def tile_exists(x, y):
"""Returns the tile at the given coordinates or None if there is no tile.
:param x: the x-coordinate in the worldspace
:param y: the y-coordinate in the worldspace
:return: the tile at the given coordinates or None if there is no tile
"""
return _world.get((x, y))
def load_tiles():
with open('scenes.txt', 'r') as f:
rows = f.readlines()
x_max = len(rows[0].split('\t'))
for y in range(len(rows)):
cols = rows[y].split('\t')
for x in range(x_max):
tile_name = cols[x].replace('\n', '')
_world[(x, y)] = None if tile_name == '' else getattr(__import__('tiles'),
tile_name)(x, y)
return _world
tiles.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import world, action
from player import Player
class MapTile():
def __init__(self, x, y):
self.x = x
self.y = y
def display_text(self):
pass
# raise NotImplementedError()
def modify_player(self, the_player):
raise NotImplementedError()
def adjacent_moves(self):
moves = []
if world.tile_exists(self.x + 1, self.y):
moves.append(action.MoveEast())
if world.tile_exists(self.x - 1, self.y):
moves.append(action.MoveWest())
if world.tile_exists(self.x, self.y - 1):
moves.append(action.MoveNorth())
if world.tile_exists(self.x, self.y + 1):
moves.append(action.MoveSouth())
return moves
def avaliable_actions(self):
'''Returns all of the default avaliable_actions in a room'''
moves = self.adjacent_moves()
# moves.append(action.ViewInventory())
return moves
class Scene_1(MapTile):
def scene_init(self):
self.location = 'Scene_1'
self.long_desc = 'Welcome to {}, the shittiest place on earth.'.format(self.location)
self.short_desc = 'Eh, I don\'t care.'
def display_text(self):
return self.long_desc
def modify_player(self, the_player):
self.first = True
return self.display_text()
class Scene_2(MapTile):
def scene_init(self):
self.location = 'Scene_2'
self.long_desc = 'This is {}, but noone gives a damn.'.format(self.location)
self.short_desc = 'Eh, I don\'t care, really.'
def display_text(self):
return self.long_desc
def modify_player(self, the_player):
self.first = True
return self.display_text()
player.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Player():
'''Base for player'''
def __init__(self):
self.inventory = []
self.hp = 100
self.location_x, self.location_y = 1, 1
self.victory = False
def is_alive(self):
return self.hp >= 0
def do_action(self, action, **kwargs):
action_method = getattr(self, action.method.__name__)
if action_method:
action_method(**kwargs)
def print_inventory(self):
for item in self.inventory:
print(item, 'n')
def move(self, dx, dy):
self.location_x += dx
self.location_y += dy
def move_north(self):
self.move(dx=0, dy=-1)
def move_south(self):
self.move(dx=0, dy=1)
def move_east(self):
self.move(dx=1, dy=0)
def move_west(self):
self.move(dx=-1, dy=0)
action.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from player import Player
class Action():
def __init__(self, method, name, **kwargs):
"""Creates a new action
:param method: the function object to execute
:param name: the name of the action
:param ends_turn: True if the player is expected to move after this action else False
:param hotkey: The keyboard key the player should use to initiate this action
"""
self.method = method
self.name = name
self.kwargs = kwargs
def __str__(self):
return "{}".format(self.name)
class MoveNorth(Action):
def __init__(self):
super().__init__(method=Player.move_north, name='north')
class MoveSouth(Action):
def __init__(self):
super().__init__(method=Player.move_south, name='south')
class MoveEast(Action):
def __init__(self):
super().__init__(method=Player.move_east, name='east')
class MoveWest(Action):
def __init__(self):
super().__init__(method=Player.move_west, name='west')
class ViewInventory(Action):
"""Prints the player's inventory"""
def __init__(self):
super().__init__(method=Player.print_inventory, name='View inventory', hotkey='i')
class Attack(Action):
def __init__(self, enemy):
super().__init__(method=Player.attack, name="Attack", hotkey='a', enemy=enemy)
class Flee(Action):
def __init__(self, tile):
super().__init__(method=Player.flee, name="Flee", hotkey='f', tile=tile)
command expect function name without () and arguments.
Mistake:
command=player.do_action(action, **action.kwargs)
This way you assign to command value returned by player.do_action() but this functions returns None
You have to use lambda function
command=lambda:player.do_action(action, **action.kwargs)
but maybe you will need also arguments in lambda because you create this in for loop.
command=lambda act=action, kws=action.kwargs : player.do_action(act, **kws)

pyqt - error while running, probably wrong paintevent method implementation

Me and my colleagues are writing a data processing application in python.
We are currently working on the frontend part of the application.
We have a big problem though, that's that the application gets the following error after a random amount of time:
QWidget::repaint: Recursive repaint detected
This one also pops up from time to time:
QPainter::begin: Paint device returned engine == 0, type: 1
This is the file where all gui related stuff happens, I cut out the irrelevant methods for the sake of not being to lengthy:
gfx.py:
import sys, random, math
from PyQt4 import QtGui, QtCore
from random import randrange
from eventbased import listener
app = QtGui.QApplication(sys.argv)
def exec():
return app.exec_()
class MapView(QtGui.QMainWindow, listener.Listener):
def __init__(self, mapimagepath = 0, nodes = 0):
QtGui.QMainWindow.__init__(self)
listener.Listener.__init__(self)
self.setWindowTitle('Population mapping')
self.map = Map(self, mapimagepath)
self.setCentralWidget(self.map)
self.map.start()
self.center()
def center(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move(50, 0)
def handle(self, event):
if(event.type == 0):
self.map.addNode(event.object.scanner)
if(event.type == 1):
self.map.delNode(event.object.scanner)
if(event.type == 2):
self.map.addBranch(event.object.node1.scanner, event.object.node2.scanner)
if(event.type == 3):
self.map.delBranch(event.object.node1.scanner, event.object.node2.scanner)
if(event.type == 4):
self.map.changeNode(event.object.scanner.sensorid, event.result)
if(event.type == 5):
self.map.changeBranch(event.object.node1.scanner.sensorid, event.object.node2.scanner.sensorid, event.result)
self.repaint(self.map.contentsRect())
self.update(self.map.contentsRect())
######################################################################
class Map(QtGui.QFrame):
def __init__(self, parent, mapimagepath):
QtGui.QFrame.__init__(self, parent)
#self.timer = QtCore.QBasicTimer()
#coordinaten hoeken NE en SW voor kaart in map graphics van SKO
self.realmap = RealMap(
mapimagepath,
(51.0442, 3.7268),
(51.0405, 3.7242),
550,
800)
parent.setGeometry(0,0,self.realmap.width, self.realmap.height)
self.refreshspeed = 5000
self.mapNodes = {}
def addNode(self, scanner):
coord = self.realmap.convertLatLon2Pix((scanner.latitude, scanner.longitude))
self.mapNodes[scanner.sensorid] = MapNode(scanner, coord[0], coord[1])
# type: 4 --> changenode ,
#((change, gem_ref, procentuele verandering ref), scanner object)
def changeNode(self, sensorid, branchdata):
self.mapNodes[sensorid].calcDanger(branchdata[2])
def paintEvent(self, event):
painter = QtGui.QPainter(self)
rect = self.contentsRect()
#teken achtergrond
self.realmap.drawRealMap(painter)
#teken nodes
for sensorid, mapNode in self.mapNodes.items():
mapNode.drawMapNode(painter, self.realmap)
######################################################################
class RealMap:
def __init__(self, path, coordRightTop,
coordLeftBot, width, height, pixpermet = 2.6):
self.path = path
self.coordLeftBot = coordLeftBot
self.coordRightTop = coordRightTop
self.width = width
self.height = height
self.realdim = self.calcRealDim()
self.pixpermet = pixpermet
def drawRealMap(self, painter):
image = QtGui.QImage(self.path)
painter.drawImage(0,0,image)
######################################################################
class MapNode:
dangertocolor = {"normal":"graphics//gradients//green.png",
"elevated":"graphics//gradients//orange.png",
"danger":"graphics//gradients//red.png"}
def __init__(self, scanner, x, y, danger = 0):
self.scanner = scanner
self.x = x
self.y = y
self.danger = 'normal'
self.calcDanger(danger)
def drawMapNode(self, painter, realmap):
radiusm = self.scanner.range
radiusp = radiusm*realmap.pixpermet
factor = radiusp/200 # basis grootte gradiƫnten is 200 pixels.
icon = QtGui.QImage("graphics//BT-icon.png")
grad = QtGui.QImage(MapNode.dangertocolor[self.danger])
grad = grad.scaled(grad.size().width()*factor, grad.size().height()*factor)
painter.drawImage(self.x-100*factor,self.y-100*factor, grad)
painter.drawImage(self.x-10, self.y-10,icon)
painter.drawText(self.x-15, self.y+20, str(self.scanner.sensorid) + '-' + str(self.scanner.name))
An object is made through our application class:
mapview = gfx.MapView(g_image)
mapview.show()
So the first question is. What are we doing wrong in the paintEvent method?
Secondly question
Is there a way to make the paintevent not be called at EVERY RANDOM THING that happens ? (like mouseovers, etc)?
I tried something like:
def paintEvent(self, event):
if(isinstance(event, QtGui.QPaintEvent)):
painter = QtGui.QPainter(self)
rect = self.contentsRect()
#teken achtergrond
self.realmap.drawRealMap(painter)
#teken nodes
for sensorid, mapNode in self.mapNodes.items():
mapNode.drawMapNode(painter, self.realmap)
else:
pass
This 'works' but is to general I guess.. It actually makes the error appear a lot faster then without the conditional.
When in your gfx.py you have:
self.repaint(self.map.contentsRect())
self.update(self.map.contentsRect())
Calling repaint and calling update one right after another is redundant. And if a paint event comes through that handler and you call repaint() there, you are asking for infinite recursion.
Take note of any Warnings or Notes in the documentation.
http://doc.qt.io/qt-4.8/qwidget.html#update
http://doc.qt.io/qt-4.8/qwidget.html#repaint
http://doc.qt.io/qt-4.8/qwidget.html#paintEvent
I don't see the cause for your other error right off, but it probably has to do with QPainter getting used when it shouldn't...
http://doc.qt.io/qt-4.8/qpainter.html#begin
http://doc.qt.io/qt-4.8/qpainter.html#details
Hope that helps.

Categories

Resources