We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
LegendItem.setParentItem fails when no offset is provided
### Short description
In the current development version, calling setParentItem() on a LegendItem without offset results in an exception and crash.
This is because the offset value seems now to be saved in self.opts["offset"] while it was in self.offset before.
Right now setParentItem() checks if an offset exists by checking in the wrong place but uses the right offset afterwards. If no offset is set, a crash ensues
```python
if self.offset is not None:
            offset = Point(self.opts['offset'])
```
Changing to the following code fixes the problem:
```python
if self.opts['offset'] is not None:
            offset = Point(self.opts['offset'])
```


### Code to reproduce
<!-- Please provide a minimal working example that reproduces the issue in the code block below.
     Ideally, this should be a full example someone else could run without additional setup. -->
```python
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui

plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: Legend')
l = pg.LegendItem((100, 60))
l.setParentItem(plt.graphicsItem())


# Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
```

### Expected behavior
The plot should be displayed normally

### Real behavior
The following exception occurs:

```
Traceback (most recent call last):
  File "/home/vin/test/testlegend.py", line 7, in <module>
    l.setParentItem(plt.graphicsItem())
  File "/home/vin/miniconda3/lib/python3.7/site-packages/pyqtgraph/graphicsItems/LegendItem.py", line 128, in setParentItem
    offset = Point(self.opts['offset'])
  File "/home/vin/miniconda3/lib/python3.7/site-packages/pyqtgraph/Point.py", line 35, in __init__
    QtCore.QPointF.__init__(self, *args)
TypeError: arguments did not match any overloaded call:
  QPointF(): too many arguments
  QPointF(float, float): argument 1 has unexpected type 'NoneType'
  QPointF(QPoint): argument 1 has unexpected type 'NoneType'
  QPointF(QPointF): argument 1 has unexpected type 'NoneType'

```

