Many unused import cleanups (#1935)

* Many unused import cleanups

Ignored some star imports, some vendored code in colorama, only looked within pyqtgraph the library, not e.g. examples

* SpinBox decimal imported with both import and from import
This commit is contained in:
Kyle Sunden 2021-07-31 09:35:23 -05:00 committed by GitHub
parent 2d90e54441
commit 6a59b7e5b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
70 changed files with 97 additions and 439 deletions

View File

@ -5,7 +5,6 @@ from time import perf_counter, perf_counter_ns
from ..Qt import QtCore, QtGui, QT_LIB, isQObjectAlive from ..Qt import QtCore, QtGui, QT_LIB, isQObjectAlive
from ..Point import Point from ..Point import Point
from .. import functions as fn
from .mouseEvents import * from .mouseEvents import *
from .. import debug as debug from .. import debug as debug
from .. import getConfigOption from .. import getConfigOption

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from time import perf_counter from time import perf_counter
from ..Point import Point from ..Point import Point
from ..Qt import QtCore, QtGui from ..Qt import QtCore
import weakref import weakref
class MouseDragEvent(object): class MouseDragEvent(object):
@ -377,4 +378,4 @@ class HoverEvent(object):
return self.__dragItems return self.__dragItems

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from .Qt import QtCore, QtGui from .Qt import QtCore
__all__ = ['ThreadsafeTimer'] __all__ = ['ThreadsafeTimer']

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from .Qt import QtCore, QtGui from .Qt import QtGui
from . import functions as fn from . import functions as fn
from .Vector import Vector from .Vector import Vector
import numpy as np import numpy as np

View File

@ -8,7 +8,7 @@ This class addresses the problem of having to save and restore the state
of a large group of widgets. of a large group of widgets.
""" """
from .Qt import QtCore, QtGui, QT_LIB from .Qt import QtCore, QtGui
import weakref, inspect import weakref, inspect
from .python2_3 import asUnicode from .python2_3 import asUnicode
@ -280,4 +280,4 @@ class WidgetGroup(QtCore.QObject):
#print "%s: Cached value %s != set value %s" % (name, str(self.cache[name]), str(v1)) #print "%s: Cached value %s != set value %s" % (name, str(self.cache[name]), str(v1))

View File

@ -9,8 +9,6 @@ import importlib
ui_template = importlib.import_module( ui_template = importlib.import_module(
f'.CanvasTemplate_{QT_LIB.lower()}', package=__package__) f'.CanvasTemplate_{QT_LIB.lower()}', package=__package__)
import numpy as np
from .. import debug
import weakref import weakref
import gc import gc
from .CanvasManager import CanvasManager from .CanvasManager import CanvasManager

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys, re, os, time, traceback, subprocess import sys, re, traceback, subprocess
import pickle import pickle
from ..Qt import QtCore, QtGui, QT_LIB from ..Qt import QtCore, QtGui, QT_LIB

View File

@ -1,10 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import weakref import weakref
from ..Qt import QtCore, QtGui from ..Qt import QtGui
from .Container import * from .Container import *
from .DockDrop import * from .DockDrop import *
from .Dock import Dock from .Dock import Dock
from .. import debug as debug
from ..python2_3 import basestring from ..python2_3 import basestring

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtCore
from .Exporter import Exporter from .Exporter import Exporter
from ..parametertree import Parameter from ..parametertree import Parameter
from .. import PlotItem from .. import PlotItem

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from ..widgets.FileDialog import FileDialog from ..widgets.FileDialog import FileDialog
from ..Qt import QtGui, QtCore, QtSvg from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode, basestring from ..python2_3 import asUnicode, basestring
from ..GraphicsScene import GraphicsScene from ..GraphicsScene import GraphicsScene
import os, re import os, re

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Qt import QtCore
from .Exporter import Exporter from .Exporter import Exporter
from ..parametertree import Parameter from ..parametertree import Parameter
from .. import PlotItem from .. import PlotItem

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from .Exporter import Exporter from .Exporter import Exporter
from ..parametertree import Parameter from ..parametertree import Parameter
from ..Qt import QtGui, QtCore, QtSvg from ..Qt import QtGui, QtCore
import re
translate = QtCore.QCoreApplication.translate translate = QtCore.QCoreApplication.translate

View File

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
from .Exporter import Exporter from .Exporter import Exporter
from ..python2_3 import asUnicode from ..python2_3 import asUnicode
from ..parametertree import Parameter from ..parametertree import Parameter
from ..Qt import QtGui, QtCore, QtSvg, QT_LIB from ..Qt import QtGui, QtCore, QtSvg
from .. import debug from .. import debug
from .. import functions as fn from .. import functions as fn
import re import re

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from ..widgets.GraphicsView import GraphicsView from ..widgets.GraphicsView import GraphicsView
from ..GraphicsScene import GraphicsScene
from ..graphicsItems.ViewBox import ViewBox from ..graphicsItems.ViewBox import ViewBox
translate = QtCore.QCoreApplication.translate translate = QtCore.QCoreApplication.translate

View File

@ -5,7 +5,6 @@ from .. import functions as fn
from .Terminal import * from .Terminal import *
from collections import OrderedDict from collections import OrderedDict
from ..debug import * from ..debug import *
import numpy as np
import warnings import warnings
translate = QtCore.QCoreApplication.translate translate = QtCore.QCoreApplication.translate

View File

@ -4,8 +4,6 @@ from ...Qt import QtGui, QtCore, QtWidgets
import numpy as np import numpy as np
import sys import sys
from .common import * from .common import *
from ...SRTTransform import SRTTransform
from ...Point import Point
from ...widgets.TreeWidget import TreeWidget from ...widgets.TreeWidget import TreeWidget
from ...graphicsItems.LinearRegionItem import LinearRegionItem from ...graphicsItems.LinearRegionItem import LinearRegionItem
@ -481,4 +479,3 @@ class AsType(CtrlNode):
def processData(self, data): def processData(self, data):
s = self.stateGroup.state() s = self.stateGroup.state()
return data.astype(s['dtype']) return data.astype(s['dtype'])

View File

@ -1,9 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Node import Node from ..Node import Node
import weakref
from ...Qt import QtCore, QtGui from ...Qt import QtCore, QtGui
from ...graphicsItems.ScatterPlotItem import ScatterPlotItem from ...graphicsItems.ScatterPlotItem import ScatterPlotItem
from ...graphicsItems.PlotCurveItem import PlotCurveItem
from ... import PlotDataItem, ComboBox from ... import PlotDataItem, ComboBox
from .common import * from .common import *

View File

@ -1,7 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import numpy as np import numpy as np
from ...Qt import QtCore, QtGui
from ..Node import Node
from . import functions from . import functions
from ... import functions as pgfn from ... import functions as pgfn
from .common import * from .common import *

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import numpy as np import numpy as np
from ...metaarray import MetaArray from ...metaarray import MetaArray
from ...python2_3 import basestring, xrange from ...python2_3 import xrange
def downsample(data, n, axis=0, xvals='subsample'): def downsample(data, n, axis=0, xvals='subsample'):
@ -354,4 +355,4 @@ def removePeriodic(data, f0=60.0, dt=None, harmonics=10, samples=4):
return data2 return data2

View File

@ -7,7 +7,6 @@ Distributed under MIT/X11 license. See license.txt for more information.
from __future__ import division from __future__ import division
import ctypes
import decimal import decimal
import re import re
import struct import struct
@ -2403,11 +2402,6 @@ def traceImage(image, values, smooth=0.5):
If image is RGB or RGBA, then the shape of values should be (nvals, 3/4) If image is RGB or RGBA, then the shape of values should be (nvals, 3/4)
The parameter *smooth* is expressed in pixels. The parameter *smooth* is expressed in pixels.
""" """
try:
import scipy.ndimage as ndi
except ImportError:
raise Exception("traceImage() requires the package scipy.ndimage, but it is not importable.")
if values.ndim == 2: if values.ndim == 2:
values = values.T values = values.T
values = values[np.newaxis, np.newaxis, ...].astype(float) values = values[np.newaxis, np.newaxis, ...].astype(float)

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from math import hypot from math import hypot
from ..Qt import QtGui, QtCore from ..Qt import QtGui
from .. import functions as fn from .. import functions as fn
import numpy as np
__all__ = ['ArrowItem'] __all__ = ['ArrowItem']
class ArrowItem(QtGui.QGraphicsPathItem): class ArrowItem(QtGui.QGraphicsPathItem):

View File

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
from math import atan2, degrees from math import atan2, degrees
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from . import ArrowItem from . import ArrowItem
from ..functions import clip_scalar from ..functions import clip_scalar
from ..Point import Point
import weakref import weakref
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject

View File

@ -1,9 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
from .. import getConfigOption from .. import getConfigOption
from .. import functions as fn from .. import functions as fn
import numpy as np
__all__ = ['ErrorBarItem'] __all__ = ['ErrorBarItem']

View File

@ -4,7 +4,6 @@ import weakref
import numpy as np import numpy as np
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from .. import functions as fn from .. import functions as fn
from .GraphicsObject import GraphicsObject
from .GraphicsWidget import GraphicsWidget from .GraphicsWidget import GraphicsWidget
from ..widgets.SpinBox import SpinBox from ..widgets.SpinBox import SpinBox
from collections import OrderedDict from collections import OrderedDict

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Qt import QtGui
from .. import functions as fn from .. import functions as fn
from .GraphicsWidget import GraphicsWidget from .GraphicsWidget import GraphicsWidget
## Must be imported at the end to avoid cyclic-dependency hell: ## Must be imported at the end to avoid cyclic-dependency hell:

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore, QT_LIB # -*- coding: utf-8 -*-
from ..Qt import QtGui, QT_LIB
if QT_LIB.startswith('PyQt'): if QT_LIB.startswith('PyQt'):
from ..Qt import sip from ..Qt import sip
from .GraphicsItem import GraphicsItem from .GraphicsItem import GraphicsItem

View File

@ -1,5 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..GraphicsScene import GraphicsScene from ..Qt import QtGui
from .GraphicsItem import GraphicsItem from .GraphicsItem import GraphicsItem
__all__ = ['GraphicsWidget'] __all__ = ['GraphicsWidget']
@ -55,5 +55,3 @@ class GraphicsWidget(GraphicsItem, QtGui.QGraphicsWidget):
p.addRect(self.boundingRect()) p.addRect(self.boundingRect())
#print "shape:", p.boundingRect() #print "shape:", p.boundingRect()
return p return p

View File

@ -1,4 +1,4 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Point import Point from ..Point import Point
__all__ = ['GraphicsWidgetAnchor'] __all__ = ['GraphicsWidgetAnchor']
@ -108,4 +108,4 @@ class GraphicsWidgetAnchor(object):
pos = p + (o-a) + off pos = p + (o-a) + off
self.setPos(pos) self.setPos(pos)

View File

@ -8,7 +8,6 @@ from .TextItem import TextItem
from .ViewBox import ViewBox from .ViewBox import ViewBox
from .. import functions as fn from .. import functions as fn
import numpy as np import numpy as np
import weakref
__all__ = ['InfiniteLine', 'InfLineLabel'] __all__ = ['InfiniteLine', 'InfLineLabel']

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Qt import QtCore
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
__all__ = ['ItemGroup'] __all__ = ['ItemGroup']
@ -19,4 +20,3 @@ class ItemGroup(GraphicsObject):
def addItem(self, item): def addItem(self, item):
item.setParentItem(self) item.setParentItem(self)

View File

@ -1,20 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import division from __future__ import division
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
import numpy as np import numpy as np
from .. import functions as fn from .. import functions as fn
from .. import debug as debug
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
from ..Point import Point
from .. import getConfigOption from .. import getConfigOption
from .GradientEditorItem import Gradients # List of colormaps from .GradientEditorItem import Gradients # List of colormaps
from ..colormap import ColorMap from ..colormap import ColorMap
try:
from collections.abc import Callable
except ImportError:
# fallback for python < 3.3
from collections import Callable
__all__ = ['PColorMeshItem'] __all__ = ['PColorMeshItem']

View File

@ -6,8 +6,7 @@ import warnings
import numpy as np import numpy as np
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
from .. import functions as fn from .. import functions as fn
from ..Point import Point import sys
import struct, sys
from .. import getConfigOption from .. import getConfigOption
from .. import debug from .. import debug

View File

@ -2,7 +2,6 @@
import warnings import warnings
import math import math
import numpy as np import numpy as np
from .. import metaarray as metaarray
from ..Qt import QtCore from ..Qt import QtCore
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
from .PlotCurveItem import PlotCurveItem from .PlotCurveItem import PlotCurveItem

View File

@ -21,7 +21,6 @@ from math import atan2, cos, degrees, sin, hypot
from .. import functions as fn from .. import functions as fn
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
from .UIGraphicsItem import UIGraphicsItem from .UIGraphicsItem import UIGraphicsItem
from .. import getConfigOption
import warnings import warnings
import sys import sys

View File

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from .GraphicsObject import * from .GraphicsObject import *
from .GraphicsWidgetAnchor import * from .GraphicsWidgetAnchor import *
from .TextItem import TextItem from .TextItem import TextItem
import numpy as np
from .. import functions as fn from .. import functions as fn
from .. import getConfigOption from .. import getConfigOption
from ..Point import Point from ..Point import Point
@ -67,5 +67,3 @@ class ScaleBar(GraphicsObject, GraphicsWidgetAnchor):
anchor = (anchorx, anchory) anchor = (anchorx, anchory)
self.anchor(itemPos=anchor, parentPos=anchor, offset=offset) self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)
return ret return ret

