Consistently use _foo for "protected" members

This commit is contained in:
Mika Fischer
2011-07-25 10:55:48 +02:00
parent ba24bc95a2
commit 1a2d5412aa
9 changed files with 197 additions and 197 deletions
+10 -10
View File
@@ -44,14 +44,14 @@ class AnnotationContainerFactory:
The mapping between file pattern and container class responsible
for loading/saving.
"""
self.containers_ = []
self._containers = []
for pattern, item in containers:
if type(item) == str:
item = import_callable(item)
self.containers_.append((pattern, item))
self._containers.append((pattern, item))
def patterns(self):
return [pattern for pattern, item in self.containers_]
return [pattern for pattern, item in self._containers]
def create(self, filename, *args, **kwargs):
"""
@@ -64,7 +64,7 @@ class AnnotationContainerFactory:
*args, **kwargs:
Arguments passed to constructor of the container.
"""
for pattern, container in self.containers_:
for pattern, container in self._containers:
if fnmatch.fnmatch(filename, pattern):
return container(*args, **kwargs)
raise ImproperlyConfigured(
@@ -81,11 +81,11 @@ class AnnotationContainer:
self.clear()
def filename(self):
return self.filename_
return self._filename
def clear(self):
self.annotations_ = []
self.filename_ = None
self._annotations = []
self._filename = None
def load(self, filename):
"""
@@ -93,7 +93,7 @@ class AnnotationContainer:
"""
if not filename:
raise InvalidArgumentException("filename cannot be empty")
self.filename_ = filename
self._filename = filename
start = time.time()
ann = self.parseFromFile(filename)
diff = time.time() - start
@@ -117,7 +117,7 @@ class AnnotationContainer:
if not filename:
filename = self.filename()
self.serializeToFile(filename, annotations)
self.filename_ = filename
self._filename = filename
def serializeToFile(self, filename, annotations):
"""
@@ -242,7 +242,7 @@ class FileNameListContainer(AnnotationContainer):
"""
def parseFromFile(self, filename):
self.basedir_ = os.path.dirname(filename)
self._basedir = os.path.dirname(filename)
f = open(filename, "r")
annotations = []
+1 -1
View File
@@ -66,7 +66,7 @@ class DumpLabelsCommand(BaseCommand):
self.labeltool.loadAnnotations(args[0])
# TODO add better accessor the the labeltool
pprint(self.labeltool.container_.annotations())
pprint(self.labeltool._container.annotations())
class AppendFilesCommand(BaseCommand):
+13 -13
View File
@@ -66,8 +66,8 @@ class LabelTool(QObject):
"""
QObject.__init__(self, parent)
self.container_factory_ = None
self.container_ = AnnotationContainer()
self._container_factory = None
self._container = AnnotationContainer()
self._current_image = None
self._model = AnnotationModel([])
self._mainwindow = None
@@ -204,15 +204,15 @@ class LabelTool(QObject):
config.update(config_module_path)
# Instatiate container factory
self.container_factory_ = AnnotationContainerFactory(config.CONTAINERS)
self._container_factory = AnnotationContainerFactory(config.CONTAINERS)
def loadPlugins(self, plugins):
self.plugins_ = []
self._plugins = []
for plugin in plugins:
if type(plugin) == str:
plugin = import_callable(plugin)
p = plugin(self)
self.plugins_.append(p)
self._plugins.append(p)
action = p.action()
self.pluginLoaded.emit(action)
@@ -223,8 +223,8 @@ class LabelTool(QObject):
fname = str(fname) # convert from QString
try:
self.container_ = self.container_factory_.create(fname)
self._model = AnnotationModel(self.container_.load(fname))
self._container = self._container_factory.create(fname)
self._model = AnnotationModel(self._container.load(fname))
msg = "Successfully loaded %s (%d files, %d annotations)" % \
(fname, self._model.root().numFiles(), self._model.root().numAnnotations())
except Exception as e:
@@ -240,14 +240,14 @@ class LabelTool(QObject):
success = False
try:
# create new container if the filename is different
if fname != self.container_.filename():
if fname != self._container.filename():
# TODO: skip if it is the same class
self.container_ = self.container_factory_.create(fname)
self._container = self._container_factory.create(fname)
# Get annotations dict
ann = self._model.root().getAnnotations()
self.container_.save(ann, fname)
self._container.save(ann, fname)
#self._model.writeback() # write back changes that are cached in the model itself, e.g. mask updates
msg = "Successfully saved %s (%d files, %d annotations)" % \
(fname, self._model.root().numFiles(), self._model.root().numAnnotations())
@@ -266,7 +266,7 @@ class LabelTool(QObject):
self.annotationsLoaded.emit()
def getCurrentFilename(self):
return self.container_.filename()
return self._container.filename()
###########################################################################
# Model stuff
@@ -318,10 +318,10 @@ class LabelTool(QObject):
def getImage(self, item):
# TODO: Also handle video frames
return self.container_.loadImage(item['filename'])
return self._container.loadImage(item['filename'])
def getAnnotationFilePatterns(self):
return self.container_factory_.patterns()
return self._container_factory.patterns()
def addImageFile(self, fname):
fileitem = {
+78 -78
View File
@@ -13,15 +13,15 @@ class AnnotationScene(QGraphicsScene):
def __init__(self, labeltool, items=None, inserters=None, parent=None):
super(AnnotationScene, self).__init__(parent)
self.model_ = None
self.image_item_ = None
self.inserter_ = None
self.scene_item_ = None
self.message_ = ""
self.labeltool_ = labeltool
self._model = None
self._image_item = None
self._inserter = None
self._scene_item = None
self._message = ""
self._labeltool = labeltool
self.itemfactory_ = Factory(items)
self.inserterfactory_ = Factory(inserters)
self._itemfactory = Factory(items)
self._inserterfactory = Factory(inserters)
self.setBackgroundBrush(Qt.darkGray)
self.reset()
@@ -30,35 +30,35 @@ class AnnotationScene(QGraphicsScene):
# getters/setters
#______________________________________________________________________________________________________
def setModel(self, model):
if model == self.model_:
if model == self._model:
# same model as the current one
# reset caches anyway, invalidate root
self.reset()
return
# disconnect old signals
if self.model_ is not None:
self.disconnect(self.model_, SIGNAL('dataChanged(QModelIndex,QModelIndex)'), self.dataChanged)
self.disconnect(self.model_, SIGNAL('rowsInserted(QModelIndex,int,int)'), self.rowsInserted)
self.disconnect(self.model_, SIGNAL('rowsAboutToBeRemoved(QModelIndex,int,int)'), self.rowsAboutToBeRemoved)
self.disconnect(self.model_, SIGNAL('rowsRemoved(QModelIndex,int,int)'), self.rowsRemoved)
self.disconnect(self.model_, SIGNAL('modelReset()'), self.reset)
if self._model is not None:
self.disconnect(self._model, SIGNAL('dataChanged(QModelIndex,QModelIndex)'), self.dataChanged)
self.disconnect(self._model, SIGNAL('rowsInserted(QModelIndex,int,int)'), self.rowsInserted)
self.disconnect(self._model, SIGNAL('rowsAboutToBeRemoved(QModelIndex,int,int)'), self.rowsAboutToBeRemoved)
self.disconnect(self._model, SIGNAL('rowsRemoved(QModelIndex,int,int)'), self.rowsRemoved)
self.disconnect(self._model, SIGNAL('modelReset()'), self.reset)
self.model_ = model
self._model = model
# connect new signals
if self.model_ is not None:
self.connect(self.model_, SIGNAL('dataChanged(QModelIndex,QModelIndex)'), self.dataChanged)
self.connect(self.model_, SIGNAL('rowsInserted(QModelIndex,int,int)'), self.rowsInserted)
self.connect(self.model_, SIGNAL('rowsAboutToBeRemoved(QModelIndex,int,int)'), self.rowsAboutToBeRemoved)
self.connect(self.model_, SIGNAL('rowsRemoved(QModelIndex,int,int)'), self.rowsRemoved)
self.connect(self.model_, SIGNAL('modelReset()'), self.reset)
if self._model is not None:
self.connect(self._model, SIGNAL('dataChanged(QModelIndex,QModelIndex)'), self.dataChanged)
self.connect(self._model, SIGNAL('rowsInserted(QModelIndex,int,int)'), self.rowsInserted)
self.connect(self._model, SIGNAL('rowsAboutToBeRemoved(QModelIndex,int,int)'), self.rowsAboutToBeRemoved)
self.connect(self._model, SIGNAL('rowsRemoved(QModelIndex,int,int)'), self.rowsRemoved)
self.connect(self._model, SIGNAL('modelReset()'), self.reset)
# reset caches, invalidate root
self.reset()
def sceneItem(self):
return self.scene_item_
return self._scene_item
def setCurrentImage(self, current_image):
"""
@@ -66,40 +66,40 @@ class AnnotationScene(QGraphicsScene):
displayed by the scene. This can be either the index to a frame in a
video, or to an image.
"""
if current_image == self.image_item_:
if current_image == self._image_item:
return
elif current_image is None:
self.clear()
self.image_item_ = None
self.image_ = None
self.pixmap_ = None
self._image_item = None
self._image = None
self._pixmap = None
else:
self.clear()
self.image_item_ = current_image
assert self.image_item_.model() == self.model_
self.image_ = self.labeltool_.getImage(self.image_item_)
self.pixmap_ = QPixmap(toQImage(self.image_))
self.scene_item_ = QGraphicsPixmapItem(self.pixmap_)
self.scene_item_.setZValue(-1)
self.setSceneRect(0, 0, self.pixmap_.width(), self.pixmap_.height())
self.addItem(self.scene_item_)
self._image_item = current_image
assert self._image_item.model() == self._model
self._image = self._labeltool.getImage(self._image_item)
self._pixmap = QPixmap(toQImage(self._image))
self._scene_item = QGraphicsPixmapItem(self._pixmap)
self._scene_item.setZValue(-1)
self.setSceneRect(0, 0, self._pixmap.width(), self._pixmap.height())
self.addItem(self._scene_item)
self.insertItems(0, len(self.image_item_.children())-1)
self.insertItems(0, len(self._image_item.children())-1)
self.update()
def insertItems(self, first, last):
if self.image_item_ is None:
if self._image_item is None:
return
assert self.model_ is not None
assert self._model is not None
# create a graphics item for each model index
for row in range(first, last+1):
child = self.image_item_.childAt(row)
child = self._image_item.childAt(row)
if not isinstance(child, AnnotationModelItem):
continue
label_class = child['class']
item = self.itemfactory_.create(label_class, child)
item = self._itemfactory.create(label_class, child)
if item is not None:
self.addItem(item)
else:
@@ -107,28 +107,28 @@ class AnnotationScene(QGraphicsScene):
def onInserterFinished(self):
self.sender().inserterFinished.disconnect(self.onInserterFinished)
self.labeltool_.exitInsertMode()
self.inserter_ = None
self._labeltool.exitInsertMode()
self._inserter = None
def onInsertionModeStarted(self, label_class):
# Abort current inserter
if self.inserter_ is not None:
self.inserter_.abort()
if self._inserter is not None:
self._inserter.abort()
self.deselectAllItems()
# Add new inserter
default_properties = self.labeltool_.propertyeditor().currentEditorProperties()
inserter = self.inserterfactory_.create(label_class, self.labeltool_, self, default_properties)
default_properties = self._labeltool.propertyeditor().currentEditorProperties()
inserter = self._inserterfactory.create(label_class, self._labeltool, self, default_properties)
if inserter is None:
raise InvalidArgumentException("Could not find inserter for class '%s' with default properties '%s'" % (label_class, default_properties))
inserter.inserterFinished.connect(self.onInserterFinished)
self.inserter_ = inserter
self._inserter = inserter
LOG.debug("Created inserter for class '%s' with default properties '%s'" % (label_class, default_properties))
def onInsertionModeEnded(self):
if self.inserter_ is not None:
self.inserter_.abort()
if self._inserter is not None:
self._inserter.abort()
#
# common methods
@@ -140,7 +140,7 @@ class AnnotationScene(QGraphicsScene):
def clear(self):
QGraphicsScene.clear(self)
self.scene_item_ = None
self._scene_item = None
def addItem(self, item):
QGraphicsScene.addItem(self, item)
@@ -151,22 +151,22 @@ class AnnotationScene(QGraphicsScene):
#______________________________________________________________________________________________________
def mousePressEvent(self, event):
LOG.debug("mousePressEvent %s %s" % (self.sceneRect().contains(event.scenePos()), event.scenePos()))
if self.inserter_ is not None:
if self._inserter is not None:
if not self.sceneRect().contains(event.scenePos()) and \
not self.inserter_.allowOutOfSceneEvents():
not self._inserter.allowOutOfSceneEvents():
# ignore events outside the scene rect
return
# insert mode
self.inserter_.mousePressEvent(event, self.image_item_)
self._inserter.mousePressEvent(event, self._image_item)
else:
# selection mode
QGraphicsScene.mousePressEvent(self, event)
def mouseReleaseEvent(self, event):
LOG.debug("mouseReleaseEvent %s %s" % (self.sceneRect().contains(event.scenePos()), event.scenePos()))
if self.inserter_ is not None:
if self._inserter is not None:
# insert mode
self.inserter_.mouseReleaseEvent(event, self.image_item_)
self._inserter.mouseReleaseEvent(event, self._image_item)
else:
# selection mode
QGraphicsScene.mouseReleaseEvent(self, event)
@@ -175,9 +175,9 @@ class AnnotationScene(QGraphicsScene):
sp = event.scenePos()
self.mousePositionChanged.emit(sp.x(), sp.y())
#LOG.debug("mouseMoveEvent %s %s" % (self.sceneRect().contains(event.scenePos()), event.scenePos()))
if self.inserter_ is not None:
if self._inserter is not None:
# insert mode
self.inserter_.mouseMoveEvent(event, self.image_item_)
self._inserter.mouseMoveEvent(event, self._image_item)
else:
# selection mode
QGraphicsScene.mouseMoveEvent(self, event)
@@ -188,7 +188,7 @@ class AnnotationScene(QGraphicsScene):
def onSelectionChanged(self):
model_items = [item.modelItem() for item in self.selectedItems()]
self.labeltool_.treeview().setSelectedItems(model_items)
self._labeltool.treeview().setSelectedItems(model_items)
self.editSelectedItems()
def onSelectionChangedInTreeView(self, items):
@@ -204,9 +204,9 @@ class AnnotationScene(QGraphicsScene):
def editSelectedItems(self):
scene_items = self.selectedItems()
if self.inserter_ is None or len(scene_items) > 0:
if self._inserter is None or len(scene_items) > 0:
items = [item.modelItem() for item in scene_items]
self.labeltool_.propertyeditor().startEditMode(items)
self._labeltool.propertyeditor().startEditMode(items)
#
# key event handlers
@@ -214,7 +214,7 @@ class AnnotationScene(QGraphicsScene):
def selectNextItem(self, reverse=False):
# disable inserting
# TODO: forward this to the ButtonArea
self.inserter_ = None
self._inserter = None
# set focus to the view, so that subsequent keyboard events are forwarded to the scene
if len(self.views()) > 0:
@@ -245,13 +245,13 @@ class AnnotationScene(QGraphicsScene):
def keyPressEvent(self, event):
LOG.debug("keyPressEvent %s" % event)
if self.model_ is None or self.image_item_ is None:
if self._model is None or self._image_item is None:
event.ignore()
return
if self.inserter_ is not None:
if self._inserter is not None:
# insert mode
self.inserter_.keyPressEvent(event, self.image_item_)
self._inserter.keyPressEvent(event, self._image_item)
else:
# selection mode
if event.key() == Qt.Key_Delete:
@@ -276,7 +276,7 @@ class AnnotationScene(QGraphicsScene):
# this is the implemenation of the scene as a view of the model
#______________________________________________________________________________________________________
def dataChanged(self, indexFrom, indexTo):
if self.image_item_ is None or self.image_item_.index() != indexFrom.parent().parent():
if self._image_item is None or self._image_item.index() != indexFrom.parent().parent():
return
item = self.itemFromIndex(indexFrom.parent())
@@ -284,13 +284,13 @@ class AnnotationScene(QGraphicsScene):
item.dataChanged()
def rowsInserted(self, index, first, last):
if self.image_item_ is None or self.image_item_.index() != index:
if self._image_item is None or self._image_item.index() != index:
return
self.insertItems(first, last)
def rowsAboutToBeRemoved(self, index, first, last):
if self.image_item_ is None or self.image_item_.index() != index:
if self._image_item is None or self._image_item.index() != index:
return
for row in range(first, last+1):
@@ -313,39 +313,39 @@ class AnnotationScene(QGraphicsScene):
# message handling and displaying
#______________________________________________________________________________________________________
def setMessage(self, message):
if self.message_ is not None:
if self._message is not None:
self.clearMessage()
if message is None or message == "":
return
# TODO don't use text item at all, just draw the text in drawForeground
self.message_ = message
self.message_text_item_ = QGraphicsSimpleTextItem(message)
self.message_text_item_.setPos(20, 20)
self._message = message
self._message_text_item = QGraphicsSimpleTextItem(message)
self._message_text_item.setPos(20, 20)
self.invalidate(QRectF(), QGraphicsScene.ForegroundLayer)
def clearMessage(self):
if self.message_ is not None:
self.message_text_item_ = None
self.message_ = None
if self._message is not None:
self._message_text_item = None
self._message = None
self.invalidate(QRectF(), QGraphicsScene.ForegroundLayer)
def drawForeground(self, painter, rect):
QGraphicsScene.drawForeground(self, painter, rect)
if self.message_ is not None:
assert self.message_text_item_ is not None
if self._message is not None:
assert self._message_text_item is not None
painter.setTransform(QTransform())
painter.setBrush(QColor('lightGray'))
painter.setPen(QPen(QBrush(QColor('black')), 2))
br = self.message_text_item_.boundingRect()
br = self._message_text_item.boundingRect()
painter.drawRoundedRect(QRectF(10, 10, br.width()+20, br.height()+20), 10.0, 10.0)
painter.setTransform(QTransform.fromTranslate(20, 20))
painter.setPen(QPen(QColor('black'), 1))
self.message_text_item_.paint(painter, QStyleOptionGraphicsItem(), None)
self._message_text_item.paint(painter, QStyleOptionGraphicsItem(), None)
+4 -4
View File
@@ -10,14 +10,14 @@ class ControlButtonWidget(QWidget):
layout.setAlignment(Qt.AlignTop)
self.back_button = QPushButton("<")
self.forward_button = QPushButton(">")
self.label_ = QLabel("<center><b></b></center>")
self._label = QLabel("<center><b></b></center>")
layout.addWidget(self.back_button)
layout.addWidget(self.label_)
layout.addWidget(self._label)
layout.addWidget(self.forward_button)
self.setLayout(layout)
def setFrameNumAndTimestamp(self, num, timestamp):
self.label_.setText("<center><b>%d / %f</b></center>" % (num, timestamp))
self._label.setText("<center><b>%d / %f</b></center>" % (num, timestamp))
def setFilename(self, filename):
self.label_.setText("<center><b>%s</b></center>" % (filename, ))
self._label.setText("<center><b>%s</b></center>" % (filename, ))
+6 -6
View File
@@ -23,7 +23,7 @@ class GraphicsView(QGraphicsView):
self.setMouseTracking(True)
self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing);
self.setStyleSheet("QFrame { border: 3px solid black }");
self.active_ = False
self._active = False
self._pan = False
self._panStartX = -1
self._panStartY = -1
@@ -53,18 +53,18 @@ class GraphicsView(QGraphicsView):
return 1
def isActive(self):
return self.active_
return self._active
def activate(self):
if not self.active_:
self.active_ = True
if not self._active:
self._active = True
self.setFocus(Qt.OtherFocusReason)
self.setStyleSheet("QFrame { border: 3px solid red }");
self.update()
def deactivate(self):
if self.active_:
self.active_ = False
if self._active:
self._active = False
self.clearFocus()
self.setStyleSheet("QFrame { border: 3px solid black }");
self.update()
+9 -9
View File
@@ -15,7 +15,7 @@ class Factory:
Mapping from type to python callable. If not None, all mappings
will be registered with the factory.
"""
self.items_ = {}
self._items = {}
if items is not None:
for _type, item in items.items():
@@ -33,13 +33,13 @@ class Factory:
Reference to the callable which creates the new object.
"""
_type = str(_type)
if _type in self.items_ and not replace:
if _type in self._items and not replace:
raise Exception("Type %s already has an item: %s" % \
(_type, str(self.items_[_type])))
(_type, str(self._items[_type])))
else:
if type(item) == str:
item = import_callable(item)
self.items_[_type] = item
self._items[_type] = item
def clear(self, _type=None):
"""
@@ -53,10 +53,10 @@ class Factory:
"""
_type = str(_type)
if _type is None:
self.items_ = {}
self._items = {}
else:
if _type in self.items_:
del self.items_[_type]
if _type in self._items:
del self._items[_type]
def create(self, _type, *args, **kwargs):
"""
@@ -76,9 +76,9 @@ class Factory:
function returns ``None``.
"""
_type = str(_type)
if _type not in self.items_:
if _type not in self._items:
return None
item = self.items_[_type]
item = self._items[_type]
if item is None:
return None
return item(*args, **kwargs)
+40 -40
View File
@@ -8,9 +8,9 @@ class ItemInserter(QObject):
def __init__(self, labeltool, scene, default_properties=None):
QObject.__init__(self)
self.labeltool_ = labeltool
self.scene_ = scene
self.default_properties_ = default_properties
self._labeltool = labeltool
self._scene = scene
self._default_properties = default_properties
def mousePressEvent(self, event, image_item):
event.accept()
@@ -34,45 +34,45 @@ class PointItemInserter(ItemInserter):
def mousePressEvent(self, event, image_item):
pos = event.scenePos()
ann = {'x': pos.x(), 'y': pos.y()}
ann.update(self.default_properties_)
ann.update(self._default_properties)
image_item.addAnnotation(ann)
event.accept()
class RectItemInserter(ItemInserter):
def __init__(self, labeltool, scene, default_properties=None):
ItemInserter.__init__(self, labeltool, scene, default_properties)
self.current_item_ = None
self.init_pos_ = None
self._current_item = None
self._init_pos = None
def mousePressEvent(self, event, image_item):
pos = event.scenePos()
item = QGraphicsRectItem(QRectF(pos.x(), pos.y(), 0, 0))
item.setPen(Qt.red)
self.current_item_ = item
self.init_pos_ = pos
self.scene_.addItem(item)
self._current_item = item
self._init_pos = pos
self._scene.addItem(item)
event.accept()
def mouseMoveEvent(self, event, image_item):
if self.current_item_ is not None:
assert self.init_pos_ is not None
rect = QRectF(self.init_pos_, event.scenePos()).normalized()
self.current_item_.setRect(rect)
if self._current_item is not None:
assert self._init_pos is not None
rect = QRectF(self._init_pos, event.scenePos()).normalized()
self._current_item.setRect(rect)
event.accept()
def mouseReleaseEvent(self, event, image_item):
if self.current_item_ is not None:
if self.current_item_.rect().width() > 1 and \
self.current_item_.rect().height() > 1:
rect = self.current_item_.rect()
if self._current_item is not None:
if self._current_item.rect().width() > 1 and \
self._current_item.rect().height() > 1:
rect = self._current_item.rect()
ann = {'x': rect.x(), 'y': rect.y(),
'width': rect.width(), 'height': rect.height()}
ann.update(self.default_properties_)
ann.update(self._default_properties)
image_item.addAnnotation(ann)
self.scene_.removeItem(self.current_item_)
self.current_item_ = None
self.init_pos_ = None
self._scene.removeItem(self._current_item)
self._current_item = None
self._init_pos = None
event.accept()
@@ -80,32 +80,32 @@ class RectItemInserter(ItemInserter):
return True
def abort(self):
if self.current_item_ is not None:
self.scene_.removeItem(self.current_item_)
self.current_item_ = None
self.init_pos_ = None
if self._current_item is not None:
self._scene.removeItem(self._current_item)
self._current_item = None
self._init_pos = None
ItemInserter.abort(self)
class FixedRatioRectItemInserter(RectItemInserter):
def __init__(self, labeltool, scene, default_properties=None):
RectItemInserter.__init__(self, labeltool, scene, default_properties)
self.ratio_ = 1
self._ratio = 1
if default_properties is not None:
self.ratio_ = float(default_properties.get('_ratio', 1))
self._ratio = float(default_properties.get('_ratio', 1))
def mouseMoveEvent(self, event, image_item):
if self.current_item_ is not None:
new_geometry = QRectF(self.current_item_.rect().topLeft(), event.scenePos())
if self._current_item is not None:
new_geometry = QRectF(self._current_item.rect().topLeft(), event.scenePos())
dx = new_geometry.width()
dy = new_geometry.height()
d = math.sqrt(dx*dx + dy*dy)
r = self.ratio_
r = self._ratio
k = math.sqrt(r*r+1)
h = d/k
w = d*r/k
new_geometry.setWidth(w)
new_geometry.setHeight(h)
self.current_item_.setRect(new_geometry.normalized())
self._current_item.setRect(new_geometry.normalized())
event.accept()
@@ -113,28 +113,28 @@ class FixedRatioRectItemInserter(RectItemInserter):
class PolygonItemInserter(ItemInserter):
def __init__(self, scene, mode=None):
ItemInserter.__init__(self, scene, mode)
self.current_item_ = None
self._current_item = None
def mousePressEvent(self, event, image_item):
pos = event.scenePos()
if self.current_item_ is None:
if self._current_item is None:
item = QGraphicsPolygonItem(QPolygonF([pos]))
self.current_item_ = item
self.scene_.addItem(item)
self._current_item = item
self._scene.addItem(item)
else:
polygon = self.current_item_.polygon()
polygon = self._current_item.polygon()
polygon.append(pos)
self.current_item_.setPolygon(polygon)
self._current_item.setPolygon(polygon)
event.accept()
def mouseMoveEvent(self, event, image_item):
if self.current_item_ is not None:
if self._current_item is not None:
pos = event.scenePos()
polygon = self.current_item_.polygon()
polygon = self._current_item.polygon()
assert polygon.size() > 0
polygon[-1] = pos
self.current_item_.setPolygon(polygon)
self._current_item.setPolygon(polygon)
event.accept()
+36 -36
View File
@@ -32,9 +32,9 @@ class BaseItem(QAbstractGraphicsShapeItem):
self.changeColor()
# initialize members
self.text_ = ""
self.text_bg_brush_ = None
self.auto_text_keys_ = []
self._text = ""
self._text_bg_brush = None
self._auto_text_keys = []
def changeColor(self):
if self._model_item is not None:
@@ -64,10 +64,10 @@ class BaseItem(QAbstractGraphicsShapeItem):
"""
Sets a text to be displayed on this item.
"""
self.text_ = text
self._text = text
def text(self):
return self.text_
return self._text
def setTextBackgroundBrush(self, brush=None):
"""
@@ -75,33 +75,33 @@ class BaseItem(QAbstractGraphicsShapeItem):
behind the text. Set to None to not draw a background
(leave transparent).
"""
self.text_bg_brush_ = brush
self._text_bg_brush = brush
def textBackgroundBrush(self):
"""
Returns the background brush for the text region.
"""
return self.text_bg_brush_
return self._text_bg_brush
def setAutoTextKeys(self, keys=[]):
"""
Sets the keys for which the values from the annotations
are displayed automatically as text.
"""
self.auto_text_keys_ = keys
self._auto_text_keys = keys
def autoTextKeys(self):
"""
Returns the list of keys for which the values from
the annotations are displayed as text automatically.
"""
return self.auto_text_keys_
return self._auto_text_keys
def _compile_text(self):
text_lines = []
if self.text_ != "" and self.text_ is not None:
text_lines.append(self.text_)
for key in self.auto_text_keys_:
if self._text != "" and self._text is not None:
text_lines.append(self._text)
for key in self._auto_text_keys:
text_lines.append("%s: %s" % \
(key, self._model_item.get(key, "")))
return '\n'.join(text_lines)
@@ -127,9 +127,9 @@ class BaseItem(QAbstractGraphicsShapeItem):
QRect(5, 5, 1000, 1000), Qt.AlignTop | Qt.AlignLeft, text)
# fill background region behind text
if self.text_bg_brush_ is not None:
if self._text_bg_brush is not None:
bg_rect = rect.adjusted(-3, -3, 3, 3)
painter.fillRect(bg_rect, self.text_bg_brush_)
painter.fillRect(bg_rect, self._text_bg_brush)
painter.drawText(rect, Qt.AlignTop | Qt.AlignLeft, text)
painter.restore()
@@ -156,22 +156,22 @@ class PointItem(BaseItem):
def __init__(self, model_item=None, parent=None):
BaseItem.__init__(self, model_item, parent)
self.radius_ = 2
self.point_ = None
self._radius = 2
self._point = None
self.updatePoint()
def setRadius(self, radius):
self.radius_ = radius
self._radius = radius
self.update()
def radius(self):
return self.radius_
return self._radius
def __call__(self, model_item=None, parent=None):
pointitem = PointItem(model_item, parent)
pointitem.setPen(self.pen())
pointitem.setBrush(self.brush())
pointitem.setRadius(self.radius_)
pointitem.setRadius(self._radius)
return pointitem
def dataChange(self):
@@ -189,15 +189,15 @@ class PointItem(BaseItem):
point = QPointF(float(self._model_item['x']),
float(self._model_item['y']))
if point == self.point_:
if point == self._point:
return
self.point_ = point
self._point = point
self.prepareGeometryChange()
self.setPos(self.point_)
self.setPos(self._point)
def boundingRect(self):
r = self.radius_
r = self._radius
return QRectF(-r, -r, 2 * r, 2 * r)
def paint(self, painter, option, widget=None):
@@ -227,13 +227,13 @@ class RectItem(BaseItem):
def __init__(self, model_item=None, parent=None):
BaseItem.__init__(self, model_item, parent)
self.rect_ = None
self._rect = None
self._resize = False
self._resize_start = None
self._resize_start_rect = None
self._updateRect(self._dataToRect(self._model_item))
LOG.debug("Constructed rect %s for model item %s" % (self.rect_, model_item))
LOG.debug("Constructed rect %s for model item %s" % (self._rect, model_item))
def __call__(self, model_item=None, parent=None):
item = RectItem(model_item, parent)
@@ -248,24 +248,24 @@ class RectItem(BaseItem):
float(model_item['width']), float(model_item['height']))
def _updateRect(self, rect):
if rect == self.rect_:
if rect == self._rect:
return
self.rect_ = rect
self._rect = rect
self.prepareGeometryChange()
self.setPos(rect.topLeft())
def updateModel(self):
self.rect_ = QRectF(self.scenePos(), self.rect_.size())
self._rect = QRectF(self.scenePos(), self._rect.size())
self._model_item.update({
'x': float(self.rect_.topLeft().x()),
'y': float(self.rect_.topLeft().y()),
'width': float(self.rect_.width()),
'height': float(self.rect_.height()),
'x': float(self._rect.topLeft().x()),
'y': float(self._rect.topLeft().y()),
'width': float(self._rect.width()),
'height': float(self._rect.height()),
})
def boundingRect(self):
return QRectF(QPointF(0, 0), self.rect_.size())
return QRectF(QPointF(0, 0), self._rect.size())
def paint(self, painter, option, widget=None):
BaseItem.paint(self, painter, option, widget)
@@ -285,7 +285,7 @@ class RectItem(BaseItem):
if event.button() & Qt.RightButton != 0:
self._resize = True
self._resize_start = event.scenePos()
self._resize_start_rect = QRectF(self.rect_)
self._resize_start_rect = QRectF(self._rect)
event.accept()
else:
BaseItem.mousePressEvent(self, event)
@@ -318,9 +318,9 @@ class RectItem(BaseItem):
}.get(event.key(), None)
if ds is not None:
if event.modifiers() & Qt.ControlModifier:
rect = self.rect_.adjusted(*((0, 0) + ds))
rect = self._rect.adjusted(*((0, 0) + ds))
else:
rect = self.rect_.adjusted(*(ds + ds))
rect = self._rect.adjusted(*(ds + ds))
self._updateRect(rect)
self.updateModel()
event.accept()