### Tested environment(s)

 * PyQtGraph version: 0.11.0.dev0+gdb483f8
 * Qt Python binding: PyQt5 5.13.0 Qt 5.13.0 (same problem with PySide2 5.12.2 Qt 5.12.2)
 * Python version: 3.7
 * NumPy version: 1.17.3
 * Operating system: Linux Mint 19.1
 * Installation method: pip from latest github version



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pyqtgraph/graphicsItems/LegendItem.py`
Content:
```
1 from .GraphicsWidget import GraphicsWidget
2 from .LabelItem import LabelItem
3 from ..Qt import QtGui, QtCore
4 from .. import functions as fn
5 from ..Point import Point
6 from .ScatterPlotItem import ScatterPlotItem, drawSymbol
7 from .PlotDataItem import PlotDataItem
8 from .GraphicsWidgetAnchor import GraphicsWidgetAnchor
9 __all__ = ['LegendItem']
10 
11 
12 class LegendItem(GraphicsWidget, GraphicsWidgetAnchor):
13     """
14     Displays a legend used for describing the contents of a plot.
15     LegendItems are most commonly created by calling PlotItem.addLegend().
16 
17     Note that this item should not be added directly to a PlotItem. Instead,
18     Make it a direct descendant of the PlotItem::
19 
20         legend.setParentItem(plotItem)
21 
22     """
23     def __init__(self, size=None, offset=None, horSpacing=25, verSpacing=0, pen=None,
24                  brush=None, labelTextColor=None, **kwargs):
25         """
26         ==============  ===============================================================
27         **Arguments:**
28         size            Specifies the fixed size (width, height) of the legend. If
29                         this argument is omitted, the legend will automatically resize
30                         to fit its contents.
31         offset          Specifies the offset position relative to the legend's parent.
32                         Positive values offset from the left or top; negative values
33                         offset from the right or bottom. If offset is None, the
34                         legend must be anchored manually by calling anchor() or
35                         positioned by calling setPos().
36         horSpacing      Specifies the spacing between the line symbol and the label.
37         verSpacing      Specifies the spacing between individual entries of the legend
38                         vertically. (Can also be negative to have them really close)
39         pen             Pen to use when drawing legend border. Any single argument
40                         accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed.
41         brush           QBrush to use as legend background filling. Any single argument
42                         accepted by :func:`mkBrush <pyqtgraph.mkBrush>` is allowed.
43         labelTextColor  Pen to use when drawing legend text. Any single argument
44                         accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed.
45         ==============  ===============================================================
46 
47         """
48 
49 
50         GraphicsWidget.__init__(self)
51         GraphicsWidgetAnchor.__init__(self)
52         self.setFlag(self.ItemIgnoresTransformations)
53         self.layout = QtGui.QGraphicsGridLayout()
54         self.layout.setVerticalSpacing(verSpacing)
55         self.layout.setHorizontalSpacing(horSpacing)
56 
57         self.setLayout(self.layout)
58         self.items = []
59         self.size = size
60         if size is not None:
61             self.setGeometry(QtCore.QRectF(0, 0, self.size[0], self.size[1]))
62 
63         self.opts = {
64             'pen': fn.mkPen(pen),
65             'brush': fn.mkBrush(brush),
66             'labelTextColor': labelTextColor,
67             'offset': offset,
68         }
69 
70         self.opts.update(kwargs)
71 
72     def offset(self):
73         return self.opts['offset']
74 
75     def setOffset(self, offset):
76         self.opts['offset'] = offset
77 
78         offset = Point(self.opts['offset'])
79         anchorx = 1 if offset[0] <= 0 else 0
80         anchory = 1 if offset[1] <= 0 else 0
81         anchor = (anchorx, anchory)
82         self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)
83 
84     def pen(self):
85         return self.opts['pen']
86 
87     def setPen(self, *args, **kargs):
88         """
89         Sets the pen used to draw lines between points.
90         *pen* can be a QPen or any argument accepted by
91         :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`
92         """
93         pen = fn.mkPen(*args, **kargs)
94         self.opts['pen'] = pen
95 
96         self.paint()
97 
98     def brush(self):
99         return self.opts['brush']
100 
101     def setBrush(self, *args, **kargs):
102         brush = fn.mkBrush(*args, **kargs)
103         if self.opts['brush'] == brush:
104             return
105         self.opts['brush'] = brush
106 
107         self.paint()
108 
109     def labelTextColor(self):
110         return self.opts['labelTextColor']
111 
112     def setLabelTextColor(self, *args, **kargs):
113         """
114         Sets the color of the label text.
115         *pen* can be a QPen or any argument accepted by
116         :func:`pyqtgraph.mkColor() <pyqtgraph.mkPen>`
117         """
118         self.opts['labelTextColor'] = fn.mkColor(*args, **kargs)
119         for sample, label in self.items:
120             label.setAttr('color', self.opts['labelTextColor'])
121 
122         self.paint()
123 
124     def setParentItem(self, p):
125         ret = GraphicsWidget.setParentItem(self, p)
126         if self.offset is not None:
127             offset = Point(self.opts['offset'])
128             anchorx = 1 if offset[0] <= 0 else 0
129             anchory = 1 if offset[1] <= 0 else 0
130             anchor = (anchorx, anchory)
131             self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)
132         return ret
133 
134     def addItem(self, item, name):
135         """
136         Add a new entry to the legend.
137 
138         ==============  ========================================================
139         **Arguments:**
140         item            A PlotDataItem from which the line and point style
141                         of the item will be determined or an instance of
142                         ItemSample (or a subclass), allowing the item display
143                         to be customized.
144         title           The title to display for this item. Simple HTML allowed.
145         ==============  ========================================================
146         """
147         label = LabelItem(name, color=self.opts['labelTextColor'], justify='left')
148         if isinstance(item, ItemSample):
149             sample = item
150         else:
151             sample = ItemSample(item)
152 
153         row = self.layout.rowCount()
154         self.items.append((sample, label))
155         self.layout.addItem(sample, row, 0)
156         self.layout.addItem(label, row, 1)
157         self.updateSize()
158 
159     def removeItem(self, item):
160         """
161         Removes one item from the legend.
162 
163         ==============  ========================================================
164         **Arguments:**
165         item            The item to remove or its name.
166         ==============  ========================================================
167         """
168         for sample, label in self.items:
169             if sample.item is item or label.text == item:
170                 self.items.remove((sample, label))      # remove from itemlist
171                 self.layout.removeItem(sample)          # remove from layout
172                 sample.close()                          # remove from drawing
173                 self.layout.removeItem(label)
174                 label.close()
175                 self.updateSize()                       # redraq box
176                 return                                  # return after first match
177 
178     def clear(self):
179         """Removes all items from legend."""
180         for sample, label in self.items:
181             self.layout.removeItem(sample)
182             self.layout.removeItem(label)
183 
184         self.items = []
185         self.updateSize()
186 
187     def clear(self):
188         """
189         Removes all items from the legend.
190 
191         Useful for reusing and dynamically updating charts and their legends.
192         """
193         while self.items != []:
194             self.removeItem(self.items[0][1].text)
195                 
196     def updateSize(self):
197         if self.size is not None:
198             return
199 
200         self.setGeometry(0, 0, 0, 0)
201 
202     def boundingRect(self):
203         return QtCore.QRectF(0, 0, self.width(), self.height())
204 
205     def paint(self, p, *args):
206         p.setPen(self.opts['pen'])
207         p.setBrush(self.opts['brush'])
208         p.drawRect(self.boundingRect())
209 
210     def hoverEvent(self, ev):
211         ev.acceptDrags(QtCore.Qt.LeftButton)
212 
213     def mouseDragEvent(self, ev):
214         if ev.button() == QtCore.Qt.LeftButton:
215             ev.accept()
216             dpos = ev.pos() - ev.lastPos()
217             self.autoAnchor(self.pos() + dpos)
218 
219 
220 class ItemSample(GraphicsWidget):
221     """ Class responsible for drawing a single item in a LegendItem (sans label).
222 
223     This may be subclassed to draw custom graphics in a Legend.
224     """
225     ## Todo: make this more generic; let each item decide how it should be represented.
226     def __init__(self, item):
227         GraphicsWidget.__init__(self)
228         self.item = item
229 
230     def boundingRect(self):
231         return QtCore.QRectF(0, 0, 20, 20)
232 
233     def paint(self, p, *args):
234         opts = self.item.opts
235 
236         if opts['antialias']:
237             p.setRenderHint(p.Antialiasing)
238 
239         if not isinstance(self.item, ScatterPlotItem):
240             p.setPen(fn.mkPen(opts['pen']))
241             p.drawLine(0, 11, 20, 11)
242 
243         symbol = opts.get('symbol', None)
244         if symbol is not None:
245             if isinstance(self.item, PlotDataItem):
246                 opts = self.item.scatter.opts
247 
248             pen = fn.mkPen(opts['pen'])
249             brush = fn.mkBrush(opts['brush'])
250             size = opts['size']
251 
252             p.translate(10, 10)
253             path = drawSymbol(p, symbol, size, pen, brush)
254 
255 
256 
257 
258
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pyqtgraph/graphicsItems/LegendItem.py b/pyqtgraph/graphicsItems/LegendItem.py
--- a/pyqtgraph/graphicsItems/LegendItem.py
+++ b/pyqtgraph/graphicsItems/LegendItem.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 from .GraphicsWidget import GraphicsWidget
 from .LabelItem import LabelItem
 from ..Qt import QtGui, QtCore