View File

@ -8,7 +8,6 @@ from .. import Qt
from ..Qt import QtGui, QtCore, QT_LIB from ..Qt import QtGui, QtCore, QT_LIB
from ..Point import Point from ..Point import Point
from .. import functions as fn from .. import functions as fn
from .GraphicsItem import GraphicsItem
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
from .. import getConfigOption from .. import getConfigOption
from collections import OrderedDict from collections import OrderedDict

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore, QT_LIB from ..Qt import QtGui, QtCore, QT_LIB
import weakref
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
if QT_LIB.startswith('PyQt'): if QT_LIB.startswith('PyQt'):
from ..Qt import sip from ..Qt import sip

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
if __name__ == '__main__': if __name__ == '__main__':
import os, sys import os, sys
path = os.path.abspath(os.path.dirname(__file__)) path = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(path, '..', '..')) sys.path.insert(0, os.path.join(path, '..', '..'))
from ..Qt import QtGui, QtCore from ..Qt import QtGui
from .. import functions as fn from .. import functions as fn
import weakref
from .UIGraphicsItem import UIGraphicsItem from .UIGraphicsItem import UIGraphicsItem
__all__ = ['VTickGroup'] __all__ = ['VTickGroup']
@ -96,4 +96,4 @@ class VTickGroup(UIGraphicsItem):
p.setPen(self.pen) p.setPen(self.pen)
p.drawPath(self.path) p.drawPath(self.path)

