Results 1 to 5 of 5

Thread: Segmentation fault when move a group item (combining a rectangle and a point) in QT

  1. #1
    Join Date
    Jul 2017
    Posts
    6
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Segmentation fault when move a group item (combining a rectangle and a point) in

    There are 3 items. Rectangle, Point, BBoxFaceItem (combining rectangle and points)
    There is no problem when I draw rectangle, point in 3 images, then move, resize, everything is good.
    But app will crash if I group these two together as BBoxFaceItem, firstly I draw one BBoxFaceItem on image 1, then move this BBoxFaceItem, then click image 2, whole app will crash.

    One messageBox pops up syaing python.exe has stopped working.
    And in the console, it says segmentation fault.

    Thanks a lot for your help, appreciate your comments.

    Below code is just part of app.

    Qt Code:
    1. """
    2. Base class for visualization items.
    3. """
    4.  
    5. cycleValuesOnKeypress = {}
    6. hotkeys = {}
    7. defaultAutoTextKeys = []
    8.  
    9. def __init__(self, model_item=None, prefix="", parent=None):
    10. """
    11. Creates a visualization item.
    12. """
    13. QAbstractGraphicsShapeItem.__init__(self, parent)
    14. self.setFlags(QGraphicsItem.ItemIsSelectable |
    15. QGraphicsItem.ItemIsMovable |
    16. QGraphicsItem.ItemSendsGeometryChanges |
    17. QGraphicsItem.ItemSendsScenePositionChanges)
    18.  
    19. self._model_item = model_item
    20. if self._model_item is not None:
    21. self._model_item.model().dataChanged.connect(self.onDataChanged)
    22.  
    23. # initialize members
    24. self._prefix = prefix
    25. self._auto_text_keys = self.defaultAutoTextKeys[:]
    26. self._text = ""
    27. self._text_bg_brush = None
    28. self._text_item = QGraphicsTextItem(self)
    29. self._text_item.setPos(0, 0)
    30. self._text_item.setAcceptHoverEvents(False)
    31. self._text_item.setFlags(QGraphicsItem.ItemIgnoresTransformations)
    32. self._text_item.setHtml(self._compile_text())
    33. self._valid = True
    34.  
    35. if len(self.cycleValuesOnKeypress) > 0:
    36. logging.warning("cycleValueOnKeypress is deprecated and will be removed in the future. " +
    37. "Set BaseItem.hotkeys instead with cycleValue()")
    38.  
    39. self.changeColor()
    40.  
    41. def changeColor(self):
    42. if self._model_item is not None:
    43. c = self._model_item.getColor()
    44. if c is not None:
    45. self.setColor(c)
    46. return
    47. self.setColor(Qt.yellow)
    48.  
    49. def onDataChanged(self, indexFrom, indexTo):
    50. # FIXME why is this not updated, when changed graphically via attribute box ?
    51. #print "onDataChanged", self._model_item.index(), indexFrom, indexTo, indexFrom.parent()
    52. if indexFrom == self._model_item.index():
    53. self.changeColor()
    54. #print "hit"
    55. # self._text_item.setHtml(self._compile_text())
    56.  
    57. def modelItem(self):
    58. """
    59. Returns the model item of this items.
    60. """
    61. return self._model_item
    62.  
    63. def index(self):
    64. """
    65. Returns the index of this item.
    66. """
    67. return self._model_item.index()
    68.  
    69. def prefix(self):
    70. """
    71. Returns the key prefix of the item.
    72. """
    73. return self._prefix
    74.  
    75. def setPen(self, pen):
    76. pen = QPen(pen) # convert to pen if argument is a QColor
    77. QAbstractGraphicsShapeItem.setPen(self, pen)
    78. self._text_item.setDefaultTextColor(pen.color())
    79.  
    80. def setText(self, text=""):
    81. """
    82. Sets a text to be displayed on this item.
    83. """
    84. self._text = text
    85. self._text_item.setHtml(self._compile_text())
    86.  
    87. def text(self):
    88. return self._text
    89.  
    90. def setTextBackgroundBrush(self, brush=None):
    91. """
    92. Sets the brush to be used to fill the background region
    93. behind the text. Set to None to not draw a background
    94. (leave transparent).
    95. """
    96. self._text_bg_brush = brush
    97.  
    98. def textBackgroundBrush(self):
    99. """
    100. Returns the background brush for the text region.
    101. """
    102. return self._text_bg_brush
    103.  
    104. def setAutoTextKeys(self, keys=None):
    105. """
    106. Sets the keys for which the values from the annotations
    107. are displayed automatically as text.
    108. """
    109. self._auto_text_keys = keys or []
    110. self._text_item.setHtml(self._compile_text())
    111.  
    112. def autoTextKeys(self):
    113. """
    114. Returns the list of keys for which the values from
    115. the annotations are displayed as text automatically.
    116. """
    117. return self._auto_text_keys
    118.  
    119. def isValid(self):
    120. """
    121. Return whether this graphics item is valid, i.e. has
    122. a matching, valid model item connected to it. An item is
    123. by default valid, will only be set invalid on failure.
    124. """
    125. return self._valid
    126.  
    127. def setValid(self, val):
    128. self._valid = val
    129.  
    130. def _compile_text(self):
    131. text_lines = []
    132. if self._text != "" and self._text is not None:
    133. text_lines.append(self._text)
    134. for key in self._auto_text_keys:
    135. text_lines.append("%s: %s" % \
    136. (key, self._model_item.get(key, "")))
    137. return '<br/>'.join(text_lines)
    138.  
    139. def dataChanged(self):
    140. self.dataChange()
    141. self._text_item.setHtml(self._compile_text())
    142. self.update()
    143.  
    144. def dataChange(self):
    145. pass
    146.  
    147. def updateModel(self, ann=None):
    148. if ann is not None:
    149. self._model_item.update(ann)
    150.  
    151. def boundingRect(self):
    152. return QRectF(0, 0, 0, 0)
    153.  
    154. def setColor(self, color):
    155. self.setPen(color)
    156. self.setBrush(color)
    157. self.update()
    158.  
    159. def paint(self, painter, option, widget=None):
    160. pass
    161.  
    162. def itemChange(self, change, value):
    163. if change == QGraphicsItem.ItemPositionHasChanged:
    164. self.updateModel()
    165. return QAbstractGraphicsShapeItem.itemChange(self, change, value)
    166.  
    167. def keyPressEvent(self, event):
    168. """
    169. This handles the value cycling as defined in cycleValuesOnKeypress.
    170. """
    171. if str(event.text()) in self.cycleValuesOnKeypress:
    172. itemkey, valuelist = self.cycleValuesOnKeypress[str(event.text())]
    173. if isinstance(itemkey, IgnorePrefix):
    174. itemkey = itemkey.value
    175. else:
    176. itemkey = self.prefix() + itemkey
    177. if len(valuelist) > 0:
    178. oldvalue = self._model_item.get(itemkey, None)
    179. if oldvalue is None:
    180. nextindex = 0
    181. else:
    182. try:
    183. nextindex = valuelist.index(oldvalue) + 1
    184. nextindex %= len(valuelist)
    185. except ValueError:
    186. nextindex = 0
    187. newvalue = valuelist[nextindex]
    188. if newvalue is None:
    189. if oldvalue is not None:
    190. self._model_item.delete(itemkey)
    191. else:
    192. self._model_item[itemkey] = valuelist[nextindex]
    193. self.dataChanged()
    194. event.accept()
    195. elif str(event.text()) in self.hotkeys:
    196. self.hotkeys[str(event.text())](self)
    197. event.accept()
    198.  
    199.  
    200. class PointItem(BaseItem):
    201. """
    202. Visualization item for points.
    203. """
    204.  
    205. def __init__(self, model_item=None, prefix="", parent=None):
    206. BaseItem.__init__(self, model_item, prefix, parent)
    207.  
    208. self._radius = 2
    209. self._point = None
    210. self.updatePoint()
    211.  
    212. def setRadius(self, radius):
    213. self.prepareGeometryChange()
    214. self._radius = radius
    215. self.update()
    216.  
    217. def radius(self):
    218. return self._radius
    219.  
    220. def __call__(self, model_item=None, parent=None):
    221. pointitem = PointItem(model_item, parent)
    222. pointitem.setPen(self.pen())
    223. pointitem.setBrush(self.brush())
    224. pointitem.setRadius(self._radius)
    225. return pointitem
    226.  
    227. def dataChange(self):
    228. self.updatePoint()
    229.  
    230. def updateModel(self):
    231. self._model_item.update({
    232. self.prefix() + 'x': self.scenePos().x(),
    233. self.prefix() + 'y': self.scenePos().y(),
    234. })
    235.  
    236. def updatePoint(self):
    237. if self._model_item is None:
    238. return
    239.  
    240. try:
    241. point = QPointF(float(self._model_item[self.prefix() + 'x']),
    242. float(self._model_item[self.prefix() + 'y']))
    243. except KeyError as e:
    244. LOG.debug("PointItem: Could not find expected key in item: "
    245. + str(e) + ". Check your config!")
    246. self.setValid(False)
    247. self._point = None
    248. return
    249.  
    250. if point == self._point:
    251. return
    252.  
    253. self.prepareGeometryChange()
    254. self._point = point
    255. self.setPos(self._point)
    256.  
    257. def boundingRect(self):
    258. r = self._radius
    259. return QRectF(-r, -r, 2 * r, 2 * r)
    260.  
    261. def paint(self, painter, option, widget=None):
    262. BaseItem.paint(self, painter, option, widget)
    263.  
    264. pen = self.pen()
    265. if self.isSelected():
    266. pen.setStyle(Qt.DashLine)
    267. painter.setPen(pen)
    268. painter.drawEllipse(self.boundingRect())
    269.  
    270. def keyPressEvent(self, event):
    271. BaseItem.keyPressEvent(self, event)
    272. step = 1
    273. if event.modifiers() & Qt.ShiftModifier:
    274. step = 5
    275. ds = {Qt.Key_Left: (-step, 0),
    276. Qt.Key_Right: (step, 0),
    277. Qt.Key_Up: (0, -step),
    278. Qt.Key_Down: (0, step)
    279. }.get(event.key(), None)
    280. if ds is not None:
    281. self.moveBy(*ds)
    282. event.accept()
    To copy to clipboard, switch view to plain text mode 



    Not done yet, see next reply

    Qt Code:
    1. class RectItem(BaseItem):
    2. def __init__(self, model_item=None, prefix="", parent=None):
    3. BaseItem.__init__(self, model_item, prefix, parent)
    4.  
    5. self._rect = None
    6. self._resize = False
    7. self._resize_start = None
    8. self._resize_start_rect = None
    9. self._upper_half_clicked = None
    10. self._left_half_clicked = None
    11.  
    12. self._updateRect(self._dataToRect(self._model_item))
    13. LOG.debug("Constructed rect %s for model item %s" %
    14. (self._rect, model_item))
    15.  
    16. def __call__(self, model_item=None, parent=None):
    17. item = RectItem(model_item, parent)
    18. item.setPen(self.pen())
    19. item.setBrush(self.brush())
    20. return item
    21.  
    22. def _dataToRect(self, model_item):
    23. if model_item is None:
    24. return QRectF()
    25.  
    26. try:
    27. return QRectF(float(model_item[self.prefix() + 'x']),
    28. float(model_item[self.prefix() + 'y']),
    29. float(model_item[self.prefix() + 'width']),
    30. float(model_item[self.prefix() + 'height']))
    31. except KeyError as e:
    32. LOG.debug("RectItem: Could not find expected key in item: "
    33. + str(e) + ". Check your config!")
    34. self.setValid(False)
    35. return QRectF()
    36.  
    37. def _updateRect(self, rect):
    38. if rect == self._rect:
    39. return
    40.  
    41. self.prepareGeometryChange()
    42. self._rect = rect
    43. self.setPos(rect.topLeft())
    44.  
    45. def updateModel(self):
    46. self._rect = QRectF(self.scenePos(), self._rect.size())
    47. self._model_item.update({
    48. self.prefix() + 'x': float(self._rect.topLeft().x()),
    49. self.prefix() + 'y': float(self._rect.topLeft().y()),
    50. self.prefix() + 'width': float(self._rect.width()),
    51. self.prefix() + 'height': float(self._rect.height()),
    52. })
    53.  
    54. def boundingRect(self):
    55. return QRectF(QPointF(0, 0), self._rect.size())
    56.  
    57. def paint(self, painter, option, widget=None):
    58. BaseItem.paint(self, painter, option, widget)
    59.  
    60. pen = self.pen()
    61. if self.isSelected():
    62. pen.setStyle(Qt.DashLine)
    63. painter.setPen(pen)
    64. painter.drawRect(self.boundingRect())
    65.  
    66. def dataChange(self):
    67. rect = self._dataToRect(self._model_item)
    68. self._updateRect(rect)
    69.  
    70. def mousePressEvent(self, event):
    71. #if event.modifiers() & Qt.ControlModifier != 0:
    72. if event.button() & Qt.RightButton != 0:
    73. self._resize = True
    74. self._resize_start = event.scenePos()
    75. self._resize_start_rect = QRectF(self._rect)
    76. self._upper_half_clicked = (event.scenePos().y() < self._resize_start_rect.center().y())
    77. self._left_half_clicked = (event.scenePos().x() < self._resize_start_rect.center().x())
    78. event.accept()
    79. else:
    80. BaseItem.mousePressEvent(self, event)
    81.  
    82. def mouseMoveEvent(self, event):
    83. if self._resize:
    84. diff = event.scenePos() - self._resize_start
    85. if self._left_half_clicked:
    86. x = self._resize_start_rect.x() + diff.x()
    87. w = self._resize_start_rect.width() - diff.x()
    88. else:
    89. x = self._resize_start_rect.x()
    90. w = self._resize_start_rect.width() + diff.x()
    91.  
    92. if self._upper_half_clicked:
    93. y = self._resize_start_rect.y() + diff.y()
    94. h = self._resize_start_rect.height() - diff.y()
    95. else:
    96. y = self._resize_start_rect.y()
    97. h = self._resize_start_rect.height() + diff.y()
    98.  
    99. rect = QRectF(QPointF(x,y), QSizeF(w, h)).normalized()
    100.  
    101. self._updateRect(rect)
    102. self.updateModel()
    103. event.accept()
    104. else:
    105. BaseItem.mouseMoveEvent(self, event)
    106.  
    107. def mouseReleaseEvent(self, event):
    108. if self._resize:
    109. self._resize = False
    110. event.accept()
    111. else:
    112. BaseItem.mouseReleaseEvent(self, event)
    113.  
    114. def keyPressEvent(self, event):
    115. BaseItem.keyPressEvent(self, event)
    116. step = 1
    117. if event.modifiers() & Qt.ShiftModifier:
    118. step = 5
    119. ds = {Qt.Key_Left: (-step, 0),
    120. Qt.Key_Right: (step, 0),
    121. Qt.Key_Up: (0, -step),
    122. Qt.Key_Down: (0, step),
    123. }.get(event.key(), None)
    124. if ds is not None:
    125. if event.modifiers() & Qt.ControlModifier:
    126. rect = self._rect.adjusted(*((0, 0) + ds))
    127. else:
    128. rect = self._rect.adjusted(*(ds + ds))
    129. self._updateRect(rect)
    130. self.updateModel()
    131. event.accept()
    132.  
    133. class GroupItem(BaseItem):
    134. items = []
    135.  
    136. def __init__(self, model_item=None, prefix="", parent=None):
    137. self._children = []
    138. BaseItem.__init__(self, model_item, prefix, parent)
    139. self.setFlag(QGraphicsItem.ItemIsMovable, False)
    140.  
    141. self.createChildren()
    142.  
    143. def createChildren(self):
    144. for callable_, prefix in self.items:
    145. child = callable_(self._model_item, prefix, self)
    146. self._children.append(child)
    147.  
    148. def setColor(self, *args, **kwargs):
    149. for c in self._children:
    150. c.setColor(*args, **kwargs)
    151. BaseItem.setColor(self, *args, **kwargs)
    152.  
    153. def boundingRect(self):
    154. br = QRectF()
    155. for item in self.childItems():
    156. if item is self._text_item:
    157. continue
    158. br |= item.mapRectToParent(item.boundingRect())
    159. return br
    160.  
    161.  
    162. class OccludablePointItem(PointItem):
    163. hotkeys = {
    164. 'o': cycleValue('occluded', [True, False])
    165. }
    166.  
    167. def __init__(self, *args, **kwargs):
    168. PointItem.__init__(self, *args, **kwargs)
    169. self.updateColor()
    170.  
    171. def dataChange(self):
    172. PointItem.dataChange(self)
    173. self.updateColor()
    174.  
    175. def updateColor(self):
    176. key = self.prefix() + 'occluded'
    177. if key in self._model_item:
    178. occluded = self._model_item[key]
    179. self.setColor(Qt.red if occluded else Qt.yellow)
    180.  
    181.  
    182. class BBoxFaceItem(GroupItem):
    183. items = [
    184. (IDRectItem, "bbox"),
    185. (OccludablePointItem, "lec"),
    186. (OccludablePointItem, "rec"),
    187. (OccludablePointItem, "mc"),
    188. ]
    To copy to clipboard, switch view to plain text mode 



    The full code is here,
    https://github.com/cvhciKIT/sloth

    All the changes I make is adding below lines in sloth/conf/default_config.py
    from line 73-80
    Qt Code:
    1. {
    2. 'attributes': {
    3. 'class': 'bbx', "id" : ["0", "1"]
    4. },
    5. 'inserter': 'sloth.items.BBoxFaceInserter',
    6. 'item': 'sloth.items.BBoxFaceItem',
    7. 'text': 'bbx',
    8. },
    To copy to clipboard, switch view to plain text mode 


    Added after 1 29 minutes:


    I am suspecting when I move the BBoxFaceItem, something is corrupted. I haven't figured out why.
    Last edited by helloworld12345; 14th July 2017 at 02:21.

  2. #2
    Join Date
    Jan 2006
    Location
    Munich, Germany
    Posts
    4,714
    Thanks
    21
    Thanked 418 Times in 411 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows

    Default Re: Segmentation fault when move a group item (combining a rectangle and a point) in

    Run with a debugger - and see which line is the one causing the crash.
    This will give you a major hint whats wrong.
    ==========================signature=============== ==================
    S.O.L.I.D principles (use them!):
    https://en.wikipedia.org/wiki/SOLID_...iented_design)

    Do you write clean code? - if you are TDD'ing then maybe, if not, your not writing clean code.

  3. #3
    Join Date
    Jul 2017
    Posts
    6
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Segmentation fault when move a group item (combining a rectangle and a point) in

    Quote Originally Posted by high_flyer View Post
    Run with a debugger - and see which line is the one causing the crash.
    This will give you a major hint whats wrong.
    Hi high_flyer,
    I am using pycharm to debug, I can't find the line that causes the crash.

    Before crashing, it will reach this line below.
    sys.exit(app.exec_())

    Then
    If I stop over(one step), it will crash.
    If I step into, it will never reach to the crash line, seems it goes through many callback code, but never to the line causing crash.

  4. #4
    Join Date
    Jan 2006
    Location
    Munich, Germany
    Posts
    4,714
    Thanks
    21
    Thanked 418 Times in 411 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows

    Default Re: Segmentation fault when move a group item (combining a rectangle and a point) in

    Are you running a debug build?
    ==========================signature=============== ==================
    S.O.L.I.D principles (use them!):
    https://en.wikipedia.org/wiki/SOLID_...iented_design)

    Do you write clean code? - if you are TDD'ing then maybe, if not, your not writing clean code.

  5. #5
    Join Date
    Jul 2017
    Posts
    6
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Segmentation fault when move a group item (combining a rectangle and a point) in

    Quote Originally Posted by high_flyer View Post
    Are you running a debug build?
    Yes, I run with debug mode, otherwise I can't run step by step.

    But I figured out how to solve it.
    As I stated at the beginning. I have 1 rectangle, 1 point and 1 group item(combing rectangle and point)
    sole rectangle and point work good, but group item doesn't.

    Each of these 3 items have their own boundingRect, after I removed the boundingRect of the group item, the crash issue is fixed.
    it seems like the boundingRect in group item conflicts with the ones in sole rectangle and sole point.

Similar Threads

  1. Replies: 5
    Last Post: 17th July 2014, 09:23
  2. Replies: 0
    Last Post: 2nd November 2010, 19:54
  3. A QComboBox item produces segmentation fault when used
    By prykHetQuo in forum Qt Programming
    Replies: 3
    Last Post: 19th March 2009, 00:13
  4. Starting Point of Rectangle in RubberBand implementation
    By cdemirkir in forum Qt Programming
    Replies: 4
    Last Post: 10th July 2007, 16:05
  5. Move Rectangle on mouse Move
    By vermarajeev in forum Qt Programming
    Replies: 24
    Last Post: 14th May 2007, 06:34

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.