@@ -123,7 +124,7 @@
 
     def setParentItem(self, p):
         ret = GraphicsWidget.setParentItem(self, p)
-        if self.offset is not None:
+        if self.opts['offset'] is not None:
             offset = Point(self.opts['offset'])
             anchorx = 1 if offset[0] <= 0 else 0
             anchory = 1 if offset[1] <= 0 else 0
@@ -251,7 +252,3 @@
 
             p.translate(10, 10)
             path = drawSymbol(p, symbol, size, pen, brush)
-
-
-
-

{"golden_diff": "diff --git a/pyqtgraph/graphicsItems/LegendItem.py b/pyqtgraph/graphicsItems/LegendItem.py\n--- a/pyqtgraph/graphicsItems/LegendItem.py\n+++ b/pyqtgraph/graphicsItems/LegendItem.py\n@@ -1,3 +1,4 @@\n+# -*- coding: utf-8 -*-\n from .GraphicsWidget import GraphicsWidget\n from .LabelItem import LabelItem\n from ..Qt import QtGui, QtCore\n@@ -123,7 +124,7 @@\n \n     def setParentItem(self, p):\n         ret = GraphicsWidget.setParentItem(self, p)\n-        if self.offset is not None:\n+        if self.opts['offset'] is not None:\n             offset = Point(self.opts['offset'])\n             anchorx = 1 if offset[0] <= 0 else 0\n             anchory = 1 if offset[1] <= 0 else 0\n@@ -251,7 +252,3 @@\n \n             p.translate(10, 10)\n             path = drawSymbol(p, symbol, size, pen, brush)\n-\n-\n-\n-\n", "issue": "LegendItem.setParentItem fails when no offset is provided\n### Short description\r\nIn the current development version, calling setParentItem() on a LegendItem without offset results in an exception and crash.\r\nThis is because the offset value seems now to be saved in self.opts[\"offset\"] while it was in self.offset before.\r\nRight now setParentItem() checks if an offset exists by checking in the wrong place but uses the right offset afterwards. If no offset is set, a crash ensues\r\n```python\r\nif self.offset is not None:\r\n            offset = Point(self.opts['offset'])\r\n```\r\nChanging to the following code fixes the problem:\r\n```python\r\nif self.opts['offset'] is not None:\r\n            offset = Point(self.opts['offset'])\r\n```\r\n\r\n\r\n### Code to reproduce\r\n<!-- Please provide a minimal working example that reproduces the issue in the code block below.\r\n     Ideally, this should be a full example someone else could run without additional setup. -->\r\n```python\r\nimport pyqtgraph as pg\r\nfrom pyqtgraph.Qt import QtCore, QtGui\r\n\r\nplt = pg.plot()\r\nplt.setWindowTitle('pyqtgraph example: Legend')\r\nl = pg.LegendItem((100, 60))\r\nl.setParentItem(plt.graphicsItem())\r\n\r\n\r\n# Start Qt event loop unless running in interactive mode or using pyside.\r\nif __name__ == '__main__':\r\n    import sys\r\n    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\r\n        QtGui.QApplication.instance().exec_()\r\n```\r\n\r\n### Expected behavior\r\nThe plot should be displayed normally\r\n\r\n### Real behavior\r\nThe following exception occurs:\r\n\r\n```\r\nTraceback (most recent call last):\r\n  File \"/home/vin/test/testlegend.py\", line 7, in <module>\r\n    l.setParentItem(plt.graphicsItem())\r\n  File \"/home/vin/miniconda3/lib/python3.7/site-packages/pyqtgraph/graphicsItems/LegendItem.py\", line 128, in setParentItem\r\n    offset = Point(self.opts['offset'])\r\n  File \"/home/vin/miniconda3/lib/python3.7/site-packages/pyqtgraph/Point.py\", line 35, in __init__\r\n    QtCore.QPointF.__init__(self, *args)\r\nTypeError: arguments did not match any overloaded call:\r\n  QPointF(): too many arguments\r\n  QPointF(float, float): argument 1 has unexpected type 'NoneType'\r\n  QPointF(QPoint): argument 1 has unexpected type 'NoneType'\r\n  QPointF(QPointF): argument 1 has unexpected type 'NoneType'\r\n\r\n```\r\n\r\n### Tested environment(s)\r\n\r\n * PyQtGraph version: 0.11.0.dev0+gdb483f8\r\n * Qt Python binding: PyQt5 5.13.0 Qt 5.13.0 (same problem with PySide2 5.12.2 Qt 5.12.2)\r\n * Python version: 3.7\r\n * NumPy version: 1.17.3\r\n * Operating system: Linux Mint 19.1\r\n * Installation method: pip from latest github version\r\n\r\n\n", "before_files": [{"content": "from .GraphicsWidget import GraphicsWidget\nfrom .LabelItem import LabelItem\nfrom ..Qt import QtGui, QtCore\nfrom .. import functions as fn\nfrom ..Point import Point\nfrom .ScatterPlotItem import ScatterPlotItem, drawSymbol\nfrom .PlotDataItem import PlotDataItem\nfrom .GraphicsWidgetAnchor import GraphicsWidgetAnchor\n__all__ = ['LegendItem']\n\n\nclass LegendItem(GraphicsWidget, GraphicsWidgetAnchor):\n    \"\"\"\n    Displays a legend used for describing the contents of a plot.\n    LegendItems are most commonly created by calling PlotItem.addLegend().\n\n    Note that this item should not be added directly to a PlotItem. Instead,\n    Make it a direct descendant of the PlotItem::\n\n        legend.setParentItem(plotItem)\n\n    \"\"\"\n    def __init__(self, size=None, offset=None, horSpacing=25, verSpacing=0, pen=None,\n                 brush=None, labelTextColor=None, **kwargs):\n        \"\"\"\n        ==============  ===============================================================\n        **Arguments:**\n        size            Specifies the fixed size (width, height) of the legend. If\n                        this argument is omitted, the legend will automatically resize\n                        to fit its contents.\n        offset          Specifies the offset position relative to the legend's parent.\n                        Positive values offset from the left or top; negative values\n                        offset from the right or bottom. If offset is None, the\n                        legend must be anchored manually by calling anchor() or\n                        positioned by calling setPos().\n        horSpacing      Specifies the spacing between the line symbol and the label.\n        verSpacing      Specifies the spacing between individual entries of the legend\n                        vertically. (Can also be negative to have them really close)\n        pen             Pen to use when drawing legend border. Any single argument\n                        accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed.\n        brush           QBrush to use as legend background filling. Any single argument\n                        accepted by :func:`mkBrush <pyqtgraph.mkBrush>` is allowed.\n        labelTextColor  Pen to use when drawing legend text. Any single argument\n                        accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed.\n        ==============  ===============================================================\n\n        \"\"\"\n\n\n        GraphicsWidget.__init__(self)\n        GraphicsWidgetAnchor.__init__(self)\n        self.setFlag(self.ItemIgnoresTransformations)\n        self.layout = QtGui.QGraphicsGridLayout()\n        self.layout.setVerticalSpacing(verSpacing)\n        self.layout.setHorizontalSpacing(horSpacing)\n\n        self.setLayout(self.layout)\n        self.items = []\n        self.size = size\n        if size is not None:\n            self.setGeometry(QtCore.QRectF(0, 0, self.size[0], self.size[1]))\n\n        self.opts = {\n            'pen': fn.mkPen(pen),\n            'brush': fn.mkBrush(brush),\n            'labelTextColor': labelTextColor,\n            'offset': offset,\n        }\n\n        self.opts.update(kwargs)\n\n    def offset(self):\n        return self.opts['offset']\n\n    def setOffset(self, offset):\n        self.opts['offset'] = offset\n\n        offset = Point(self.opts['offset'])\n        anchorx = 1 if offset[0] <= 0 else 0\n        anchory = 1 if offset[1] <= 0 else 0\n        anchor = (anchorx, anchory)\n        self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)\n\n    def pen(self):\n        return self.opts['pen']\n\n    def setPen(self, *args, **kargs):\n        \"\"\"\n        Sets the pen used to draw lines between points.\n        *pen* can be a QPen or any argument accepted by\n        :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`\n        \"\"\"\n        pen = fn.mkPen(*args, **kargs)\n        self.opts['pen'] = pen\n\n        self.paint()\n\n    def brush(self):\n        return self.opts['brush']\n\n    def setBrush(self, *args, **kargs):\n        brush = fn.mkBrush(*args, **kargs)\n        if self.opts['brush'] == brush:\n            return\n        self.opts['brush'] = brush\n\n        self.paint()\n\n    def labelTextColor(self):\n        return self.opts['labelTextColor']\n\n    def setLabelTextColor(self, *args, **kargs):\n        \"\"\"\n        Sets the color of the label text.\n        *pen* can be a QPen or any argument accepted by\n        :func:`pyqtgraph.mkColor() <pyqtgraph.mkPen>`\n        \"\"\"\n        self.opts['labelTextColor'] = fn.mkColor(*args, **kargs)\n        for sample, label in self.items:\n            label.setAttr('color', self.opts['labelTextColor'])\n\n        self.paint()\n\n    def setParentItem(self, p):\n        ret = GraphicsWidget.setParentItem(self, p)\n        if self.offset is not None:\n            offset = Point(self.opts['offset'])\n            anchorx = 1 if offset[0] <= 0 else 0\n            anchory = 1 if offset[1] <= 0 else 0\n            anchor = (anchorx, anchory)\n            self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)\n        return ret\n\n    def addItem(self, item, name):\n        \"\"\"\n        Add a new entry to the legend.\n\n        ==============  ========================================================\n        **Arguments:**\n        item            A PlotDataItem from which the line and point style\n                        of the item will be determined or an instance of\n                        ItemSample (or a subclass), allowing the item display\n                        to be customized.\n        title           The title to display for this item. Simple HTML allowed.\n        ==============  ========================================================\n        \"\"\"\n        label = LabelItem(name, color=self.opts['labelTextColor'], justify='left')\n        if isinstance(item, ItemSample):\n            sample = item\n        else:\n            sample = ItemSample(item)\n\n        row = self.layout.rowCount()\n        self.items.append((sample, label))\n        self.layout.addItem(sample, row, 0)\n        self.layout.addItem(label, row, 1)\n        self.updateSize()\n\n    def removeItem(self, item):\n        \"\"\"\n        Removes one item from the legend.\n\n        ==============  ========================================================\n        **Arguments:**\n        item            The item to remove or its name.\n        ==============  ========================================================\n        \"\"\"\n        for sample, label in self.items:\n            if sample.item is item or label.text == item:\n                self.items.remove((sample, label))      # remove from itemlist\n                self.layout.removeItem(sample)          # remove from layout\n                sample.close()                          # remove from drawing\n                self.layout.removeItem(label)\n                label.close()\n                self.updateSize()                       # redraq box\n                return                                  # return after first match\n\n    def clear(self):\n        \"\"\"Removes all items from legend.\"\"\"\n        for sample, label in self.items:\n            self.layout.removeItem(sample)\n            self.layout.removeItem(label)\n\n        self.items = []\n        self.updateSize()\n\n    def clear(self):\n        \"\"\"\n        Removes all items from the legend.\n\n        Useful for reusing and dynamically updating charts and their legends.\n        \"\"\"\n        while self.items != []:\n            self.removeItem(self.items[0][1].text)\n                \n    def updateSize(self):\n        if self.size is not None:\n            return\n\n        self.setGeometry(0, 0, 0, 0)\n\n    def boundingRect(self):\n        return QtCore.QRectF(0, 0, self.width(), self.height())\n\n    def paint(self, p, *args):\n        p.setPen(self.opts['pen'])\n        p.setBrush(self.opts['brush'])\n        p.drawRect(self.boundingRect())\n\n    def hoverEvent(self, ev):\n        ev.acceptDrags(QtCore.Qt.LeftButton)\n\n    def mouseDragEvent(self, ev):\n        if ev.button() == QtCore.Qt.LeftButton:\n            ev.accept()\n            dpos = ev.pos() - ev.lastPos()\n            self.autoAnchor(self.pos() + dpos)\n\n\nclass ItemSample(GraphicsWidget):\n    \"\"\" Class responsible for drawing a single item in a LegendItem (sans label).\n\n    This may be subclassed to draw custom graphics in a Legend.\n    \"\"\"\n    ## Todo: make this more generic; let each item decide how it should be represented.\n    def __init__(self, item):\n        GraphicsWidget.__init__(self)\n        self.item = item\n\n    def boundingRect(self):\n        return QtCore.QRectF(0, 0, 20, 20)\n\n    def paint(self, p, *args):\n        opts = self.item.opts\n\n        if opts['antialias']:\n            p.setRenderHint(p.Antialiasing)\n\n        if not isinstance(self.item, ScatterPlotItem):\n            p.setPen(fn.mkPen(opts['pen']))\n            p.drawLine(0, 11, 20, 11)\n\n        symbol = opts.get('symbol', None)\n        if symbol is not None:\n            if isinstance(self.item, PlotDataItem):\n                opts = self.item.scatter.opts\n\n            pen = fn.mkPen(opts['pen'])\n            brush = fn.mkBrush(opts['brush'])\n            size = opts['size']\n\n            p.translate(10, 10)\n            path = drawSymbol(p, symbol, size, pen, brush)\n\n\n\n\n", "path": "pyqtgraph/graphicsItems/LegendItem.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nfrom .GraphicsWidget import GraphicsWidget\nfrom .LabelItem import LabelItem\nfrom ..Qt import QtGui, QtCore\nfrom .. import functions as fn\nfrom ..Point import Point\nfrom .ScatterPlotItem import ScatterPlotItem, drawSymbol\nfrom .PlotDataItem import PlotDataItem\nfrom .GraphicsWidgetAnchor import GraphicsWidgetAnchor\n__all__ = ['LegendItem']\n\n\nclass LegendItem(GraphicsWidget, GraphicsWidgetAnchor):\n    \"\"\"\n    Displays a legend used for describing the contents of a plot.\n    LegendItems are most commonly created by calling PlotItem.addLegend().\n\n    Note that this item should not be added directly to a PlotItem. Instead,\n    Make it a direct descendant of the PlotItem::\n\n        legend.setParentItem(plotItem)\n\n    \"\"\"\n    def __init__(self, size=None, offset=None, horSpacing=25, verSpacing=0, pen=None,\n                 brush=None, labelTextColor=None, **kwargs):\n        \"\"\"\n        ==============  ===============================================================\n        **Arguments:**\n        size            Specifies the fixed size (width, height) of the legend. If\n                        this argument is omitted, the legend will automatically resize\n                        to fit its contents.\n        offset          Specifies the offset position relative to the legend's parent.\n                        Positive values offset from the left or top; negative values\n                        offset from the right or bottom. If offset is None, the\n                        legend must be anchored manually by calling anchor() or\n                        positioned by calling setPos().\n        horSpacing      Specifies the spacing between the line symbol and the label.\n        verSpacing      Specifies the spacing between individual entries of the legend\n                        vertically. (Can also be negative to have them really close)\n        pen             Pen to use when drawing legend border. Any single argument\n                        accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed.\n        brush           QBrush to use as legend background filling. Any single argument\n                        accepted by :func:`mkBrush <pyqtgraph.mkBrush>` is allowed.\n        labelTextColor  Pen to use when drawing legend text. Any single argument\n                        accepted by :func:`mkPen <pyqtgraph.mkPen>` is allowed.\n        ==============  ===============================================================\n\n        \"\"\"\n\n\n        GraphicsWidget.__init__(self)\n        GraphicsWidgetAnchor.__init__(self)\n        self.setFlag(self.ItemIgnoresTransformations)\n        self.layout = QtGui.QGraphicsGridLayout()\n        self.layout.setVerticalSpacing(verSpacing)\n        self.layout.setHorizontalSpacing(horSpacing)\n\n        self.setLayout(self.layout)\n        self.items = []\n        self.size = size\n        if size is not None:\n            self.setGeometry(QtCore.QRectF(0, 0, self.size[0], self.size[1]))\n\n        self.opts = {\n            'pen': fn.mkPen(pen),\n            'brush': fn.mkBrush(brush),\n            'labelTextColor': labelTextColor,\n            'offset': offset,\n        }\n\n        self.opts.update(kwargs)\n\n    def offset(self):\n        return self.opts['offset']\n\n    def setOffset(self, offset):\n        self.opts['offset'] = offset\n\n        offset = Point(self.opts['offset'])\n        anchorx = 1 if offset[0] <= 0 else 0\n        anchory = 1 if offset[1] <= 0 else 0\n        anchor = (anchorx, anchory)\n        self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)\n\n    def pen(self):\n        return self.opts['pen']\n\n    def setPen(self, *args, **kargs):\n        \"\"\"\n        Sets the pen used to draw lines between points.\n        *pen* can be a QPen or any argument accepted by\n        :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`\n        \"\"\"\n        pen = fn.mkPen(*args, **kargs)\n        self.opts['pen'] = pen\n\n        self.paint()\n\n    def brush(self):\n        return self.opts['brush']\n\n    def setBrush(self, *args, **kargs):\n        brush = fn.mkBrush(*args, **kargs)\n        if self.opts['brush'] == brush:\n            return\n        self.opts['brush'] = brush\n\n        self.paint()\n\n    def labelTextColor(self):\n        return self.opts['labelTextColor']\n\n    def setLabelTextColor(self, *args, **kargs):\n        \"\"\"\n        Sets the color of the label text.\n        *pen* can be a QPen or any argument accepted by\n        :func:`pyqtgraph.mkColor() <pyqtgraph.mkPen>`\n        \"\"\"\n        self.opts['labelTextColor'] = fn.mkColor(*args, **kargs)\n        for sample, label in self.items:\n            label.setAttr('color', self.opts['labelTextColor'])\n\n        self.paint()\n\n    def setParentItem(self, p):\n        ret = GraphicsWidget.setParentItem(self, p)\n        if self.opts['offset'] is not None:\n            offset = Point(self.opts['offset'])\n            anchorx = 1 if offset[0] <= 0 else 0\n            anchory = 1 if offset[1] <= 0 else 0\n            anchor = (anchorx, anchory)\n            self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)\n        return ret\n\n    def addItem(self, item, name):\n        \"\"\"\n        Add a new entry to the legend.\n\n        ==============  ========================================================\n        **Arguments:**\n        item            A PlotDataItem from which the line and point style\n                        of the item will be determined or an instance of\n                        ItemSample (or a subclass), allowing the item display\n                        to be customized.\n        title           The title to display for this item. Simple HTML allowed.\n        ==============  ========================================================\n        \"\"\"\n        label = LabelItem(name, color=self.opts['labelTextColor'], justify='left')\n        if isinstance(item, ItemSample):\n            sample = item\n        else:\n            sample = ItemSample(item)\n\n        row = self.layout.rowCount()\n        self.items.append((sample, label))\n        self.layout.addItem(sample, row, 0)\n        self.layout.addItem(label, row, 1)\n        self.updateSize()\n\n    def removeItem(self, item):\n        \"\"\"\n        Removes one item from the legend.\n\n        ==============  ========================================================\n        **Arguments:**\n        item            The item to remove or its name.\n        ==============  ========================================================\n        \"\"\"\n        for sample, label in self.items:\n            if sample.item is item or label.text == item:\n                self.items.remove((sample, label))      # remove from itemlist\n                self.layout.removeItem(sample)          # remove from layout\n                sample.close()                          # remove from drawing\n                self.layout.removeItem(label)\n                label.close()\n                self.updateSize()                       # redraq box\n                return                                  # return after first match\n\n    def clear(self):\n        \"\"\"Removes all items from legend.\"\"\"\n        for sample, label in self.items:\n            self.layout.removeItem(sample)\n            self.layout.removeItem(label)\n\n        self.items = []\n        self.updateSize()\n\n    def clear(self):\n        \"\"\"\n        Removes all items from the legend.\n\n        Useful for reusing and dynamically updating charts and their legends.\n        \"\"\"\n        while self.items != []:\n            self.removeItem(self.items[0][1].text)\n                \n    def updateSize(self):\n        if self.size is not None:\n            return\n\n        self.setGeometry(0, 0, 0, 0)\n\n    def boundingRect(self):\n        return QtCore.QRectF(0, 0, self.width(), self.height())\n\n    def paint(self, p, *args):\n        p.setPen(self.opts['pen'])\n        p.setBrush(self.opts['brush'])\n        p.drawRect(self.boundingRect())\n\n    def hoverEvent(self, ev):\n        ev.acceptDrags(QtCore.Qt.LeftButton)\n\n    def mouseDragEvent(self, ev):\n        if ev.button() == QtCore.Qt.LeftButton:\n            ev.accept()\n            dpos = ev.pos() - ev.lastPos()\n            self.autoAnchor(self.pos() + dpos)\n\n\nclass ItemSample(GraphicsWidget):\n    \"\"\" Class responsible for drawing a single item in a LegendItem (sans label).\n\n    This may be subclassed to draw custom graphics in a Legend.\n    \"\"\"\n    ## Todo: make this more generic; let each item decide how it should be represented.\n    def __init__(self, item):\n        GraphicsWidget.__init__(self)\n        self.item = item\n\n    def boundingRect(self):\n        return QtCore.QRectF(0, 0, 20, 20)\n\n    def paint(self, p, *args):\n        opts = self.item.opts\n\n        if opts['antialias']:\n            p.setRenderHint(p.Antialiasing)\n\n        if not isinstance(self.item, ScatterPlotItem):\n            p.setPen(fn.mkPen(opts['pen']))\n            p.drawLine(0, 11, 20, 11)\n\n        symbol = opts.get('symbol', None)\n        if symbol is not None:\n            if isinstance(self.item, PlotDataItem):\n                opts = self.item.scatter.opts\n\n            pen = fn.mkPen(opts['pen'])\n            brush = fn.mkBrush(opts['brush'])\n            size = opts['size']\n\n            p.translate(10, 10)\n            path = drawSymbol(p, symbol, size, pen, brush)\n", "path": "pyqtgraph/graphicsItems/LegendItem.py"}]}