View File

@ -12,7 +12,6 @@ from .Qt import QtCore, QtGui, mkQApp
from .widgets.PlotWidget import * from .widgets.PlotWidget import *
from .imageview import * from .imageview import *
from .widgets.GraphicsLayoutWidget import GraphicsLayoutWidget from .widgets.GraphicsLayoutWidget import GraphicsLayoutWidget
from .widgets.GraphicsView import GraphicsView
import warnings import warnings

View File

@ -10,7 +10,7 @@ new methods for slicing and indexing the array based on this meta data.
More info at http://www.scipy.org/Cookbook/MetaArray More info at http://www.scipy.org/Cookbook/MetaArray
""" """
import types, copy, threading, os, re import copy, os
import pickle import pickle
import numpy as np import numpy as np
from ..python2_3 import basestring from ..python2_3 import basestring

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import subprocess, atexit, os, sys, time, random, socket, signal, inspect import subprocess, atexit, os, sys, time, signal, inspect
import multiprocessing.connection import multiprocessing.connection
try: try:
import cPickle as pickle import cPickle as pickle
@ -388,7 +388,7 @@ class RemoteQtEventHandler(RemoteEventHandler):
RemoteEventHandler.__init__(self, *args, **kwds) RemoteEventHandler.__init__(self, *args, **kwds)
def startEventTimer(self): def startEventTimer(self):
from ..Qt import QtGui, QtCore from ..Qt import QtCore
self.timer = QtCore.QTimer() self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.processRequests) self.timer.timeout.connect(self.processRequests)
self.timer.start(10) self.timer.start(10)
@ -397,7 +397,7 @@ class RemoteQtEventHandler(RemoteEventHandler):
try: try:
RemoteEventHandler.processRequests(self) RemoteEventHandler.processRequests(self)
except ClosedError: except ClosedError:
from ..Qt import QtGui, QtCore from ..Qt import QtGui
QtGui.QApplication.instance().quit() QtGui.QApplication.instance().quit()
self.timer.stop() self.timer.stop()
#raise SystemExit #raise SystemExit
@ -466,7 +466,7 @@ def startQtEventLoop(name, port, authkey, ppid, debug=False):
conn = multiprocessing.connection.Client(('localhost', int(port)), authkey=authkey) conn = multiprocessing.connection.Client(('localhost', int(port)), authkey=authkey)
if debug: if debug:
cprint.cout(debug, '[%d] connected; starting remote proxy.\n' % os.getpid(), -1) cprint.cout(debug, '[%d] connected; starting remote proxy.\n' % os.getpid(), -1)
from ..Qt import QtGui, QtCore from ..Qt import QtGui
app = QtGui.QApplication.instance() app = QtGui.QApplication.instance()
#print app #print app
if app is None: if app is None:

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import numpy as np import numpy as np
from ..Qt import QtGui from ..Qt import QtGui
from .. import functions as fn
from ..python2_3 import xrange from ..python2_3 import xrange

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
from OpenGL.GL import * from OpenGL.GL import *
from .. GLGraphicsItem import GLGraphicsItem from .. GLGraphicsItem import GLGraphicsItem
from ...Qt import QtGui
import numpy as np
__all__ = ['GLImageItem'] __all__ = ['GLImageItem']

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
from OpenGL.GL import * from OpenGL.GL import *
from OpenGL.arrays import vbo
from .. GLGraphicsItem import GLGraphicsItem from .. GLGraphicsItem import GLGraphicsItem
from .. import shaders
from ... import QtGui from ... import QtGui
from ... import functions as fn from ... import functions as fn
import numpy as np import numpy as np
@ -51,7 +50,6 @@ class GLLinePlotItem(GLGraphicsItem):
for arg in args: for arg in args:
if arg in kwds: if arg in kwds:
setattr(self, arg, kwds[arg]) setattr(self, arg, kwds[arg])
#self.vbo.pop(arg, None)
self.update() self.update()
def paint(self): def paint(self):

View File

@ -1,6 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from OpenGL.GL import * from OpenGL.GL import *
from OpenGL.arrays import vbo
from .. GLGraphicsItem import GLGraphicsItem from .. GLGraphicsItem import GLGraphicsItem
from .. import shaders from .. import shaders
from ... import functions as fn from ... import functions as fn
@ -20,7 +19,6 @@ class GLScatterPlotItem(GLGraphicsItem):
self.size = 10 self.size = 10
self.color = [1.0,1.0,1.0,0.5] self.color = [1.0,1.0,1.0,0.5]
self.pxMode = True self.pxMode = True
#self.vbo = {} ## VBO does not appear to improve performance very much.
self.setData(**kwds) self.setData(**kwds)
self.shader = None self.shader = None
@ -51,7 +49,6 @@ class GLScatterPlotItem(GLGraphicsItem):
for arg in args: for arg in args:
if arg in kwds: if arg in kwds:
setattr(self, arg, kwds[arg]) setattr(self, arg, kwds[arg])
#self.vbo.pop(arg, None)
self.pxMode = kwds.get('pxMode', self.pxMode) self.pxMode = kwds.get('pxMode', self.pxMode)
self.update() self.update()
@ -79,11 +76,6 @@ class GLScatterPlotItem(GLGraphicsItem):
self.shader = shaders.getShaderProgram('pointSprite') self.shader = shaders.getShaderProgram('pointSprite')
#def getVBO(self, name):
#if name not in self.vbo:
#self.vbo[name] = vbo.VBO(getattr(self, name).astype('f'))
#return self.vbo[name]
#def setupGLState(self): #def setupGLState(self):
#"""Prepare OpenGL state for drawing. This function is called immediately before painting.""" #"""Prepare OpenGL state for drawing. This function is called immediately before painting."""
##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly. ##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly.

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from OpenGL.GL import * from OpenGL.GL import *
from .GLMeshItem import GLMeshItem from .GLMeshItem import GLMeshItem
from .. MeshData import MeshData from .. MeshData import MeshData
from ...Qt import QtGui
import numpy as np import numpy as np

View File

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
from OpenGL.GL import * from OpenGL.GL import *
from .. GLGraphicsItem import GLGraphicsItem from .. GLGraphicsItem import GLGraphicsItem
from ...Qt import QtGui from ...Qt import QtGui
import numpy as np import numpy as np
from ... import debug
__all__ = ['GLVolumeItem'] __all__ = ['GLVolumeItem']
@ -227,4 +227,3 @@ class GLVolumeItem(GLGraphicsItem):
#glPopMatrix() #glPopMatrix()

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from .. import functions as fn from .. import functions as fn
from ..Qt import QtGui, QtCore from ..Qt import QtCore
import os, weakref, re import weakref, re
from collections import OrderedDict from collections import OrderedDict
from ..python2_3 import asUnicode, basestring from ..python2_3 import asUnicode, basestring
from .ParameterItem import ParameterItem from .ParameterItem import ParameterItem

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from ..python2_3 import asUnicode from ..python2_3 import asUnicode
import os, weakref, re
translate = QtCore.QCoreApplication.translate translate = QtCore.QCoreApplication.translate

View File

@ -1,3 +1,6 @@
# -*- coding: utf-8 -*-
__all__ = ["ParameterSystem", "SystemSolver"]
from .parameterTypes import GroupParameter from .parameterTypes import GroupParameter
from .. import functions as fn from .. import functions as fn
from .SystemSolver import SystemSolver from .SystemSolver import SystemSolver
@ -124,4 +127,3 @@ class ParameterSystem(GroupParameter):

View File

@ -1,10 +1,8 @@
# -*- coding: utf-8 -*-
from ..Qt import QtCore, QtWidgets from ..Qt import QtCore, QtWidgets
from ..widgets.TreeWidget import TreeWidget from ..widgets.TreeWidget import TreeWidget
import os, weakref, re
from .ParameterItem import ParameterItem from .ParameterItem import ParameterItem
#import functions as fn
class ParameterTree(TreeWidget): class ParameterTree(TreeWidget):
"""Widget used to display or control data from a hierarchy of Parameters""" """Widget used to display or control data from a hierarchy of Parameters"""

View File

@ -17,7 +17,6 @@ warnings.warn(
) )
import threading import threading
import sys
import copy import copy
from collections import OrderedDict from collections import OrderedDict

View File

@ -312,289 +312,3 @@ def getPreviousVersion(obj):
else: else:
# python 3 # python 3
return types.MethodType(oldfunc, self) return types.MethodType(oldfunc, self)
## Tests:
# write modules to disk, import, then re-write and run again
if __name__ == '__main__':
doQtTest = True
try:
from PyQt4 import QtCore
if not hasattr(QtCore, 'Signal'):
QtCore.Signal = QtCore.pyqtSignal
#app = QtGui.QApplication([])
class Btn(QtCore.QObject):
sig = QtCore.Signal()
def emit(self):
self.sig.emit()
btn = Btn()
except:
raise
import os
if not os.path.isdir('test1'):
os.mkdir('test1')
with open('test1/__init__.py', 'w'):
pass
modFile1 = "test1/test1.py"
modCode1 = """
import sys
class A(object):
def __init__(self, msg):
object.__init__(self)
self.msg = msg
def fn(self, pfx = ""):
print(pfx+"A class: %%s %%s" %% (str(self.__class__), str(id(self.__class__))))
print(pfx+" %%s: %d" %% self.msg)
class B(A):
def fn(self, pfx=""):
print(pfx+"B class:", self.__class__, id(self.__class__))
print(pfx+" %%s: %d" %% self.msg)
print(pfx+" calling superclass.. (%%s)" %% id(A) )
A.fn(self, " ")
"""
modFile2 = "test2.py"
modCode2 = """
from test1.test1 import A
from test1.test1 import B
a1 = A("ax1")
b1 = B("bx1")
class C(A):
def __init__(self, msg):
#print "| C init:"
#print "| C.__bases__ = ", map(id, C.__bases__)
#print "| A:", id(A)
#print "| A.__init__ = ", id(A.__init__.im_func), id(A.__init__.im_func.__code__), id(A.__init__.im_class)
A.__init__(self, msg + "(init from C)")
def fn():
print("fn: %s")
"""
with open(modFile1, 'w') as f:
f.write(modCode1 % (1, 1))
with open(modFile2, 'w') as f:
f.write(modCode2 % ("message 1", ))
import test1.test1 as test1
import test2
print("Test 1 originals:")
A1 = test1.A
B1 = test1.B
a1 = test1.A("a1")
b1 = test1.B("b1")
a1.fn()
b1.fn()
#print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class))
from test2 import fn, C
if doQtTest:
print("Button test before:")
btn.sig.connect(fn)
btn.sig.connect(a1.fn)
btn.emit()
#btn.sig.emit()
print("")
#print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func)
print("Test2 before reload:")
fn()
oldfn = fn
test2.a1.fn()
test2.b1.fn()
c1 = test2.C('c1')
c1.fn()
os.remove(modFile1+'c')
with open(modFile1, 'w') as f:
f.write(modCode1 %(2, 2))
print("\n----RELOAD test1-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True)
print("Subclass test:")
c2 = test2.C('c2')
c2.fn()
os.remove(modFile2+'c')
with open(modFile2, 'w') as f:
f.write(modCode2 % ("message 2", ))
print("\n----RELOAD test2-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True)
if doQtTest:
print("Button test after:")
btn.emit()
#btn.sig.emit()
#print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func)
print("Test2 after reload:")
fn()
test2.a1.fn()
test2.b1.fn()
print("\n==> Test 1 Old instances:")
a1.fn()
b1.fn()
c1.fn()
#print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class))
print("\n==> Test 1 New instances:")
a2 = test1.A("a2")
b2 = test1.B("b2")
a2.fn()
b2.fn()
c2 = test2.C('c2')
c2.fn()
#print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class))
os.remove(modFile1+'c')
os.remove(modFile2+'c')
with open(modFile1, 'w') as f:
f.write(modCode1 % (3, 3))
with open(modFile2, 'w') as f:
f.write(modCode2 % ("message 3", ))
print("\n----RELOAD-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True)
if doQtTest:
print("Button test after:")
btn.emit()
#btn.sig.emit()
#print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func)
print("Test2 after reload:")
fn()
test2.a1.fn()
test2.b1.fn()
print("\n==> Test 1 Old instances:")
a1.fn()
b1.fn()
print("function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.__func__), id(a1.fn.__self__.__class__), id(b1.fn.__func__), id(b1.fn.__self__.__class__)))
print("\n==> Test 1 New instances:")
a2 = test1.A("a2")
b2 = test1.B("b2")
a2.fn()
b2.fn()
print("function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.__func__), id(a1.fn.__self__.__class__), id(b1.fn.__func__), id(b1.fn.__self__.__class__)))
os.remove(modFile1)
os.remove(modFile2)
os.remove(modFile1+'c')
os.remove(modFile2+'c')
os.system('rm -r test1')
#
# Failure graveyard ahead:
#
"""Reload Importer:
Hooks into import system to
1) keep a record of module dependencies as they are imported
2) make sure modules are always reloaded in correct order
3) update old classes and functions to use reloaded code"""
#import imp, sys
## python's import hook mechanism doesn't work since we need to be
## informed every time there is an import statement, not just for new imports
#class ReloadImporter:
#def __init__(self):
#self.depth = 0
#def find_module(self, name, path):
#print " "*self.depth + "find: ", name, path
##if name == 'PyQt4' and path is None:
##print "PyQt4 -> PySide"
##self.modData = imp.find_module('PySide')
##return self
##return None ## return none to allow the import to proceed normally; return self to intercept with load_module
#self.modData = imp.find_module(name, path)
#self.depth += 1
##sys.path_importer_cache = {}
#return self
#def load_module(self, name):
#mod = imp.load_module(name, *self.modData)
#self.depth -= 1
#print " "*self.depth + "load: ", name
#return mod
#def pathHook(path):
#print "path hook:", path
#raise ImportError
#sys.path_hooks.append(pathHook)
#sys.meta_path.append(ReloadImporter())
### replace __import__ with a wrapper that tracks module dependencies
#modDeps = {}
#reloadModule = None
#origImport = __builtins__.__import__
#def _import(name, globals=None, locals=None, fromlist=None, level=-1, stack=[]):
### Note that stack behaves as a static variable.
##print " "*len(importStack) + "import %s" % args[0]
#stack.append(set())
#mod = origImport(name, globals, locals, fromlist, level)
#deps = stack.pop()
#if len(stack) > 0:
#stack[-1].add(mod)
#elif reloadModule is not None: ## If this is the top level import AND we're inside a module reload
#modDeps[reloadModule].add(mod)
#if mod in modDeps:
#modDeps[mod] |= deps
#else:
#modDeps[mod] = deps
#return mod
#__builtins__.__import__ = _import
### replace
#origReload = __builtins__.reload
#def _reload(mod):
#reloadModule = mod
#ret = origReload(mod)
#reloadModule = None
#return ret
#__builtins__.reload = _reload
#def reload(mod, visited=None):
#if visited is None:
#visited = set()
#if mod in visited:
#return
#visited.add(mod)
#for dep in modDeps.get(mod, []):
#reload(dep, visited)
#__builtins__.reload(mod)

View File

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
""" """
Cross-platform color text printing Cross-platform color text printing
Based on colorama (see pyqtgraph/util/colorama/README.txt) Based on colorama (see pyqtgraph/util/colorama/README.txt)
""" """
import sys, re import sys
from .colorama.winterm import WinTerm, WinColor, WinStyle from .colorama.winterm import WinTerm, WinColor, WinStyle
from .colorama.win32 import windll from .colorama.win32 import windll
@ -98,5 +99,3 @@ def cout(*args):
def cerr(*args): def cerr(*args):
"""Shorthand for cprint('stderr', ...)""" """Shorthand for cprint('stderr', ...)"""
cprint('stderr', *args) cprint('stderr', *args)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from warnings import warn from warnings import warn
from .. import getConfigOption from .. import getConfigOption
@ -5,7 +6,7 @@ from .. import getConfigOption
def getNumbaFunctions(): def getNumbaFunctions():
if getConfigOption("useNumba"): if getConfigOption("useNumba"):
try: try:
import numba import numba # noqa
except ImportError: except ImportError:
warn("numba library could not be loaded, but 'useNumba' is set.") warn("numba library could not be loaded, but 'useNumba' is set.")
return None return None

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Qt import QtCore
from .. import parametertree as ptree from .. import parametertree as ptree
import numpy as np import numpy as np
from collections import OrderedDict from collections import OrderedDict
@ -270,5 +271,3 @@ class EnumColorMapItem(ptree.types.GroupParameter):
#colors[mask] = nanColor #colors[mask] = nanColor
return colors return colors

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys import sys
from ..Qt import QtGui, QtCore from ..Qt import QtGui
from ..SignalProxy import SignalProxy
from collections import OrderedDict from collections import OrderedDict
from ..python2_3 import asUnicode, basestring from ..python2_3 import asUnicode, basestring

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Qt import QtCore
from .. import parametertree as ptree from .. import parametertree as ptree
import numpy as np import numpy as np
from collections import OrderedDict from collections import OrderedDict

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui
from collections import OrderedDict from collections import OrderedDict
from .TableWidget import TableWidget from .TableWidget import TableWidget
from ..python2_3 import asUnicode from ..python2_3 import asUnicode
@ -7,7 +7,7 @@ import types, traceback
import numpy as np import numpy as np
try: try:
import metaarray import metaarray # noqa
HAVE_METAARRAY = True HAVE_METAARRAY = True
except: except:
HAVE_METAARRAY = False HAVE_METAARRAY = False

View File

@ -1,9 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui
from collections import OrderedDict
from .DataTreeWidget import DataTreeWidget from .DataTreeWidget import DataTreeWidget
from .. import functions as fn from .. import functions as fn
import types, traceback
import numpy as np import numpy as np
__all__ = ['DiffTreeWidget'] __all__ = ['DiffTreeWidget']
@ -161,4 +159,4 @@ class DiffTreeWidget(QtGui.QWidget):
assert info == expect assert info == expect
except Exception: except Exception:
raise NotImplementedError("Cannot compare objects of type %s" % type(info)) raise NotImplementedError("Cannot compare objects of type %s" % type(info))

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Qt import QtGui
import sys import sys
__all__ = ['FileDialog'] __all__ = ['FileDialog']
@ -11,4 +12,4 @@ class FileDialog(QtGui.QFileDialog):
QtGui.QFileDialog.__init__(self, *args) QtGui.QFileDialog.__init__(self, *args)
if sys.platform == 'darwin': if sys.platform == 'darwin':
self.setOption(QtGui.QFileDialog.Option.DontUseNativeDialog) self.setOption(QtGui.QFileDialog.Option.DontUseNativeDialog)

View File

@ -2,8 +2,6 @@
from ..Qt import QtGui, QtCore, QtWidgets from ..Qt import QtGui, QtCore, QtWidgets
from .GraphicsView import GraphicsView from .GraphicsView import GraphicsView
from ..graphicsItems.GradientEditorItem import GradientEditorItem from ..graphicsItems.GradientEditorItem import GradientEditorItem
import weakref
import numpy as np
__all__ = ['GradientWidget'] __all__ = ['GradientWidget']
@ -75,5 +73,3 @@ class GradientWidget(GraphicsView):
def widgetGroupInterface(self): def widgetGroupInterface(self):
return (self.sigGradientChanged, self.saveState, self.restoreState) return (self.sigGradientChanged, self.saveState, self.restoreState)

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, mkQApp from ..Qt import mkQApp
from ..graphicsItems.GraphicsLayout import GraphicsLayout from ..graphicsItems.GraphicsLayout import GraphicsLayout
from .GraphicsView import GraphicsView from .GraphicsView import GraphicsView

View File

@ -9,7 +9,6 @@ from ..Qt import QtCore, QtGui, QtWidgets, QT_LIB
from ..Point import Point from ..Point import Point
from ..GraphicsScene import GraphicsScene from ..GraphicsScene import GraphicsScene
from .. import functions as fn from .. import functions as fn
from .. import debug as debug
from .. import getConfigOption from .. import getConfigOption
__all__ = ['GraphicsView'] __all__ = ['GraphicsView']

View File

@ -1,4 +1,5 @@
from ..Qt import QtGui, QtCore # -*- coding: utf-8 -*-
from ..Qt import QtGui
__all__ = ['LayoutWidget'] __all__ = ['LayoutWidget']
class LayoutWidget(QtGui.QWidget): class LayoutWidget(QtGui.QWidget):
@ -97,5 +98,3 @@ class LayoutWidget(QtGui.QWidget):
#items = [] #items = []
#for i in list(self.items.keys()): #for i in list(self.items.keys()):
#self.removeItem(i) #self.removeItem(i)

View File

@ -1,5 +1,5 @@
from ..Qt import QtGui, QtCore, QT_LIB # -*- coding: utf-8 -*-
import matplotlib from ..Qt import QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

View File

@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore, QT_LIB from ..Qt import QtGui, QtCore, QT_LIB
if QT_LIB.startswith('PyQt'): if QT_LIB.startswith('PyQt'):
from ..Qt import sip from ..Qt import sip
from .. import multiprocess as mp from .. import multiprocess as mp
from .GraphicsView import GraphicsView from .GraphicsView import GraphicsView
from .. import CONFIG_OPTIONS from .. import CONFIG_OPTIONS
import numpy as np
import mmap, tempfile, os, atexit, sys, random import mmap, tempfile, os, atexit, sys, random
__all__ = ['RemoteGraphicsView'] __all__ = ['RemoteGraphicsView']
@ -292,4 +292,3 @@ class Renderer(GraphicsView):
typ = QtCore.QEvent.Type(typ) typ = QtCore.QEvent.Type(typ)
ev = QtCore.QEvent(typ) ev = QtCore.QEvent(typ)
return super().leaveEvent(ev) return super().leaveEvent(ev)

View File

@ -1,8 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from math import isnan, isinf from math import isnan, isinf
from decimal import Decimal as D ## Use decimal to avoid accumulating floating-point errors
import decimal import decimal
import weakref
import re import re
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
@ -74,7 +72,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
'wrapping': False, 'wrapping': False,
## normal arithmetic step ## normal arithmetic step
'step': D('0.01'), ## if 'dec' is false, the spinBox steps by 'step' every time 'step': decimal.Decimal('0.01'), ## if 'dec' is false, the spinBox steps by 'step' every time
## if 'dec' is True, the step size is relative to the value ## if 'dec' is True, the step size is relative to the value
## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True) ## 'step' needs to be an integral divisor of ten, ie 'step'*n=10 for some integer value of n (but only if dec is True)
'dec': False, ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc. 'dec': False, ## if true, does decimal stepping. ie from 1-10 it steps by 'step', from 10 to 100 it steps by 10*'step', etc.
@ -94,14 +92,14 @@ class SpinBox(QtGui.QAbstractSpinBox):
'format': asUnicode("{scaledValue:.{decimals}g}{suffixGap}{siPrefix}{suffix}"), 'format': asUnicode("{scaledValue:.{decimals}g}{suffixGap}{siPrefix}{suffix}"),
'regex': fn.FLOAT_REGEX, 'regex': fn.FLOAT_REGEX,
'evalFunc': D, 'evalFunc': decimal.Decimal,
'compactHeight': True, # manually remove extra margin outside of text 'compactHeight': True, # manually remove extra margin outside of text
} }
self.decOpts = ['step', 'minStep'] self.decOpts = ['step', 'minStep']
self.val = D(asUnicode(value)) ## Value is precise decimal. Ordinary math not allowed. self.val = decimal.Decimal(asUnicode(value)) ## Value is precise decimal. Ordinary math not allowed.
self.updateText() self.updateText()
self.skipValidate = False self.skipValidate = False
self.setCorrectionMode(self.CorrectionMode.CorrectToPreviousValue) self.setCorrectionMode(self.CorrectionMode.CorrectToPreviousValue)
@ -183,7 +181,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
elif k == 'max': elif k == 'max':
self.setMaximum(v, update=False) self.setMaximum(v, update=False)
elif k in ['step', 'minStep']: elif k in ['step', 'minStep']:
self.opts[k] = D(asUnicode(v)) self.opts[k] = decimal.Decimal(asUnicode(v))
elif k == 'value': elif k == 'value':
pass ## don't set value until bounds have been set pass ## don't set value until bounds have been set
elif k == 'format': elif k == 'format':
@ -236,7 +234,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
def setMaximum(self, m, update=True): def setMaximum(self, m, update=True):
"""Set the maximum allowed value (or None for no limit)""" """Set the maximum allowed value (or None for no limit)"""
if m is not None: if m is not None:
m = D(asUnicode(m)) m = decimal.Decimal(asUnicode(m))
self.opts['bounds'][1] = m self.opts['bounds'][1] = m
if update: if update:
self.setValue() self.setValue()
@ -244,7 +242,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
def setMinimum(self, m, update=True): def setMinimum(self, m, update=True):
"""Set the minimum allowed value (or None for no limit)""" """Set the minimum allowed value (or None for no limit)"""
if m is not None: if m is not None:
m = D(asUnicode(m)) m = decimal.Decimal(asUnicode(m))
self.opts['bounds'][0] = m self.opts['bounds'][0] = m
if update: if update:
self.setValue() self.setValue()
@ -359,8 +357,8 @@ class SpinBox(QtGui.QAbstractSpinBox):
if self.opts['int']: if self.opts['int']:
value = int(value) value = int(value)
if not isinstance(value, D): if not isinstance(value, decimal.Decimal):
value = D(asUnicode(value)) value = decimal.Decimal(asUnicode(value))
prev, self.val = self.val, value prev, self.val = self.val, value
changed = not fn.eq(value, prev) # use fn.eq to handle nan changed = not fn.eq(value, prev) # use fn.eq to handle nan
@ -400,8 +398,8 @@ class SpinBox(QtGui.QAbstractSpinBox):
if isinf(self.val) or isnan(self.val): if isinf(self.val) or isnan(self.val):
return return
n = D(int(n)) ## n must be integral number of steps. n = decimal.Decimal(int(n)) ## n must be integral number of steps.
s = [D(-1), D(1)][n >= 0] ## determine sign of step s = [decimal.Decimal(-1), decimal.Decimal(1)][n >= 0] ## determine sign of step
val = self.val val = self.val
for i in range(int(abs(n))): for i in range(int(abs(n))):
@ -410,11 +408,11 @@ class SpinBox(QtGui.QAbstractSpinBox):
step = self.opts['minStep'] step = self.opts['minStep']
exp = None exp = None
else: else:
vs = [D(-1), D(1)][val >= 0] vs = [decimal.Decimal(-1), decimal.Decimal(1)][val >= 0]
#exp = D(int(abs(val*(D('1.01')**(s*vs))).log10())) #exp = decimal.Decimal(int(abs(val*(decimal.Decimal('1.01')**(s*vs))).log10()))
fudge = D('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign. fudge = decimal.Decimal('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign.
exp = abs(val * fudge).log10().quantize(1, decimal.ROUND_FLOOR) exp = abs(val * fudge).log10().quantize(1, decimal.ROUND_FLOOR)
step = self.opts['step'] * D(10)**exp step = self.opts['step'] * decimal.Decimal(10)**exp
if 'minStep' in self.opts: if 'minStep' in self.opts:
step = max(step, self.opts['minStep']) step = max(step, self.opts['minStep'])
val += s * step val += s * step
@ -423,7 +421,7 @@ class SpinBox(QtGui.QAbstractSpinBox):
val += s*self.opts['step'] val += s*self.opts['step']
if 'minStep' in self.opts and abs(val) < self.opts['minStep']: if 'minStep' in self.opts and abs(val) < self.opts['minStep']:
val = D(0) val = decimal.Decimal(0)
self.setValue(val, delaySignal=True) ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only. self.setValue(val, delaySignal=True) ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only.
def valueInRange(self, value): def valueInRange(self, value):

View File

@ -1,6 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from weakref import *
__all__ = ['TreeWidget', 'TreeWidgetItem'] __all__ = ['TreeWidget', 'TreeWidgetItem']

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from time import perf_counter from time import perf_counter
from ..Qt import QtCore, QtGui from ..Qt import QtGui
from .. import functions as fn from .. import functions as fn
__all__ = ['ValueLabel'] __all__ = ['ValueLabel']