rebased (regenerated) branch from master

This commit is contained in:
Jose Luis Cercos-Pita 2014-01-12 15:07:19 +01:00
parent 1e135aa367
commit 11278f34f3
16 changed files with 2408 additions and 1723 deletions

View File

@ -21,26 +21,42 @@
#* * #* *
#*************************************************************************** #***************************************************************************
class PlotWorkbench(Workbench): class PlotWorkbench(Workbench):
""" @brief Workbench of Plot module. Here toolbars & icons are append. """ """Workbench of Plot module."""
from plotUtils import Paths from plotUtils import Paths
import PlotGui import PlotGui
Icon = 'Icon.svg' Icon = 'Icon.svg'
MenuText = "Plot" MenuText = "Plot"
ToolTip = "The Plot module is used to edit/save output plots performed by other tools" ToolTip = ("The Plot module is used to edit/save output plots performed "
"by other tools")
def Initialize(self): def Initialize(self):
from PyQt4 import QtCore, QtGui from PySide import QtCore, QtGui
cmdlst = ["Plot_SaveFig", "Plot_Axes", "Plot_Series", "Plot_Grid", "Plot_Legend", "Plot_Labels", "Plot_Positions"] cmdlst = ["Plot_SaveFig",
self.appendToolbar(str(QtCore.QT_TRANSLATE_NOOP("Plot", "Plot edition tools")),cmdlst) "Plot_Axes",
self.appendMenu(str(QtCore.QT_TRANSLATE_NOOP("Plot", "Plot")),cmdlst) "Plot_Series",
"Plot_Grid",
"Plot_Legend",
"Plot_Labels",
"Plot_Positions"]
self.appendToolbar(str(QtCore.QT_TRANSLATE_NOOP(
"Plot",
"Plot edition tools")), cmdlst)
self.appendMenu(str(QtCore.QT_TRANSLATE_NOOP(
"Plot",
"Plot")), cmdlst)
try: try:
import matplotlib import matplotlib
except ImportError: except ImportError:
from PyQt4 import QtCore, QtGui from PySide import QtCore, QtGui
msg = QtGui.QApplication.translate("plot_console", "matplotlib not found, Plot module will be disabled", msg = QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8) "plot_console",
"matplotlib not found, Plot module will be disabled",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintMessage(msg + '\n') FreeCAD.Console.PrintMessage(msg + '\n')
Gui.addWorkbench(PlotWorkbench()) Gui.addWorkbench(PlotWorkbench())

View File

@ -21,42 +21,52 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD
import FreeCAD import FreeCAD
# PyQt4 import PySide
from PyQt4 import QtCore, QtGui from PySide import QtCore, QtGui
# Matplot lib
try: try:
import matplotlib import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure from matplotlib.figure import Figure
except ImportError: except ImportError:
msg = QtGui.QApplication.translate("plot_console", "matplotlib not found, so Plot module can not be loaded", msg = QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8) "plot_console",
"matplotlib not found, so Plot module can not be loaded",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintMessage(msg + '\n') FreeCAD.Console.PrintMessage(msg + '\n')
raise ImportError("matplotlib not installed") raise ImportError("matplotlib not installed")
def getMainWindow(): def getMainWindow():
""" getMainWindow(): Gets FreeCAD main window. """ """ Return the FreeCAD main window. """
toplevel = QtGui.qApp.topLevelWidgets() toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel: for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow": if i.metaObject().className() == "Gui::MainWindow":
return i return i
return None return None
def getMdiArea(): def getMdiArea():
""" getMdiArea(): Gets FreeCAD MdiArea. """ """ Return FreeCAD MdiArea. """
mw = getMainWindow() mw = getMainWindow()
if not mw: if not mw:
return None return None
return mw.findChild(QtGui.QMdiArea) childs = mw.children()
for c in childs:
if isinstance(c, PySide.QtGui.QMdiArea):
return c
return None
def getPlot(): def getPlot():
""" getPlot(): Gets selected Plot document if exist. """ """ Return the selected Plot document if exist. """
# Get active tab # Get active tab
mdi = getMdiArea() mdi = getMdiArea()
if not mdi: if not mdi:
@ -70,8 +80,13 @@ def getPlot():
return i return i
return None return None
def figure(winTitle="plot"): def figure(winTitle="plot"):
""" figure(winTitle="plot"): Create a new plot subwindow.\n winTitle = Tab title. """ """Create a new plot subwindow/tab.
Keyword arguments:
winTitle -- Plot tab title.
"""
mdi = getMdiArea() mdi = getMdiArea()
if not mdi: if not mdi:
return None return None
@ -80,8 +95,15 @@ def figure(winTitle="plot"):
sub.show() sub.show()
return win return win
def plot(x, y, name=None): def plot(x, y, name=None):
""" plot(x,y,name=None): Plots a new serie (as line plot)\n x = X values\n y = Y values\n name = Serie name (for legend). """ """Plots a new serie (as line plot)
Keyword arguments:
x -- X values
y -- Y values
name -- Data serie name (for legend).
"""
# Get active plot, or create another one if don't exist # Get active plot, or create another one if don't exist
plt = getPlot() plt = getPlot()
if not plt: if not plt:
@ -89,15 +111,21 @@ def plot(x,y,name=None):
# Call to plot # Call to plot
return plt.plot(x, y, name) return plt.plot(x, y, name)
def series(): def series():
""" lines(): Get all lines from selected plot. """ """Return all the lines from a selected plot."""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return [] return []
return plt.series return plt.series
def removeSerie(index): def removeSerie(index):
""" removeSerie(index): Removes a serie from plot.\n index = Index of serie to remove. """ """Remove a data serie from the active plot.
Keyword arguments:
index -- Index of the serie to remove.
"""
# Get active series # Get active series
plt = getPlot() plt = getPlot()
if not plt: if not plt:
@ -113,8 +141,15 @@ def removeSerie(index):
# Update GUI # Update GUI
plt.update() plt.update()
def legend(status=True, pos=None, fontsize=None): def legend(status=True, pos=None, fontsize=None):
""" legend(status=True): Show/Hide legend.\n status = True if legend must be shown, False otherwise.\n pos = Legend position.\n fontsize = Font size """ """Show/Hide the legend from the active plot.
Keyword arguments:
status -- True if legend must be shown, False otherwise.
pos -- Legend position.
fontsize -- Font size
"""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return return
@ -132,7 +167,7 @@ def legend(status=True, pos=None, fontsize=None):
handles = [] handles = []
names = [] names = []
for l in lines: for l in lines:
if l.name != None: if l.name is not None:
handles.append(l.line) handles.append(l.line)
names.append(l.name) names.append(l.name)
# Show the legend (at selected position or at best) # Show the legend (at selected position or at best)
@ -146,14 +181,21 @@ def legend(status=True, pos=None, fontsize=None):
# Get resultant position # Get resultant position
fax = axes.get_frame().get_extents() fax = axes.get_frame().get_extents()
fl = l.get_frame() fl = l.get_frame()
plt.legPos = ((fl._x+fl._width-fax.x0) / fax.width, (fl._y+fl._height-fax.y0) / fax.height) plt.legPos = (
(fl._x + fl._width - fax.x0) / fax.width,
(fl._y + fl._height - fax.y0) / fax.height)
# Set fontsize # Set fontsize
for t in l.get_texts(): for t in l.get_texts():
t.set_fontsize(plt.legSiz) t.set_fontsize(plt.legSiz)
plt.update() plt.update()
def grid(status=True): def grid(status=True):
""" grid(status=True): Show/Hide grid.\n status = True if grid must be shown, False otherwise. """ """Show/Hide the grid from the active plot.
Keyword arguments:
status -- True if grid must be shown, False otherwise.
"""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return return
@ -162,8 +204,13 @@ def grid(status=True):
axes.grid(status) axes.grid(status)
plt.update() plt.update()
def title(string): def title(string):
""" title(string): Setup plot title.\n string = Title to set. """ """Setup the plot title.
Keyword arguments:
string -- Plot title.
"""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return return
@ -171,8 +218,13 @@ def title(string):
axes.set_title(string) axes.set_title(string)
plt.update() plt.update()
def xlabel(string): def xlabel(string):
""" xlabel(string): Setup x label.\n string = Title to set. """ """Setup the x label.
Keyword arguments:
string -- Title to set.
"""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return return
@ -180,8 +232,13 @@ def xlabel(string):
axes.set_xlabel(string) axes.set_xlabel(string)
plt.update() plt.update()
def ylabel(string): def ylabel(string):
""" ylabel(string): Setup y label.\n string = Title to set. """ """Setup the y label.
Keyword arguments:
string -- Title to set.
"""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return return
@ -189,27 +246,36 @@ def ylabel(string):
axes.set_ylabel(string) axes.set_ylabel(string)
plt.update() plt.update()
def axesList(): def axesList():
""" axesList(): Gets plot axes list. """ """Return the plot axes sets list. """
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return [] return []
return plt.axesList return plt.axesList
def axes(): def axes():
""" axes(): Gets active plot axes. """ """Return the active plot axes."""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return None return None
return plt.axes return plt.axes
def addNewAxes(rect=None, frameon=True, patchcolor='none'): def addNewAxes(rect=None, frameon=True, patchcolor='none'):
""" addNewAxes(pos=None, frameon=True): Add new axes to plot, setting it as active one.\n rect = Axes area, None to copy last axes data.\n frameon = True to show frame, False otherwise.\n patchcolor = Patch color, 'none' for transparent plot. """ """Add new axes to plot, setting it as the active one.
Keyword arguments:
rect -- Axes area, None to copy from the last axes data.
frameon -- True to show frame, False otherwise.
patchcolor -- Patch color, 'none' for transparent plot.
"""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return None return None
fig = plt.fig fig = plt.fig
if rect == None: if rect is None:
rect = plt.axes.get_position() rect = plt.axes.get_position()
ax = fig.add_axes(rect, frameon=frameon) ax = fig.add_axes(rect, frameon=frameon)
ax.xaxis.set_ticks_position('bottom') ax.xaxis.set_ticks_position('bottom')
@ -222,8 +288,15 @@ def addNewAxes(rect=None, frameon=True, patchcolor='none'):
plt.update() plt.update()
return ax return ax
def save(path, figsize=None, dpi=None): def save(path, figsize=None, dpi=None):
""" save(path): Save plot.\n path = Destination file path.\n figsize = w,h figure size tuple in inches.\n dpi = Dots per inch.""" """Save plot.
Keyword arguments:
path -- Destination file path.
figsize -- w,h figure size tuple in inches.
dpi -- Dots per inch.
"""
plt = getPlot() plt = getPlot()
if not plt: if not plt:
return return
@ -242,9 +315,17 @@ def save(path, figsize=None, dpi=None):
fig.set_dpi(dpiBack) fig.set_dpi(dpiBack)
plt.update() plt.update()
class Line(): class Line():
def __init__(self, axes, x, y, name): def __init__(self, axes, x, y, name):
""" __init__(axes, x, y, name): Construct new plot serie.\n axes = Active axes\n x = X values\n y = Y values\n name = Serie name (for legend). """ """Construct a new plot serie.
Keyword arguments:
axes -- Active axes
x -- X values
y -- Y values
name -- Data serie name (for legend).
"""
self.axes = axes self.axes = axes
self.x = x self.x = x
self.y = y self.y = y
@ -253,16 +334,35 @@ class Line():
self.line, = axes.plot(x, y) self.line, = axes.plot(x, y)
def setp(self, prop, value): def setp(self, prop, value):
""" setp(prop, value): Change line property value.\n prop = Property name.\n value = New property value. """ """Change a line property value.
Keyword arguments:
prop -- Property name.
value -- New property value.
"""
plt.setp(self.line, prop, value) plt.setp(self.line, prop, value)
def getp(self, prop): def getp(self, prop):
""" getp(prop): Get property value.\n prop = Property name.""" """Get line property value.
Keyword arguments:
prop -- Property name.
"""
return plt.getp(self.line, prop) return plt.getp(self.line, prop)
class Plot(QtGui.QWidget): class Plot(QtGui.QWidget):
def __init__(self, winTitle="plot", parent = None, flags = QtCore.Qt.WindowFlags(0)): def __init__(self,
""" __init__(winTitle="plot", parent = None, flags = Qt.WindowFlags(0)): Construct a new plot widget.\n winTitle = Tab title.\n parent = Widget parent.\n flags = QWidget flags""" winTitle="plot",
parent=None,
flags=QtCore.Qt.WindowFlags(0)):
"""Construct a new plot widget.
Keyword arguments:
winTitle -- Tab title.
parent -- Widget parent.
flags -- QWidget flags
"""
QtGui.QWidget.__init__(self, parent, flags) QtGui.QWidget.__init__(self, parent, flags)
self.setWindowTitle(winTitle) self.setWindowTitle(winTitle)
# Create matplotlib canvas # Create matplotlib canvas
@ -290,7 +390,12 @@ class Plot(QtGui.QWidget):
self.grid = False self.grid = False
def plot(self, x, y, name=None): def plot(self, x, y, name=None):
""" plot(self, x, y, name=None): Plot a new line and return it.\n x = X values\n y = Y values\n name = Serie name (for legend). """ """Plot a new line and return it.
Keyword arguments:
x -- X values
y -- Y values
name -- Serie name (for legend). """
l = Line(self.axes, x, y, name) l = Line(self.axes, x, y, name)
self.series.append(l) self.series.append(l)
# Update window # Update window
@ -298,7 +403,7 @@ class Plot(QtGui.QWidget):
return l return l
def update(self): def update(self):
""" update(): Updates plot. """ """Update the plot, redrawing the canvas."""
if not self.skip: if not self.skip:
self.skip = True self.skip = True
if self.legend: if self.legend:
@ -307,15 +412,18 @@ class Plot(QtGui.QWidget):
self.skip = False self.skip = False
def isGrid(self): def isGrid(self):
""" isGrid(): Return True if Grid is active, False otherwise. """ """Return True if Grid is active, False otherwise."""
return bool(self.grid) return bool(self.grid)
def isLegend(self): def isLegend(self):
""" isLegend(): Return True if Legend is active, False otherwise. """ """Return True if Legend is active, False otherwise."""
return bool(self.legend) return bool(self.legend)
def setActiveAxes(self, index): def setActiveAxes(self, index):
""" setActiveAxes(index): Change current active axes.\n index = Index of the new active axes. """ """Change the current active axes.
Keyword arguments:
index -- Index of the new active axes set.
"""
self.axes = self.axesList[index] self.axes = self.axesList[index]
self.fig.sca(self.axes) self.fig.sca(self.axes)

View File

@ -21,28 +21,18 @@
#* * #* *
#*************************************************************************** #***************************************************************************
from PyQt4 import QtCore, QtGui import PySide
import FreeCAD, FreeCADGui, os from PySide import QtCore, QtGui
import FreeCAD
import FreeCADGui
import os
# Load resources
import Plot_rc import Plot_rc
FreeCADGui.addLanguagePath(":/Plot/translations") FreeCADGui.addLanguagePath(":/Plot/translations")
FreeCADGui.addIconPath(":/Plot/icons") FreeCADGui.addIconPath(":/Plot/icons")
"""
# Setup tranlations
from plotUtils import Paths
path = Paths.translationsPath()
FreeCADGui.addLanguagePath(path)
import os
import FreeCAD
translator = QtCore.QTranslator()
dirList=os.listdir(path)
for fname in dirList:
valid = translator.load(os.path.join(path, fname))
if valid:
QtGui.QApplication.installTranslator(translator)
"""
class Save: class Save:
def Activated(self): def Activated(self):
@ -52,9 +42,16 @@ class Save:
def GetResources(self): def GetResources(self):
# from plotUtils import Paths # from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Save.svg" # IconPath = Paths.iconsPath() + "/Save.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_SaveFig", "Save plot") MenuText = QtCore.QT_TRANSLATE_NOOP(
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_SaveFig", "Save plot as image file") "Plot_SaveFig",
return {'Pixmap' : 'Save', 'MenuText': MenuText, 'ToolTip': ToolTip} "Save plot")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_SaveFig",
"Save the plot as an image file")
return {'Pixmap': 'Save',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Axes: class Axes:
def Activated(self): def Activated(self):
@ -62,11 +59,16 @@ class Axes:
plotAxes.load() plotAxes.load()
def GetResources(self): def GetResources(self):
# from plotUtils import Paths MenuText = QtCore.QT_TRANSLATE_NOOP(
# IconPath = Paths.iconsPath() + "/Axes.svg" "Plot_Axes",
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Axes", "Configure axes") "Configure axes")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Axes", "Configure axes parameters") ToolTip = QtCore.QT_TRANSLATE_NOOP(
return {'Pixmap' : 'Axes', 'MenuText': MenuText, 'ToolTip': ToolTip} "Plot_Axes",
"Configure the axes parameters")
return {'Pixmap': 'Axes',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Series: class Series:
def Activated(self): def Activated(self):
@ -76,17 +78,27 @@ class Series:
def GetResources(self): def GetResources(self):
# from plotUtils import Paths # from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Series.svg" # IconPath = Paths.iconsPath() + "/Series.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Series", "Configure series") MenuText = QtCore.QT_TRANSLATE_NOOP(
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Series", "Configure series drawing style and label") "Plot_Series",
return {'Pixmap' : 'Series', 'MenuText': MenuText, 'ToolTip': ToolTip} "Configure series")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Series",
"Configure series drawing style and label")
return {'Pixmap': 'Series',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Grid: class Grid:
def Activated(self): def Activated(self):
import Plot import Plot
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
msg = QtGui.QApplication.translate("plot_console", "Grid must be activated on top of a plot document", msg = QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8) "plot_console",
"The grid must be activated on top of a plot document",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintError(msg + "\n") FreeCAD.Console.PrintError(msg + "\n")
return return
flag = plt.isGrid() flag = plt.isGrid()
@ -95,28 +107,43 @@ class Grid:
def GetResources(self): def GetResources(self):
# from plotUtils import Paths # from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Grid.svg" # IconPath = Paths.iconsPath() + "/Grid.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Grid", "Show/Hide grid") MenuText = QtCore.QT_TRANSLATE_NOOP(
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Grid", "Show/Hide grid on selected plot") "Plot_Grid",
return {'Pixmap' : 'Grid', 'MenuText': MenuText, 'ToolTip': ToolTip} "Show/Hide grid")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Grid",
"Show/Hide grid on selected plot")
return {'Pixmap': 'Grid',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Legend: class Legend:
def Activated(self): def Activated(self):
import Plot import Plot
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
msg = QtGui.QApplication.translate("plot_console", "Legend must be activated on top of a plot document", msg = QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8) "plot_console",
"The legend must be activated on top of a plot document",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintError(msg + "\n") FreeCAD.Console.PrintError(msg + "\n")
return return
flag = plt.isLegend() flag = plt.isLegend()
Plot.legend(not flag) Plot.legend(not flag)
def GetResources(self): def GetResources(self):
# from plotUtils import Paths MenuText = QtCore.QT_TRANSLATE_NOOP(
# IconPath = Paths.iconsPath() + "/Legend.svg" "Plot_Legend",
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Legend", "Show/Hide legend") "Show/Hide legend")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Legend", "Show/Hide legend on selected plot") ToolTip = QtCore.QT_TRANSLATE_NOOP(
return {'Pixmap' : 'Legend', 'MenuText': MenuText, 'ToolTip': ToolTip} "Plot_Legend",
"Show/Hide legend on selected plot")
return {'Pixmap': 'Legend',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Labels: class Labels:
def Activated(self): def Activated(self):
@ -124,11 +151,16 @@ class Labels:
plotLabels.load() plotLabels.load()
def GetResources(self): def GetResources(self):
# from plotUtils import Paths MenuText = QtCore.QT_TRANSLATE_NOOP(
# IconPath = Paths.iconsPath() + "/Labels.svg" "Plot_Labels",
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Labels", "Set labels") "Set labels")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Labels", "Set title and axes labels") ToolTip = QtCore.QT_TRANSLATE_NOOP(
return {'Pixmap' : 'Labels', 'MenuText': MenuText, 'ToolTip': ToolTip} "Plot_Labels",
"Set title and axes labels")
return {'Pixmap': 'Labels',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Positions: class Positions:
def Activated(self): def Activated(self):
@ -136,11 +168,16 @@ class Positions:
plotPositions.load() plotPositions.load()
def GetResources(self): def GetResources(self):
# from plotUtils import Paths MenuText = QtCore.QT_TRANSLATE_NOOP(
# IconPath = Paths.iconsPath() + "/Positions.svg" "Plot_Positions",
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Positions", "Set positions and sizes") "Set positions and sizes")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Positions", "Set labels and legend positions and sizes") ToolTip = QtCore.QT_TRANSLATE_NOOP(
return {'Pixmap' : 'Positions', 'MenuText': MenuText, 'ToolTip': ToolTip} "Plot_Positions",
"Set labels and legend positions and sizes")
return {'Pixmap': 'Positions',
'MenuText': MenuText,
'ToolTip': ToolTip}
FreeCADGui.addCommand('Plot_SaveFig', Save()) FreeCADGui.addCommand('Plot_SaveFig', Save())
FreeCADGui.addCommand('Plot_Axes', Axes()) FreeCADGui.addCommand('Plot_Axes', Axes())
@ -149,4 +186,3 @@ FreeCADGui.addCommand('Plot_Grid', Grid())
FreeCADGui.addCommand('Plot_Legend', Legend()) FreeCADGui.addCommand('Plot_Legend', Legend())
FreeCADGui.addCommand('Plot_Labels', Labels()) FreeCADGui.addCommand('Plot_Labels', Labels())
FreeCADGui.addCommand('Plot_Positions', Positions()) FreeCADGui.addCommand('Plot_Positions', Positions())

View File

@ -7,7 +7,7 @@
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore from PySide import QtCore
qt_resource_data = "\ qt_resource_data = "\
\x00\x00\x00\x10\ \x00\x00\x00\x10\

View File

@ -21,15 +21,15 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD as App import FreeCAD as App
import FreeCADGui as Gui import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore from PySide import QtGui, QtCore
# Module
import Plot import Plot
from plotUtils import Paths from plotUtils import Paths
class TaskPanel: class TaskPanel:
def __init__(self): def __init__(self):
self.ui = Paths.modulePath() + "/plotAxes/TaskPanel.ui" self.ui = Paths.modulePath() + "/plotAxes/TaskPanel.ui"
@ -65,25 +65,25 @@ class TaskPanel:
def setupUi(self): def setupUi(self):
mw = self.getMainWindow() mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel") form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = form.findChild(QtGui.QSpinBox, "axesIndex")
form.new = form.findChild(QtGui.QPushButton, "newAxesButton")
form.remove = form.findChild(QtGui.QPushButton, "delAxesButton")
form.all = form.findChild(QtGui.QCheckBox, "allAxes")
form.xMin = form.findChild(QtGui.QSlider, "posXMin")
form.xMax = form.findChild(QtGui.QSlider, "posXMax")
form.yMin = form.findChild(QtGui.QSlider, "posYMin")
form.yMax = form.findChild(QtGui.QSlider, "posYMax")
form.xAlign = form.findChild(QtGui.QComboBox, "xAlign")
form.yAlign = form.findChild(QtGui.QComboBox, "yAlign")
form.xOffset = form.findChild(QtGui.QSpinBox, "xOffset")
form.yOffset = form.findChild(QtGui.QSpinBox, "yOffset")
form.xAuto = form.findChild(QtGui.QCheckBox, "xAuto")
form.yAuto = form.findChild(QtGui.QCheckBox, "yAuto")
form.xSMin = form.findChild(QtGui.QLineEdit, "xMin")
form.xSMax = form.findChild(QtGui.QLineEdit, "xMax")
form.ySMin = form.findChild(QtGui.QLineEdit, "yMin")
form.ySMax = form.findChild(QtGui.QLineEdit, "yMax")
self.form = form self.form = form
form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
form.new = self.widget(QtGui.QPushButton, "newAxesButton")
form.remove = self.widget(QtGui.QPushButton, "delAxesButton")
form.all = self.widget(QtGui.QCheckBox, "allAxes")
form.xMin = self.widget(QtGui.QSlider, "posXMin")
form.xMax = self.widget(QtGui.QSlider, "posXMax")
form.yMin = self.widget(QtGui.QSlider, "posYMin")
form.yMax = self.widget(QtGui.QSlider, "posYMax")
form.xAlign = self.widget(QtGui.QComboBox, "xAlign")
form.yAlign = self.widget(QtGui.QComboBox, "yAlign")
form.xOffset = self.widget(QtGui.QSpinBox, "xOffset")
form.yOffset = self.widget(QtGui.QSpinBox, "yOffset")
form.xAuto = self.widget(QtGui.QCheckBox, "xAuto")
form.yAuto = self.widget(QtGui.QCheckBox, "yAuto")
form.xSMin = self.widget(QtGui.QLineEdit, "xMin")
form.xSMax = self.widget(QtGui.QLineEdit, "xMax")
form.ySMin = self.widget(QtGui.QLineEdit, "yMin")
form.ySMax = self.widget(QtGui.QLineEdit, "yMax")
self.retranslateUi() self.retranslateUi()
# Look for active axes if can # Look for active axes if can
axId = 0 axId = 0
@ -93,173 +93,339 @@ class TaskPanel:
axId = axId + 1 axId = axId + 1
form.axId.setValue(axId) form.axId.setValue(axId)
self.updateUI() self.updateUI()
QtCore.QObject.connect(form.axId, QtCore.SIGNAL('valueChanged(int)'),self.onAxesId) QtCore.QObject.connect(form.axId,
QtCore.QObject.connect(form.new, QtCore.SIGNAL("pressed()"),self.onNew) QtCore.SIGNAL('valueChanged(int)'),
QtCore.QObject.connect(form.remove, QtCore.SIGNAL("pressed()"),self.onRemove) self.onAxesId)
QtCore.QObject.connect(form.xMin, QtCore.SIGNAL("valueChanged(int)"),self.onDims) QtCore.QObject.connect(form.new,
QtCore.QObject.connect(form.xMax, QtCore.SIGNAL("valueChanged(int)"),self.onDims) QtCore.SIGNAL("pressed()"),
QtCore.QObject.connect(form.yMin, QtCore.SIGNAL("valueChanged(int)"),self.onDims) self.onNew)
QtCore.QObject.connect(form.yMax, QtCore.SIGNAL("valueChanged(int)"),self.onDims) QtCore.QObject.connect(form.remove,
QtCore.QObject.connect(form.xAlign, QtCore.SIGNAL("currentIndexChanged(int)"),self.onAlign) QtCore.SIGNAL("pressed()"),
QtCore.QObject.connect(form.yAlign, QtCore.SIGNAL("currentIndexChanged(int)"),self.onAlign) self.onRemove)
QtCore.QObject.connect(form.xOffset,QtCore.SIGNAL("valueChanged(int)"),self.onOffset) QtCore.QObject.connect(form.xMin,
QtCore.QObject.connect(form.yOffset,QtCore.SIGNAL("valueChanged(int)"),self.onOffset) QtCore.SIGNAL("valueChanged(int)"),
QtCore.QObject.connect(form.xAuto, QtCore.SIGNAL("stateChanged(int)"),self.onScales) self.onDims)
QtCore.QObject.connect(form.yAuto, QtCore.SIGNAL("stateChanged(int)"),self.onScales) QtCore.QObject.connect(form.xMax,
QtCore.QObject.connect(form.xSMin, QtCore.SIGNAL("editingFinished()"),self.onScales) QtCore.SIGNAL("valueChanged(int)"),
QtCore.QObject.connect(form.xSMax, QtCore.SIGNAL("editingFinished()"),self.onScales) self.onDims)
QtCore.QObject.connect(form.ySMin, QtCore.SIGNAL("editingFinished()"),self.onScales) QtCore.QObject.connect(form.yMin,
QtCore.QObject.connect(form.ySMax, QtCore.SIGNAL("editingFinished()"),self.onScales) QtCore.SIGNAL("valueChanged(int)"),
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) self.onDims)
QtCore.QObject.connect(form.yMax,
QtCore.SIGNAL("valueChanged(int)"),
self.onDims)
QtCore.QObject.connect(form.xAlign,
QtCore.SIGNAL("currentIndexChanged(int)"),
self.onAlign)
QtCore.QObject.connect(form.yAlign,
QtCore.SIGNAL("currentIndexChanged(int)"),
self.onAlign)
QtCore.QObject.connect(form.xOffset,
QtCore.SIGNAL("valueChanged(int)"),
self.onOffset)
QtCore.QObject.connect(form.yOffset,
QtCore.SIGNAL("valueChanged(int)"),
self.onOffset)
QtCore.QObject.connect(form.xAuto,
QtCore.SIGNAL("stateChanged(int)"),
self.onScales)
QtCore.QObject.connect(form.yAuto,
QtCore.SIGNAL("stateChanged(int)"),
self.onScales)
QtCore.QObject.connect(form.xSMin,
QtCore.SIGNAL("editingFinished()"),
self.onScales)
QtCore.QObject.connect(form.xSMax,
QtCore.SIGNAL("editingFinished()"),
self.onScales)
QtCore.QObject.connect(form.ySMin,
QtCore.SIGNAL("editingFinished()"),
self.onScales)
QtCore.QObject.connect(form.ySMax,
QtCore.SIGNAL("editingFinished()"),
self.onScales)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
return False return False
def getMainWindow(self): def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets() toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel: for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow": if i.metaObject().className() == "Gui::MainWindow":
return i return i
raise Exception("No main window found") raise Exception("No main window found")
def retranslateUi(self): def widget(self, class_id, name):
""" Set user interface locale strings. """Return the selected widget.
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
""" """
self.form.setWindowTitle(QtGui.QApplication.translate("plot_axes", "Configure axes", mw = self.getMainWindow()
None,QtGui.QApplication.UnicodeUTF8)) form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.findChild(QtGui.QLabel, "axesLabel").setText(QtGui.QApplication.translate("plot_axes", "Active axes", return form.findChild(class_id, name)
None,QtGui.QApplication.UnicodeUTF8))
self.form.all.setText(QtGui.QApplication.translate("plot_axes", "Apply to all axes", def retranslateUi(self):
None,QtGui.QApplication.UnicodeUTF8)) """Set the user interface locale strings.
self.form.findChild(QtGui.QLabel, "dimLabel").setText(QtGui.QApplication.translate("plot_axes", "Dimensions", """
None,QtGui.QApplication.UnicodeUTF8)) form = self.form
self.form.findChild(QtGui.QLabel, "xPosLabel").setText(QtGui.QApplication.translate("plot_axes", "X axis position", form.setWindowTitle(QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_axes",
self.form.findChild(QtGui.QLabel, "yPosLabel").setText(QtGui.QApplication.translate("plot_axes", "Y axis position", "Configure axes",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.findChild(QtGui.QLabel, "scalesLabel").setText(QtGui.QApplication.translate("plot_axes", "Scales", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "axesLabel").setText(
self.form.xAuto.setText(QtGui.QApplication.translate("plot_axes", "X auto", QtGui.QApplication.translate("plot_axes",
None,QtGui.QApplication.UnicodeUTF8)) "Active axes",
self.form.yAuto.setText(QtGui.QApplication.translate("plot_axes", "Y auto", None,
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QCheckBox, "allAxes").setText(QtGui.QApplication.translate("plot_axes", "Apply to all axes", self.widget(QtGui.QCheckBox, "allAxes").setText(
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.translate("plot_axes",
self.form.findChild(QtGui.QLabel, "dimLabel").setText(QtGui.QApplication.translate("plot_axes", "Dimensions", "Apply to all axes",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.findChild(QtGui.QLabel, "xPosLabel").setText(QtGui.QApplication.translate("plot_axes", "X axis position", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "dimLabel").setText(
self.form.findChild(QtGui.QLabel, "yPosLabel").setText(QtGui.QApplication.translate("plot_axes", "Y axis position", QtGui.QApplication.translate("plot_axes",
None,QtGui.QApplication.UnicodeUTF8)) "Dimensions",
self.form.axId.setToolTip(QtGui.QApplication.translate("plot_axes", "Index of the active axes", None,
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.UnicodeUTF8))
self.form.new.setToolTip(QtGui.QApplication.translate("plot_axes", "Add new axes to the plot", self.widget(QtGui.QLabel, "xPosLabel").setText(
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.translate("plot_axes",
self.form.remove.setToolTip(QtGui.QApplication.translate("plot_axes", "Remove selected axes", "X axis position",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.all.setToolTip(QtGui.QApplication.translate("plot_axes", "Check it to apply transformations to all axes", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "yPosLabel").setText(
self.form.xMin.setToolTip(QtGui.QApplication.translate("plot_axes", "Left bound of axes", QtGui.QApplication.translate("plot_axes",
None,QtGui.QApplication.UnicodeUTF8)) "Y axis position",
self.form.xMax.setToolTip(QtGui.QApplication.translate("plot_axes", "Right bound of axes", None,
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.UnicodeUTF8))
self.form.yMin.setToolTip(QtGui.QApplication.translate("plot_axes", "Bottom bound of axes", self.widget(QtGui.QLabel, "scalesLabel").setText(
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.translate("plot_axes",
self.form.yMax.setToolTip(QtGui.QApplication.translate("plot_axes", "Top bound of axes", "Scales",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.xOffset.setToolTip(QtGui.QApplication.translate("plot_axes", "Outward offset of X axis", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QCheckBox, "xAuto").setText(
self.form.yOffset.setToolTip(QtGui.QApplication.translate("plot_axes", "Outward offset of Y axis", QtGui.QApplication.translate("plot_axes",
None,QtGui.QApplication.UnicodeUTF8)) "X auto",
self.form.xAuto.setToolTip(QtGui.QApplication.translate("plot_axes", "X axis scale autoselection", None,
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.UnicodeUTF8))
self.form.yAuto.setToolTip(QtGui.QApplication.translate("plot_axes", "Y axis scale autoselection", self.widget(QtGui.QCheckBox, "yAuto").setText(
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.translate("plot_axes",
"Y auto",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QCheckBox, "allAxes").setText(
QtGui.QApplication.translate("plot_axes",
"Apply to all axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "dimLabel").setText(
QtGui.QApplication.translate("plot_axes",
"Dimensions",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "xPosLabel").setText(
QtGui.QApplication.translate("plot_axes",
"X axis position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "yPosLabel").setText(
QtGui.QApplication.translate("plot_axes",
"Y axis position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "axesIndex").setToolTip(
QtGui.QApplication.translate("plot_axes",
"Index of the active axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "newAxesButton").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Add new axes to the plot",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "delAxesButton").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Remove selected axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QCheckBox, "allAxes").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Check it to apply transformations to all axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSlider, "posXMin").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Left bound of axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSlider, "posXMax").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Right bound of axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSlider, "posYMin").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Bottom bound of axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSlider, "posYMax").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Top bound of axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "xOffset").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Outward offset of X axis",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "yOffset").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Outward offset of Y axis",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QCheckBox, "xAuto").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"X axis scale autoselection",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QCheckBox, "yAuto").setToolTip(
QtGui.QApplication.translate(
"plot_axes",
"Y axis scale autoselection",
None,
QtGui.QApplication.UnicodeUTF8))
def onAxesId(self, value): def onAxesId(self, value):
"""Executed when axes index is modified.""" """Executed when axes index is modified."""
if not self.skip: if not self.skip:
self.skip = True self.skip = True
# UI control in some special plot cases # No active plot case
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
self.skip = False self.skip = False
return return
# UI control in most cases # Get again all the subwidgets (to avoid PySide Pitfalls)
self.form.axId.setMaximum(len(plt.axesList)) mw = self.getMainWindow()
if self.form.axId.value() >= len(plt.axesList): form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.axId.setValue(len(plt.axesList)-1) form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
form.axId.setMaximum(len(plt.axesList))
if form.axId.value() >= len(plt.axesList):
form.axId.setValue(len(plt.axesList) - 1)
# Send new control to Plot instance # Send new control to Plot instance
plt.setActiveAxes(self.form.axId.value()) plt.setActiveAxes(form.axId.value())
self.updateUI() self.updateUI()
self.skip = False self.skip = False
def onNew(self): def onNew(self):
"""Executed when new axes must be created.""" """Executed when new axes must be created."""
# Ensure that we can work
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
Plot.addNewAxes() Plot.addNewAxes()
self.form.axId.setValue(len(plt.axesList)-1) form.axId.setValue(len(plt.axesList) - 1)
plt.update() plt.update()
def onRemove(self): def onRemove(self):
"""Executed when axes must be deleted.""" """Executed when axes must be deleted."""
# Ensure taht we can work
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
# Don't remove first axes # Don't remove first axes
if not self.form.axId.value(): if not form.axId.value():
msg = QtGui.QApplication.translate("plot_console", "Axes 0 can not be deleted", msg = QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8) "plot_console",
"Axes 0 can not be deleted",
None,
QtGui.QApplication.UnicodeUTF8)
App.Console.PrintError(msg + "\n") App.Console.PrintError(msg + "\n")
return return
# Remove axes # Remove axes
ax = plt.axes ax = plt.axes
ax.set_axis_off() ax.set_axis_off()
plt.axesList.pop(self.form.axId.value()) plt.axesList.pop(form.axId.value())
# Ensure that active axes is correct # Ensure that active axes is correct
index = min(self.form.axId.value(), len(plt.axesList)-1) index = min(form.axId.value(), len(plt.axesList) - 1)
self.form.axId.setValue(index) form.axId.setValue(index)
plt.update() plt.update()
def onDims(self, value): def onDims(self, value):
"""Executed when axes dims have been modified.""" """Executed when axes dims have been modified."""
# Get apply environment # Ensure that we can work
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.all = self.widget(QtGui.QCheckBox, "allAxes")
form.xMin = self.widget(QtGui.QSlider, "posXMin")
form.xMax = self.widget(QtGui.QSlider, "posXMax")
form.yMin = self.widget(QtGui.QSlider, "posYMin")
form.yMax = self.widget(QtGui.QSlider, "posYMax")
axesList = [plt.axes] axesList = [plt.axes]
if self.form.all.isChecked(): if form.all.isChecked():
axesList = plt.axesList axesList = plt.axesList
# Set new dimensions # Set new dimensions
xmin = self.form.xMin.value() / 100.0 xmin = form.xMin.value() / 100.0
xmax = self.form.xMax.value() / 100.0 xmax = form.xMax.value() / 100.0
ymin = self.form.yMin.value() / 100.0 ymin = form.yMin.value() / 100.0
ymax = self.form.yMax.value() / 100.0 ymax = form.yMax.value() / 100.0
for axes in axesList: for axes in axesList:
axes.set_position([xmin, ymin, xmax - xmin, ymax - ymin]) axes.set_position([xmin, ymin, xmax - xmin, ymax - ymin])
plt.update() plt.update()
def onAlign(self, value): def onAlign(self, value):
"""Executed when axes align have been modified.""" """Executed when axes align have been modified."""
# Get apply environment # Ensure that we can work
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.all = self.widget(QtGui.QCheckBox, "allAxes")
form.xAlign = self.widget(QtGui.QComboBox, "xAlign")
form.yAlign = self.widget(QtGui.QComboBox, "yAlign")
axesList = [plt.axes] axesList = [plt.axes]
if self.form.all.isChecked(): if form.all.isChecked():
axesList = plt.axesList axesList = plt.axesList
# Set new alignement # Set new alignement
for axes in axesList: for axes in axesList:
if self.form.xAlign.currentIndex() == 0: if form.xAlign.currentIndex() == 0:
axes.xaxis.tick_bottom() axes.xaxis.tick_bottom()
axes.spines['bottom'].set_color((0.0, 0.0, 0.0)) axes.spines['bottom'].set_color((0.0, 0.0, 0.0))
axes.spines['top'].set_color('none') axes.spines['top'].set_color('none')
@ -271,7 +437,7 @@ class TaskPanel:
axes.spines['bottom'].set_color('none') axes.spines['bottom'].set_color('none')
axes.xaxis.set_ticks_position('top') axes.xaxis.set_ticks_position('top')
axes.xaxis.set_label_position('top') axes.xaxis.set_label_position('top')
if self.form.yAlign.currentIndex() == 0: if form.yAlign.currentIndex() == 0:
axes.yaxis.tick_left() axes.yaxis.tick_left()
axes.spines['left'].set_color((0.0, 0.0, 0.0)) axes.spines['left'].set_color((0.0, 0.0, 0.0))
axes.spines['right'].set_color('none') axes.spines['right'].set_color('none')
@ -287,13 +453,20 @@ class TaskPanel:
def onOffset(self, value): def onOffset(self, value):
"""Executed when axes offsets have been modified.""" """Executed when axes offsets have been modified."""
# Get apply environment # Ensure that we can work
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.all = self.widget(QtGui.QCheckBox, "allAxes")
form.xOffset = self.widget(QtGui.QSpinBox, "xOffset")
form.yOffset = self.widget(QtGui.QSpinBox, "yOffset")
axesList = [plt.axes] axesList = [plt.axes]
if self.form.all.isChecked(): if form.all.isChecked():
axesList = plt.axesList axesList = plt.axesList
# Set new offset # Set new offset
for axes in axesList: for axes in axesList:
@ -303,9 +476,9 @@ class TaskPanel:
y = axes.get_ylabel() y = axes.get_ylabel()
for loc, spine in axes.spines.iteritems(): for loc, spine in axes.spines.iteritems():
if loc in ['bottom', 'top']: if loc in ['bottom', 'top']:
spine.set_position(('outward',self.form.xOffset.value())) spine.set_position(('outward', form.xOffset.value()))
if loc in ['left', 'right']: if loc in ['left', 'right']:
spine.set_position(('outward',self.form.yOffset.value())) spine.set_position(('outward', form.yOffset.value()))
# Now we can restore axes labels # Now we can restore axes labels
Plot.xlabel(unicode(x)) Plot.xlabel(unicode(x))
Plot.ylabel(unicode(y)) Plot.ylabel(unicode(y))
@ -313,62 +486,73 @@ class TaskPanel:
def onScales(self): def onScales(self):
"""Executed when axes scales have been modified.""" """Executed when axes scales have been modified."""
# Get apply environment # Ensure that we can work
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.all = self.widget(QtGui.QCheckBox, "allAxes")
form.xAuto = self.widget(QtGui.QCheckBox, "xAuto")
form.yAuto = self.widget(QtGui.QCheckBox, "yAuto")
form.xSMin = self.widget(QtGui.QLineEdit, "xMin")
form.xSMax = self.widget(QtGui.QLineEdit, "xMax")
form.ySMin = self.widget(QtGui.QLineEdit, "yMin")
form.ySMax = self.widget(QtGui.QLineEdit, "yMax")
axesList = [plt.axes] axesList = [plt.axes]
if self.form.all.isChecked(): if form.all.isChecked():
axesList = plt.axesList axesList = plt.axesList
if not self.skip: if not self.skip:
self.skip = True self.skip = True
# X axis # X axis
if self.form.xAuto.isChecked(): if form.xAuto.isChecked():
for ax in axesList: for ax in axesList:
ax.set_autoscalex_on(True) ax.set_autoscalex_on(True)
self.form.xSMin.setEnabled(False) form.xSMin.setEnabled(False)
self.form.xSMax.setEnabled(False) form.xSMax.setEnabled(False)
lim = plt.axes.get_xlim() lim = plt.axes.get_xlim()
self.form.xSMin.setText(str(lim[0])) form.xSMin.setText(str(lim[0]))
self.form.xSMax.setText(str(lim[1])) form.xSMax.setText(str(lim[1]))
else: else:
self.form.xSMin.setEnabled(True) form.xSMin.setEnabled(True)
self.form.xSMax.setEnabled(True) form.xSMax.setEnabled(True)
try: try:
xMin = float(self.form.xSMin.text()) xMin = float(form.xSMin.text())
except: except:
xMin = plt.axes.get_xlim()[0] xMin = plt.axes.get_xlim()[0]
self.form.xSMin.setText(str(xMin)) form.xSMin.setText(str(xMin))
try: try:
xMax = float(self.form.xSMax.text()) xMax = float(form.xSMax.text())
except: except:
xMax = plt.axes.get_xlim()[1] xMax = plt.axes.get_xlim()[1]
self.form.xSMax.setText(str(xMax)) form.xSMax.setText(str(xMax))
for ax in axesList: for ax in axesList:
ax.set_xlim((xMin, xMax)) ax.set_xlim((xMin, xMax))
# Y axis # Y axis
if self.form.yAuto.isChecked(): if form.yAuto.isChecked():
for ax in axesList: for ax in axesList:
ax.set_autoscaley_on(True) ax.set_autoscaley_on(True)
self.form.ySMin.setEnabled(False) form.ySMin.setEnabled(False)
self.form.ySMax.setEnabled(False) form.ySMax.setEnabled(False)
lim = plt.axes.get_ylim() lim = plt.axes.get_ylim()
self.form.ySMin.setText(str(lim[0])) form.ySMin.setText(str(lim[0]))
self.form.ySMax.setText(str(lim[1])) form.ySMax.setText(str(lim[1]))
else: else:
self.form.ySMin.setEnabled(True) form.ySMin.setEnabled(True)
self.form.ySMax.setEnabled(True) form.ySMax.setEnabled(True)
try: try:
yMin = float(self.form.ySMin.text()) yMin = float(form.ySMin.text())
except: except:
yMin = plt.axes.get_ylim()[0] yMin = plt.axes.get_ylim()[0]
self.form.ySMin.setText(str(yMin)) form.ySMin.setText(str(yMin))
try: try:
yMax = float(self.form.ySMax.text()) yMax = float(form.ySMax.text())
except: except:
yMax = plt.axes.get_ylim()[1] yMax = plt.axes.get_ylim()[1]
self.form.ySMax.setText(str(yMax)) form.ySMax.setText(str(yMax))
for ax in axesList: for ax in axesList:
ax.set_ylim((yMin, yMax)) ax.set_ylim((yMin, yMax))
plt.update() plt.update()
@ -376,7 +560,9 @@ class TaskPanel:
def onMdiArea(self, subWin): def onMdiArea(self, subWin):
"""Executed when window is selected on mdi area. """Executed when window is selected on mdi area.
@param subWin Selected window.
Keyword arguments:
subWin -- Selected window.
""" """
plt = Plot.getPlot() plt = Plot.getPlot()
if plt != subWin: if plt != subWin:
@ -385,74 +571,98 @@ class TaskPanel:
def updateUI(self): def updateUI(self):
"""Setup UI controls values if possible""" """Setup UI controls values if possible"""
plt = Plot.getPlot() plt = Plot.getPlot()
self.form.axId.setEnabled(bool(plt)) # Get again all the subwidgets (to avoid PySide Pitfalls)
self.form.new.setEnabled(bool(plt)) mw = self.getMainWindow()
self.form.remove.setEnabled(bool(plt)) form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.all.setEnabled(bool(plt)) form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
self.form.xMin.setEnabled(bool(plt)) form.new = self.widget(QtGui.QPushButton, "newAxesButton")
self.form.xMax.setEnabled(bool(plt)) form.remove = self.widget(QtGui.QPushButton, "delAxesButton")
self.form.yMin.setEnabled(bool(plt)) form.all = self.widget(QtGui.QCheckBox, "allAxes")
self.form.yMax.setEnabled(bool(plt)) form.xMin = self.widget(QtGui.QSlider, "posXMin")
self.form.xAlign.setEnabled(bool(plt)) form.xMax = self.widget(QtGui.QSlider, "posXMax")
self.form.yAlign.setEnabled(bool(plt)) form.yMin = self.widget(QtGui.QSlider, "posYMin")
self.form.xOffset.setEnabled(bool(plt)) form.yMax = self.widget(QtGui.QSlider, "posYMax")
self.form.yOffset.setEnabled(bool(plt)) form.xAlign = self.widget(QtGui.QComboBox, "xAlign")
self.form.xAuto.setEnabled(bool(plt)) form.yAlign = self.widget(QtGui.QComboBox, "yAlign")
self.form.yAuto.setEnabled(bool(plt)) form.xOffset = self.widget(QtGui.QSpinBox, "xOffset")
self.form.xSMin.setEnabled(bool(plt)) form.yOffset = self.widget(QtGui.QSpinBox, "yOffset")
self.form.xSMax.setEnabled(bool(plt)) form.xAuto = self.widget(QtGui.QCheckBox, "xAuto")
self.form.ySMin.setEnabled(bool(plt)) form.yAuto = self.widget(QtGui.QCheckBox, "yAuto")
self.form.ySMax.setEnabled(bool(plt)) form.xSMin = self.widget(QtGui.QLineEdit, "xMin")
form.xSMax = self.widget(QtGui.QLineEdit, "xMax")
form.ySMin = self.widget(QtGui.QLineEdit, "yMin")
form.ySMax = self.widget(QtGui.QLineEdit, "yMax")
# Enable/disable them
form.axId.setEnabled(bool(plt))
form.new.setEnabled(bool(plt))
form.remove.setEnabled(bool(plt))
form.all.setEnabled(bool(plt))
form.xMin.setEnabled(bool(plt))
form.xMax.setEnabled(bool(plt))
form.yMin.setEnabled(bool(plt))
form.yMax.setEnabled(bool(plt))
form.xAlign.setEnabled(bool(plt))
form.yAlign.setEnabled(bool(plt))
form.xOffset.setEnabled(bool(plt))
form.yOffset.setEnabled(bool(plt))
form.xAuto.setEnabled(bool(plt))
form.yAuto.setEnabled(bool(plt))
form.xSMin.setEnabled(bool(plt))
form.xSMax.setEnabled(bool(plt))
form.ySMin.setEnabled(bool(plt))
form.ySMax.setEnabled(bool(plt))
if not plt: if not plt:
form.axId.setValue(0)
return return
# Ensure that active axes is correct # Ensure that active axes is correct
index = min(self.form.axId.value(), len(plt.axesList)-1) index = min(form.axId.value(), len(plt.axesList) - 1)
self.form.axId.setValue(index) form.axId.setValue(index)
# Set dimensions # Set dimensions
ax = plt.axes ax = plt.axes
bb = ax.get_position() bb = ax.get_position()
self.form.xMin.setValue(int(100*bb._get_xmin())) form.xMin.setValue(int(100 * bb._get_xmin()))
self.form.xMax.setValue(int(100*bb._get_xmax())) form.xMax.setValue(int(100 * bb._get_xmax()))
self.form.yMin.setValue(int(100*bb._get_ymin())) form.yMin.setValue(int(100 * bb._get_ymin()))
self.form.yMax.setValue(int(100*bb._get_ymax())) form.yMax.setValue(int(100 * bb._get_ymax()))
# Set alignment and offset # Set alignment and offset
xPos = ax.xaxis.get_ticks_position() xPos = ax.xaxis.get_ticks_position()
yPos = ax.yaxis.get_ticks_position() yPos = ax.yaxis.get_ticks_position()
xOffset = ax.spines['bottom'].get_position()[1] xOffset = ax.spines['bottom'].get_position()[1]
yOffset = ax.spines['left'].get_position()[1] yOffset = ax.spines['left'].get_position()[1]
if xPos == 'bottom' or xPos == 'default': if xPos == 'bottom' or xPos == 'default':
self.form.xAlign.setCurrentIndex(0) form.xAlign.setCurrentIndex(0)
else: else:
self.form.xAlign.setCurrentIndex(1) form.xAlign.setCurrentIndex(1)
self.form.xOffset.setValue(xOffset) form.xOffset.setValue(xOffset)
if yPos == 'left' or yPos == 'default': if yPos == 'left' or yPos == 'default':
self.form.yAlign.setCurrentIndex(0) form.yAlign.setCurrentIndex(0)
else: else:
self.form.yAlign.setCurrentIndex(1) form.yAlign.setCurrentIndex(1)
self.form.yOffset.setValue(yOffset) form.yOffset.setValue(yOffset)
# Set scales # Set scales
if ax.get_autoscalex_on(): if ax.get_autoscalex_on():
self.form.xAuto.setChecked(True) form.xAuto.setChecked(True)
self.form.xSMin.setEnabled(False) form.xSMin.setEnabled(False)
self.form.xSMax.setEnabled(False) form.xSMax.setEnabled(False)
else: else:
self.form.xAuto.setChecked(False) form.xAuto.setChecked(False)
self.form.xSMin.setEnabled(True) form.xSMin.setEnabled(True)
self.form.xSMax.setEnabled(True) form.xSMax.setEnabled(True)
lim = ax.get_xlim() lim = ax.get_xlim()
self.form.xSMin.setText(str(lim[0])) form.xSMin.setText(str(lim[0]))
self.form.xSMax.setText(str(lim[1])) form.xSMax.setText(str(lim[1]))
if ax.get_autoscaley_on(): if ax.get_autoscaley_on():
self.form.yAuto.setChecked(True) form.yAuto.setChecked(True)
self.form.ySMin.setEnabled(False) form.ySMin.setEnabled(False)
self.form.ySMax.setEnabled(False) form.ySMax.setEnabled(False)
else: else:
self.form.yAuto.setChecked(False) form.yAuto.setChecked(False)
self.form.ySMin.setEnabled(True) form.ySMin.setEnabled(True)
self.form.ySMax.setEnabled(True) form.ySMax.setEnabled(True)
lim = ax.get_ylim() lim = ax.get_ylim()
self.form.ySMin.setText(str(lim[0])) form.ySMin.setText(str(lim[0]))
self.form.ySMax.setText(str(lim[1])) form.ySMax.setText(str(lim[1]))
def createTask(): def createTask():
panel = TaskPanel() panel = TaskPanel()

View File

@ -21,16 +21,9 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel import TaskPanel
def load(): def load():
""" Loads the tool """ """Load the tool"""
TaskPanel.createTask() TaskPanel.createTask()

View File

@ -21,15 +21,15 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD as App import FreeCAD as App
import FreeCADGui as Gui import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore from PySide import QtGui, QtCore
# Module
import Plot import Plot
from plotUtils import Paths from plotUtils import Paths
class TaskPanel: class TaskPanel:
def __init__(self): def __init__(self):
self.ui = Paths.modulePath() + "/plotLabels/TaskPanel.ui" self.ui = Paths.modulePath() + "/plotLabels/TaskPanel.ui"
@ -65,13 +65,13 @@ class TaskPanel:
def setupUi(self): def setupUi(self):
mw = self.getMainWindow() mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel") form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = form.findChild(QtGui.QSpinBox, "axesIndex") form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
form.title = form.findChild(QtGui.QLineEdit, "title") form.title = self.widget(QtGui.QLineEdit, "title")
form.titleSize = form.findChild(QtGui.QSpinBox, "titleSize") form.titleSize = self.widget(QtGui.QSpinBox, "titleSize")
form.xLabel = form.findChild(QtGui.QLineEdit, "titleX") form.xLabel = self.widget(QtGui.QLineEdit, "titleX")
form.xSize = form.findChild(QtGui.QSpinBox, "xSize") form.xSize = self.widget(QtGui.QSpinBox, "xSize")
form.yLabel = form.findChild(QtGui.QLineEdit, "titleY") form.yLabel = self.widget(QtGui.QLineEdit, "titleY")
form.ySize = form.findChild(QtGui.QSpinBox, "ySize") form.ySize = self.widget(QtGui.QSpinBox, "ySize")
self.form = form self.form = form
self.retranslateUi() self.retranslateUi()
# Look for active axes if can # Look for active axes if can
@ -82,71 +82,141 @@ class TaskPanel:
axId = axId + 1 axId = axId + 1
form.axId.setValue(axId) form.axId.setValue(axId)
self.updateUI() self.updateUI()
QtCore.QObject.connect(form.axId, QtCore.SIGNAL('valueChanged(int)'),self.onAxesId) QtCore.QObject.connect(form.axId,
QtCore.QObject.connect(form.title, QtCore.SIGNAL("editingFinished()"),self.onLabels) QtCore.SIGNAL('valueChanged(int)'),
QtCore.QObject.connect(form.xLabel, QtCore.SIGNAL("editingFinished()"),self.onLabels) self.onAxesId)
QtCore.QObject.connect(form.yLabel, QtCore.SIGNAL("editingFinished()"),self.onLabels) QtCore.QObject.connect(form.title,
QtCore.QObject.connect(form.titleSize,QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes) QtCore.SIGNAL("editingFinished()"),
QtCore.QObject.connect(form.xSize, QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes) self.onLabels)
QtCore.QObject.connect(form.ySize, QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes) QtCore.QObject.connect(form.xLabel,
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) QtCore.SIGNAL("editingFinished()"),
self.onLabels)
QtCore.QObject.connect(form.yLabel,
QtCore.SIGNAL("editingFinished()"),
self.onLabels)
QtCore.QObject.connect(form.titleSize,
QtCore.SIGNAL("valueChanged(int)"),
self.onFontSizes)
QtCore.QObject.connect(form.xSize,
QtCore.SIGNAL("valueChanged(int)"),
self.onFontSizes)
QtCore.QObject.connect(form.ySize,
QtCore.SIGNAL("valueChanged(int)"),
self.onFontSizes)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
return False return False
def getMainWindow(self): def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets() toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel: for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow": if i.metaObject().className() == "Gui::MainWindow":
return i return i
raise Exception("No main window found") raise Exception("No main window found")
def retranslateUi(self): def widget(self, class_id, name):
""" Set user interface locale strings. """Return the selected widget.
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
""" """
self.form.setWindowTitle(QtGui.QApplication.translate("plot_labels", "Set labels", mw = self.getMainWindow()
None,QtGui.QApplication.UnicodeUTF8)) form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.findChild(QtGui.QLabel, "axesLabel").setText(QtGui.QApplication.translate("plot_labels", "Active axes", return form.findChild(class_id, name)
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "titleLabel").setText(QtGui.QApplication.translate("plot_labels", "Title", def retranslateUi(self):
None,QtGui.QApplication.UnicodeUTF8)) """ Set the user interface locale strings.
self.form.findChild(QtGui.QLabel, "xLabel").setText(QtGui.QApplication.translate("plot_labels", "X label", """
None,QtGui.QApplication.UnicodeUTF8)) self.form.setWindowTitle(QtGui.QApplication.translate(
self.form.findChild(QtGui.QLabel, "yLabel").setText(QtGui.QApplication.translate("plot_labels", "Y label", "plot_labels",
None,QtGui.QApplication.UnicodeUTF8)) "Set labels",
self.form.axId.setToolTip(QtGui.QApplication.translate("plot_labels", "Index of the active axes", None,
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.UnicodeUTF8))
self.form.title.setToolTip(QtGui.QApplication.translate("plot_labels", "Title (associated to active axes)", self.widget(QtGui.QLabel, "axesLabel").setText(
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.translate("plot_labels",
self.form.titleSize.setToolTip(QtGui.QApplication.translate("plot_labels", "Title font size", "Active axes",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.xLabel.setToolTip(QtGui.QApplication.translate("plot_labels", "X axis title", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "titleLabel").setText(
self.form.xSize.setToolTip(QtGui.QApplication.translate("plot_labels", "X axis title font size", QtGui.QApplication.translate("plot_labels",
None,QtGui.QApplication.UnicodeUTF8)) "Title",
self.form.yLabel.setToolTip(QtGui.QApplication.translate("plot_labels", "Y axis title", None,
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.UnicodeUTF8))
self.form.ySize.setToolTip(QtGui.QApplication.translate("plot_labels", "Y axis title font size", self.widget(QtGui.QLabel, "xLabel").setText(
None,QtGui.QApplication.UnicodeUTF8)) QtGui.QApplication.translate("plot_labels",
"X label",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "yLabel").setText(
QtGui.QApplication.translate("plot_labels",
"Y label",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "axesIndex").setToolTip(QtGui.QApplication.translate(
"plot_labels",
"Index of the active axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "title").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Title (associated to active axes)",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "titleSize").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Title font size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "titleX").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"X axis title",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "xSize").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"X axis title font size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "titleY").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Y axis title",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "ySize").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Y axis title font size",
None,
QtGui.QApplication.UnicodeUTF8))
def onAxesId(self, value): def onAxesId(self, value):
""" Executed when axes index is modified. """ """ Executed when axes index is modified. """
if not self.skip: if not self.skip:
self.skip = True self.skip = True
# UI control in some special plot cases # No active plot case
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
self.skip = False self.skip = False
return return
# UI control in most cases # Get again all the subwidgets (to avoid PySide Pitfalls)
self.form.axId.setMaximum(len(plt.axesList)) mw = self.getMainWindow()
if self.form.axId.value() >= len(plt.axesList): form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.axId.setValue(len(plt.axesList)-1) form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
form.axId.setMaximum(len(plt.axesList))
if form.axId.value() >= len(plt.axesList):
form.axId.setValue(len(plt.axesList) - 1)
# Send new control to Plot instance # Send new control to Plot instance
plt.setActiveAxes(self.form.axId.value()) plt.setActiveAxes(form.axId.value())
self.updateUI() self.updateUI()
self.skip = False self.skip = False
@ -156,10 +226,16 @@ class TaskPanel:
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Set labels # Get again all the subwidgets (to avoid PySide Pitfalls)
Plot.title(unicode(self.form.title.text())) mw = self.getMainWindow()
Plot.xlabel(unicode(self.form.xLabel.text())) form = mw.findChild(QtGui.QWidget, "TaskPanel")
Plot.ylabel(unicode(self.form.yLabel.text())) form.title = self.widget(QtGui.QLineEdit, "title")
form.xLabel = self.widget(QtGui.QLineEdit, "titleX")
form.yLabel = self.widget(QtGui.QLineEdit, "titleY")
Plot.title(unicode(form.title.text()))
Plot.xlabel(unicode(form.xLabel.text()))
Plot.ylabel(unicode(form.yLabel.text()))
plt.update() plt.update()
def onFontSizes(self, value): def onFontSizes(self, value):
@ -169,16 +245,24 @@ class TaskPanel:
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
# Set font sizes # Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.titleSize = self.widget(QtGui.QSpinBox, "titleSize")
form.xSize = self.widget(QtGui.QSpinBox, "xSize")
form.ySize = self.widget(QtGui.QSpinBox, "ySize")
ax = plt.axes ax = plt.axes
ax.title.set_fontsize(self.form.titleSize.value()) ax.title.set_fontsize(form.titleSize.value())
ax.xaxis.label.set_fontsize(self.form.xSize.value()) ax.xaxis.label.set_fontsize(form.xSize.value())
ax.yaxis.label.set_fontsize(self.form.ySize.value()) ax.yaxis.label.set_fontsize(form.ySize.value())
plt.update() plt.update()
def onMdiArea(self, subWin): def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area. """ Executed when window is selected on mdi area.
@param subWin Selected window.
Keyword arguments:
subWin -- Selected window.
""" """
plt = Plot.getPlot() plt = Plot.getPlot()
if plt != subWin: if plt != subWin:
@ -186,20 +270,32 @@ class TaskPanel:
def updateUI(self): def updateUI(self):
""" Setup UI controls values if possible """ """ Setup UI controls values if possible """
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
form.title = self.widget(QtGui.QLineEdit, "title")
form.titleSize = self.widget(QtGui.QSpinBox, "titleSize")
form.xLabel = self.widget(QtGui.QLineEdit, "titleX")
form.xSize = self.widget(QtGui.QSpinBox, "xSize")
form.yLabel = self.widget(QtGui.QLineEdit, "titleY")
form.ySize = self.widget(QtGui.QSpinBox, "ySize")
plt = Plot.getPlot() plt = Plot.getPlot()
self.form.axId.setEnabled(bool(plt)) form.axId.setEnabled(bool(plt))
self.form.title.setEnabled(bool(plt)) form.title.setEnabled(bool(plt))
self.form.titleSize.setEnabled(bool(plt)) form.titleSize.setEnabled(bool(plt))
self.form.xLabel.setEnabled(bool(plt)) form.xLabel.setEnabled(bool(plt))
self.form.xSize.setEnabled(bool(plt)) form.xSize.setEnabled(bool(plt))
self.form.yLabel.setEnabled(bool(plt)) form.yLabel.setEnabled(bool(plt))
self.form.ySize.setEnabled(bool(plt)) form.ySize.setEnabled(bool(plt))
if not plt: if not plt:
return return
# Ensure that active axes is correct # Ensure that active axes is correct
index = min(self.form.axId.value(), len(plt.axesList)-1) index = min(form.axId.value(), len(plt.axesList) - 1)
self.form.axId.setValue(index) form.axId.setValue(index)
# Store data before starting changing it. # Store data before starting changing it.
ax = plt.axes ax = plt.axes
t = ax.get_title() t = ax.get_title()
x = ax.get_xlabel() x = ax.get_xlabel()
@ -208,13 +304,14 @@ class TaskPanel:
xx = ax.xaxis.label.get_fontsize() xx = ax.xaxis.label.get_fontsize()
yy = ax.yaxis.label.get_fontsize() yy = ax.yaxis.label.get_fontsize()
# Set labels # Set labels
self.form.title.setText(t) form.title.setText(t)
self.form.xLabel.setText(x) form.xLabel.setText(x)
self.form.yLabel.setText(y) form.yLabel.setText(y)
# Set font sizes # Set font sizes
self.form.titleSize.setValue(tt) form.titleSize.setValue(tt)
self.form.xSize.setValue(xx) form.xSize.setValue(xx)
self.form.ySize.setValue(yy) form.ySize.setValue(yy)
def createTask(): def createTask():
panel = TaskPanel() panel = TaskPanel()

View File

@ -21,16 +21,9 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel import TaskPanel
def load(): def load():
""" Loads the tool """ """Load the tool"""
TaskPanel.createTask() TaskPanel.createTask()

View File

@ -21,15 +21,15 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD as App import FreeCAD as App
import FreeCADGui as Gui import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore from PySide import QtGui, QtCore
# Module
import Plot import Plot
from plotUtils import Paths from plotUtils import Paths
class TaskPanel: class TaskPanel:
def __init__(self): def __init__(self):
self.ui = Paths.modulePath() + "/plotPositions/TaskPanel.ui" self.ui = Paths.modulePath() + "/plotPositions/TaskPanel.ui"
@ -69,54 +69,100 @@ class TaskPanel:
def setupUi(self): def setupUi(self):
mw = self.getMainWindow() mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel") form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = form.findChild(QtGui.QListWidget, "items") form.items = self.widget(QtGui.QListWidget, "items")
form.x = form.findChild(QtGui.QDoubleSpinBox, "x") form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = form.findChild(QtGui.QDoubleSpinBox, "y") form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = form.findChild(QtGui.QDoubleSpinBox, "size") form.s = self.widget(QtGui.QDoubleSpinBox, "size")
self.form = form self.form = form
self.retranslateUi() self.retranslateUi()
self.updateUI() self.updateUI()
QtCore.QObject.connect(form.items, QtCore.SIGNAL("currentRowChanged(int)"),self.onItem) QtCore.QObject.connect(
QtCore.QObject.connect(form.x, QtCore.SIGNAL("valueChanged(double)"),self.onData) form.items,
QtCore.QObject.connect(form.y, QtCore.SIGNAL("valueChanged(double)"),self.onData) QtCore.SIGNAL("currentRowChanged(int)"),
QtCore.QObject.connect(form.s, QtCore.SIGNAL("valueChanged(double)"),self.onData) self.onItem)
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) QtCore.QObject.connect(
form.x,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
form.y,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
form.s,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
return False return False
def getMainWindow(self): def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets() toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel: for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow": if i.metaObject().className() == "Gui::MainWindow":
return i return i
raise Exception("No main window found") raise Exception("No main window found")
def retranslateUi(self): def widget(self, class_id, name):
""" Set user interface locale strings. """Return the selected widget.
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
""" """
self.form.setWindowTitle(QtGui.QApplication.translate("plot_positions", "Set positions and sizes", mw = self.getMainWindow()
None,QtGui.QApplication.UnicodeUTF8)) form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.findChild(QtGui.QLabel, "posLabel").setText(QtGui.QApplication.translate("plot_positions", "Position", return form.findChild(class_id, name)
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "sizeLabel").setText(QtGui.QApplication.translate("plot_positions", "Size", def retranslateUi(self):
None,QtGui.QApplication.UnicodeUTF8)) """Set the user interface locale strings."""
self.form.items.setToolTip(QtGui.QApplication.translate("plot_positions", "List of modificable items", self.form.setWindowTitle(QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_positions",
self.form.x.setToolTip(QtGui.QApplication.translate("plot_positions", "X item position", "Set positions and sizes",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.y.setToolTip(QtGui.QApplication.translate("plot_positions", "Y item position", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "posLabel").setText(
self.form.s.setToolTip(QtGui.QApplication.translate("plot_positions", "Item size", QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_positions",
"Position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "sizeLabel").setText(
QtGui.QApplication.translate(
"plot_positions",
"Size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QListWidget, "items").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"List of modificable items",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "x").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"X item position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "y").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"Y item position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "size").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"Item size",
None,
QtGui.QApplication.UnicodeUTF8))
def onItem(self, row): def onItem(self, row):
""" Executed when selected item is modified. """ """ Executed when selected item is modified. """
# Get selected item
self.item = row self.item = row
# Call to update
self.updateUI() self.updateUI()
def onData(self, value): def onData(self, value):
@ -125,18 +171,24 @@ class TaskPanel:
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = self.widget(QtGui.QDoubleSpinBox, "size")
if not self.skip: if not self.skip:
self.skip = True self.skip = True
name = self.names[self.item] name = self.names[self.item]
obj = self.objs[self.item] obj = self.objs[self.item]
x = self.form.x.value() x = form.x.value()
y = self.form.y.value() y = form.y.value()
s = self.form.s.value() s = form.s.value()
# x/y labels only have one position control # x/y labels only have one position control
if name.find('x label') >= 0: if name.find('x label') >= 0:
self.form.y.setValue(x) form.y.setValue(x)
elif name.find('y label') >= 0: elif name.find('y label') >= 0:
self.form.x.setValue(y) form.x.setValue(y)
# title and labels only have one size control # title and labels only have one size control
if name.find('title') >= 0 or name.find('label') >= 0: if name.find('title') >= 0 or name.find('label') >= 0:
obj.set_position((x, y)) obj.set_position((x, y))
@ -148,28 +200,36 @@ class TaskPanel:
self.skip = False self.skip = False
def onMdiArea(self, subWin): def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area. """Executed when a new window is selected on the mdi area.
@param subWin Selected window.
Keyword arguments:
subWin -- Selected window.
""" """
plt = Plot.getPlot() plt = Plot.getPlot()
if plt != subWin: if plt != subWin:
self.updateUI() self.updateUI()
def updateUI(self): def updateUI(self):
""" Setup UI controls values if possible """ """Setup the UI control values if it is possible."""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = self.widget(QtGui.QDoubleSpinBox, "size")
plt = Plot.getPlot() plt = Plot.getPlot()
self.form.items.setEnabled(bool(plt)) form.items.setEnabled(bool(plt))
self.form.x.setEnabled(bool(plt)) form.x.setEnabled(bool(plt))
self.form.y.setEnabled(bool(plt)) form.y.setEnabled(bool(plt))
self.form.s.setEnabled(bool(plt)) form.s.setEnabled(bool(plt))
if not plt: if not plt:
self.plt = plt self.plt = plt
self.form.items.clear() form.items.clear()
return return
# Refill items list only if Plot instance have been changed # Refill items list only if Plot instance have been changed
if self.plt != plt: if self.plt != plt:
self.plt = plt self.plt = plt
self.plt.update() # Update plot in order to put legend in correct place self.plt.update()
self.setList() self.setList()
# Get data for controls # Get data for controls
name = self.names[self.item] name = self.names[self.item]
@ -180,22 +240,28 @@ class TaskPanel:
y = p[1] y = p[1]
s = obj.get_size() s = obj.get_size()
if name.find('x label') >= 0: if name.find('x label') >= 0:
self.form.y.setEnabled(False) form.y.setEnabled(False)
self.form.y.setValue(x) form.y.setValue(x)
elif name.find('y label') >= 0: elif name.find('y label') >= 0:
self.form.x.setEnabled(False) form.x.setEnabled(False)
self.form.x.setValue(y) form.x.setValue(y)
else: else:
x = plt.legPos[0] x = plt.legPos[0]
y = plt.legPos[1] y = plt.legPos[1]
s = obj.get_texts()[-1].get_fontsize() s = obj.get_texts()[-1].get_fontsize()
# Send it to controls # Send it to controls
self.form.x.setValue(x) form.x.setValue(x)
self.form.y.setValue(y) form.y.setValue(y)
self.form.s.setValue(s) form.s.setValue(s)
def setList(self): def setList(self):
""" Setup UI controls values if possible """ """ Setup UI controls values if possible """
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = self.widget(QtGui.QDoubleSpinBox, "size")
# Clear lists # Clear lists
self.names = [] self.names = []
self.objs = [] self.objs = []
@ -205,11 +271,11 @@ class TaskPanel:
for i in range(0, len(self.plt.axesList)): for i in range(0, len(self.plt.axesList)):
ax = self.plt.axesList[i] ax = self.plt.axesList[i]
# Each axes have title, xaxis and yaxis # Each axes have title, xaxis and yaxis
self.names.append('title (axes %d)' % (i)) self.names.append('title (axes {})'.format(i))
self.objs.append(ax.title) self.objs.append(ax.title)
self.names.append('x label (axes %d)' % (i)) self.names.append('x label (axes {})'.format(i))
self.objs.append(ax.xaxis.get_label()) self.objs.append(ax.xaxis.get_label())
self.names.append('y label (axes %d)' % (i)) self.names.append('y label (axes {})'.format(i))
self.objs.append(ax.yaxis.get_label()) self.objs.append(ax.yaxis.get_label())
# Legend if exist # Legend if exist
ax = self.plt.axesList[-1] ax = self.plt.axesList[-1]
@ -217,13 +283,14 @@ class TaskPanel:
self.names.append('legend') self.names.append('legend')
self.objs.append(ax.legend_) self.objs.append(ax.legend_)
# Send list to widget # Send list to widget
self.form.items.clear() form.items.clear()
for name in self.names: for name in self.names:
self.form.items.addItem(name) form.items.addItem(name)
# Ensure that selected item is correct # Ensure that selected item is correct
if self.item >= len(self.names): if self.item >= len(self.names):
self.item = len(self.names) - 1 self.item = len(self.names) - 1
self.form.items.setCurrentIndex(self.item) form.items.setCurrentIndex(self.item)
def createTask(): def createTask():
panel = TaskPanel() panel = TaskPanel()

View File

@ -21,16 +21,9 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel import TaskPanel
def load(): def load():
""" Loads the tool """ """Load the tool"""
TaskPanel.createTask() TaskPanel.createTask()

View File

@ -22,15 +22,16 @@
#*************************************************************************** #***************************************************************************
import os import os
# FreeCAD modules
import FreeCAD as App import FreeCAD as App
import FreeCADGui as Gui import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore from PySide import QtGui, QtCore
# Module
import Plot import Plot
from plotUtils import Paths from plotUtils import Paths
class TaskPanel: class TaskPanel:
def __init__(self): def __init__(self):
self.ui = Paths.modulePath() + "/plotSave/TaskPanel.ui" self.ui = Paths.modulePath() + "/plotSave/TaskPanel.ui"
@ -38,13 +39,22 @@ class TaskPanel:
def accept(self): def accept(self):
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
msg = QtGui.QApplication.translate("plot_console", "Plot document must be selected in order to save it", msg = QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8) "plot_console",
"Plot document must be selected in order to save it",
None,
QtGui.QApplication.UnicodeUTF8)
App.Console.PrintError(msg + "\n") App.Console.PrintError(msg + "\n")
return False return False
path = unicode(self.form.path.text()) mw = self.getMainWindow()
size = (self.form.sizeX.value(), self.form.sizeY.value()) form = mw.findChild(QtGui.QWidget, "TaskPanel")
dpi = self.form.dpi.value() form.path = self.widget(QtGui.QLineEdit, "path")
form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX")
form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY")
form.dpi = self.widget(QtGui.QSpinBox, "dpi")
path = unicode(form.path.text())
size = (form.sizeX.value(), form.sizeY.value())
dpi = form.dpi.value()
Plot.save(path, size, dpi) Plot.save(path, size, dpi)
return True return True
@ -75,85 +85,147 @@ class TaskPanel:
def setupUi(self): def setupUi(self):
mw = self.getMainWindow() mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel") form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.path = form.findChild(QtGui.QLineEdit, "path") form.path = self.widget(QtGui.QLineEdit, "path")
form.pathButton = form.findChild(QtGui.QPushButton, "pathButton") form.pathButton = self.widget(QtGui.QPushButton, "pathButton")
form.sizeX = form.findChild(QtGui.QDoubleSpinBox, "sizeX") form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX")
form.sizeY = form.findChild(QtGui.QDoubleSpinBox, "sizeY") form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY")
form.dpi = form.findChild(QtGui.QSpinBox, "dpi") form.dpi = self.widget(QtGui.QSpinBox, "dpi")
self.form = form self.form = form
self.retranslateUi() self.retranslateUi()
QtCore.QObject.connect(form.pathButton,QtCore.SIGNAL("pressed()"),self.onPathButton) QtCore.QObject.connect(
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) form.pathButton,
QtCore.SIGNAL("pressed()"),
self.onPathButton)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
home = os.getenv('USERPROFILE') or os.getenv('HOME') home = os.getenv('USERPROFILE') or os.getenv('HOME')
form.path.setText(os.path.join(home, "plot.png")) form.path.setText(os.path.join(home, "plot.png"))
self.updateUI() self.updateUI()
return False return False
def getMainWindow(self): def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets() toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel: for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow": if i.metaObject().className() == "Gui::MainWindow":
return i return i
raise Exception("No main window found") raise Exception("No main window found")
def retranslateUi(self): def widget(self, class_id, name):
""" Set user interface locale strings. """Return the selected widget.
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
""" """
self.form.setWindowTitle(QtGui.QApplication.translate("plot_save", "Save figure", mw = self.getMainWindow()
None,QtGui.QApplication.UnicodeUTF8)) form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.findChild(QtGui.QLabel, "sizeLabel").setText(QtGui.QApplication.translate("plot_save", "Inches", return form.findChild(class_id, name)
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "dpiLabel").setText(QtGui.QApplication.translate("plot_save", "Dots per Inch", def retranslateUi(self):
None,QtGui.QApplication.UnicodeUTF8)) """Set the user interface locale strings."""
self.form.path.setToolTip(QtGui.QApplication.translate("plot_save", "Output image file path", self.form.setWindowTitle(QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_save",
self.form.pathButton.setToolTip(QtGui.QApplication.translate("plot_save", "Show a file selection dialog", "Save figure",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.sizeX.setToolTip(QtGui.QApplication.translate("plot_save", "X image size", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "sizeLabel").setText(
self.form.sizeY.setToolTip(QtGui.QApplication.translate("plot_save", "Y image size", QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_save",
self.form.dpi.setToolTip(QtGui.QApplication.translate("plot_save", "Dots per point, with size will define output image resolution", "Inches",
None,QtGui.QApplication.UnicodeUTF8)) None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "dpiLabel").setText(
QtGui.QApplication.translate(
"plot_save",
"Dots per Inch",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "path").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Output image file path",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "pathButton").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Show a file selection dialog",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "sizeX").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"X image size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "sizeY").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Y image size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "dpi").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Dots per point, with size will define output image"
" resolution",
None,
QtGui.QApplication.UnicodeUTF8))
def updateUI(self): def updateUI(self):
""" Setup UI controls values if possible """ """ Setup UI controls values if possible """
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.path = self.widget(QtGui.QLineEdit, "path")
form.pathButton = self.widget(QtGui.QPushButton, "pathButton")
form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX")
form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY")
form.dpi = self.widget(QtGui.QSpinBox, "dpi")
plt = Plot.getPlot() plt = Plot.getPlot()
self.form.path.setEnabled(bool(plt)) form.path.setEnabled(bool(plt))
self.form.pathButton.setEnabled(bool(plt)) form.pathButton.setEnabled(bool(plt))
self.form.sizeX.setEnabled(bool(plt)) form.sizeX.setEnabled(bool(plt))
self.form.sizeY.setEnabled(bool(plt)) form.sizeY.setEnabled(bool(plt))
self.form.dpi.setEnabled(bool(plt)) form.dpi.setEnabled(bool(plt))
if not plt: if not plt:
return return
fig = plt.fig fig = plt.fig
size = fig.get_size_inches() size = fig.get_size_inches()
dpi = fig.get_dpi() dpi = fig.get_dpi()
self.form.sizeX.setValue(size[0]) form.sizeX.setValue(size[0])
self.form.sizeY.setValue(size[1]) form.sizeY.setValue(size[1])
self.form.dpi.setValue(dpi) form.dpi.setValue(dpi)
def onPathButton(self): def onPathButton(self):
""" Executed when path button is pressed. """Executed when the path selection button is pressed."""
""" mw = self.getMainWindow()
path = self.form.path.text() form = mw.findChild(QtGui.QWidget, "TaskPanel")
file_choices = "Portable Network Graphics (*.png)|*.png;;Portable Document Format (*.pdf)|*.pdf;;PostScript (*.ps)|*.ps;;Encapsulated PostScript (*.eps)|*.eps" form.path = self.widget(QtGui.QLineEdit, "path")
path = QtGui.QFileDialog.getSaveFileName(None, 'Save figure', path, file_choices) path = form.path.text()
file_choices = ("Portable Network Graphics (*.png)|*.png;;"
"Portable Document Format (*.pdf)|*.pdf;;"
"PostScript (*.ps)|*.ps;;"
"Encapsulated PostScript (*.eps)|*.eps")
path = QtGui.QFileDialog.getSaveFileName(None,
'Save figure',
path,
file_choices)
if path: if path:
self.form.path.setText(path) form.path.setText(path)
def onMdiArea(self, subWin): def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area. """Executed when a new window is selected on the mdi area.
@param subWin Selected window.
Keyword arguments:
subWin -- Selected window.
""" """
plt = Plot.getPlot() plt = Plot.getPlot()
if plt != subWin: if plt != subWin:
self.updateUI() self.updateUI()
def createTask(): def createTask():
panel = TaskPanel() panel = TaskPanel()
Gui.Control.showDialog(panel) Gui.Control.showDialog(panel)

View File

@ -21,16 +21,9 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel import TaskPanel
def load(): def load():
""" Loads the tool """ """Load the tool"""
TaskPanel.createTask() TaskPanel.createTask()

View File

@ -21,19 +21,19 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD as App import FreeCAD as App
import FreeCADGui as Gui import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore from PySide import QtGui, QtCore
# Module
import Plot import Plot
from plotUtils import Paths from plotUtils import Paths
# matplotlib
import matplotlib import matplotlib
from matplotlib.lines import Line2D from matplotlib.lines import Line2D
import matplotlib.colors as Colors import matplotlib.colors as Colors
class TaskPanel: class TaskPanel:
def __init__(self): def __init__(self):
self.ui = Paths.modulePath() + "/plotSeries/TaskPanel.ui" self.ui = Paths.modulePath() + "/plotSeries/TaskPanel.ui"
@ -71,129 +71,234 @@ class TaskPanel:
def setupUi(self): def setupUi(self):
mw = self.getMainWindow() mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel") form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = form.findChild(QtGui.QListWidget, "items") form.items = self.widget(QtGui.QListWidget, "items")
form.label = form.findChild(QtGui.QLineEdit, "label") form.label = self.widget(QtGui.QLineEdit, "label")
form.isLabel = form.findChild(QtGui.QCheckBox, "isLabel") form.isLabel = self.widget(QtGui.QCheckBox, "isLabel")
form.style = form.findChild(QtGui.QComboBox, "lineStyle") form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = form.findChild(QtGui.QComboBox, "markers") form.marker = self.widget(QtGui.QComboBox, "markers")
form.width = form.findChild(QtGui.QDoubleSpinBox, "lineWidth") form.width = self.widget(QtGui.QDoubleSpinBox, "lineWidth")
form.size = form.findChild(QtGui.QSpinBox, "markerSize") form.size = self.widget(QtGui.QSpinBox, "markerSize")
form.color = form.findChild(QtGui.QPushButton, "color") form.color = self.widget(QtGui.QPushButton, "color")
form.remove = form.findChild(QtGui.QPushButton, "remove") form.remove = self.widget(QtGui.QPushButton, "remove")
self.form = form self.form = form
self.retranslateUi() self.retranslateUi()
self.fillStyles() self.fillStyles()
self.updateUI() self.updateUI()
QtCore.QObject.connect(form.items, QtCore.SIGNAL("currentRowChanged(int)"),self.onItem) QtCore.QObject.connect(
QtCore.QObject.connect(form.label, QtCore.SIGNAL("editingFinished()"),self.onData) form.items,
QtCore.QObject.connect(form.isLabel,QtCore.SIGNAL("stateChanged(int)"),self.onData) QtCore.SIGNAL("currentRowChanged(int)"),
QtCore.QObject.connect(form.style, QtCore.SIGNAL("currentIndexChanged(int)"),self.onData) self.onItem)
QtCore.QObject.connect(form.marker, QtCore.SIGNAL("currentIndexChanged(int)"),self.onData) QtCore.QObject.connect(
QtCore.QObject.connect(form.width, QtCore.SIGNAL("valueChanged(double)"),self.onData) form.label,
QtCore.QObject.connect(form.size, QtCore.SIGNAL("valueChanged(int)"),self.onData) QtCore.SIGNAL("editingFinished()"),
QtCore.QObject.connect(form.color, QtCore.SIGNAL("pressed()"),self.onColor) self.onData)
QtCore.QObject.connect(form.remove, QtCore.SIGNAL("pressed()"),self.onRemove) QtCore.QObject.connect(
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea) form.isLabel,
QtCore.SIGNAL("stateChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.style,
QtCore.SIGNAL("currentIndexChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.marker,
QtCore.SIGNAL("currentIndexChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.width,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
form.size,
QtCore.SIGNAL("valueChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.color,
QtCore.SIGNAL("pressed()"),
self.onColor)
QtCore.QObject.connect(
form.remove,
QtCore.SIGNAL("pressed()"),
self.onRemove)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
return False return False
def getMainWindow(self): def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets() toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel: for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow": if i.metaObject().className() == "Gui::MainWindow":
return i return i
raise Exception("No main window found") raise Exception("No main window found")
def retranslateUi(self): def widget(self, class_id, name):
""" Set user interface locale strings. """Return the selected widget.
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
""" """
self.form.setWindowTitle(QtGui.QApplication.translate("plot_series", "Configure series", mw = self.getMainWindow()
None,QtGui.QApplication.UnicodeUTF8)) form = mw.findChild(QtGui.QWidget, "TaskPanel")
self.form.isLabel.setText(QtGui.QApplication.translate("plot_series", "No label", return form.findChild(class_id, name)
None,QtGui.QApplication.UnicodeUTF8))
self.form.remove.setText(QtGui.QApplication.translate("plot_series", "Remove serie", def retranslateUi(self):
None,QtGui.QApplication.UnicodeUTF8)) """Set the user interface locale strings."""
self.form.findChild(QtGui.QLabel, "styleLabel").setText(QtGui.QApplication.translate("plot_series", "Line style", self.form.setWindowTitle(QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_series",
self.form.findChild(QtGui.QLabel, "markerLabel").setText(QtGui.QApplication.translate("plot_series", "Marker", "Configure series",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.items.setToolTip(QtGui.QApplication.translate("plot_series", "List of available series", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QCheckBox, "isLabel").setText(
self.form.label.setToolTip(QtGui.QApplication.translate("plot_series", "Line title", QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_series",
self.form.isLabel.setToolTip(QtGui.QApplication.translate("plot_series", "If checked serie will not be considered for legend", "No label",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.style.setToolTip(QtGui.QApplication.translate("plot_series", "Line style", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QPushButton, "remove").setText(
self.form.marker.setToolTip(QtGui.QApplication.translate("plot_series", "Marker style", QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_series",
self.form.width.setToolTip(QtGui.QApplication.translate("plot_series", "Line width", "Remove serie",
None,QtGui.QApplication.UnicodeUTF8)) None,
self.form.size.setToolTip(QtGui.QApplication.translate("plot_series", "Marker size", QtGui.QApplication.UnicodeUTF8))
None,QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "styleLabel").setText(
self.form.color.setToolTip(QtGui.QApplication.translate("plot_series", "Line and marker color", QtGui.QApplication.translate(
None,QtGui.QApplication.UnicodeUTF8)) "plot_series",
self.form.remove.setToolTip(QtGui.QApplication.translate("plot_series", "Removes this serie", "Line style",
None,QtGui.QApplication.UnicodeUTF8)) None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "markerLabel").setText(
QtGui.QApplication.translate(
"plot_series",
"Marker",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QListWidget, "items").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"List of available series",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "label").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line title",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QCheckBox, "isLabel").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"If checked serie will not be considered for legend",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QComboBox, "lineStyle").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line style",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QComboBox, "markers").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Marker style",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "lineWidth").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line width",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "markerSize").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Marker size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "color").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line and marker color",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "remove").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Removes this serie",
None,
QtGui.QApplication.UnicodeUTF8))
def fillStyles(self): def fillStyles(self):
""" Fill style combo boxes. """ """Fill the style combo boxes with the availabel ones."""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = self.widget(QtGui.QComboBox, "markers")
# Line styles # Line styles
linestyles = Line2D.lineStyles.keys() linestyles = Line2D.lineStyles.keys()
for i in range(0, len(linestyles)): for i in range(0, len(linestyles)):
style = linestyles[i] style = linestyles[i]
string = "\'" + str(style) + "\' (" + Line2D.lineStyles[style] + ")" string = "\'" + str(style) + "\'"
self.form.style.addItem(string) string += " (" + Line2D.lineStyles[style] + ")"
form.style.addItem(string)
# Markers # Markers
markers = Line2D.markers.keys() markers = Line2D.markers.keys()
for i in range(0, len(markers)): for i in range(0, len(markers)):
marker = markers[i] marker = markers[i]
string = "\'" + str(marker) + "\' (" + Line2D.markers[marker] + ")" string = "\'" + str(marker) + "\'"
self.form.marker.addItem(string) string += " (" + Line2D.markers[marker] + ")"
form.marker.addItem(string)
def onItem(self, row): def onItem(self, row):
""" Executed when selected item is modified. """ """Executed when the selected item is modified."""
if not self.skip: if not self.skip:
self.skip = True self.skip = True
# Get selected item
self.item = row self.item = row
# Call to update
self.updateUI() self.updateUI()
self.skip = False self.skip = False
def onData(self): def onData(self):
""" Executed when selected item data is modified. """ """Executed when the selected item data is modified."""
if not self.skip: if not self.skip:
self.skip = True self.skip = True
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.label = self.widget(QtGui.QLineEdit, "label")
form.isLabel = self.widget(QtGui.QCheckBox, "isLabel")
form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = self.widget(QtGui.QComboBox, "markers")
form.width = self.widget(QtGui.QDoubleSpinBox, "lineWidth")
form.size = self.widget(QtGui.QSpinBox, "markerSize")
# Ensure that selected serie exist # Ensure that selected serie exist
if self.item >= len(Plot.series()): if self.item >= len(Plot.series()):
self.updateUI() self.updateUI()
return return
# Set label # Set label
serie = Plot.series()[self.item] serie = Plot.series()[self.item]
if(self.form.isLabel.isChecked()): if(form.isLabel.isChecked()):
serie.name = None serie.name = None
self.form.label.setEnabled(False) form.label.setEnabled(False)
else: else:
serie.name = self.form.label.text() serie.name = form.label.text()
self.form.label.setEnabled(True) form.label.setEnabled(True)
# Set line style and marker # Set line style and marker
style = self.form.style.currentIndex() style = form.style.currentIndex()
linestyles = Line2D.lineStyles.keys() linestyles = Line2D.lineStyles.keys()
serie.line.set_linestyle(linestyles[style]) serie.line.set_linestyle(linestyles[style])
marker = self.form.marker.currentIndex() marker = form.marker.currentIndex()
markers = Line2D.markers.keys() markers = Line2D.markers.keys()
serie.line.set_marker(markers[marker]) serie.line.set_marker(markers[marker])
# Set line width and marker size # Set line width and marker size
serie.line.set_linewidth(self.form.width.value()) serie.line.set_linewidth(form.width.value())
serie.line.set_markersize(self.form.size.value()) serie.line.set_markersize(form.size.value())
plt.update() plt.update()
# Regenerate series labels # Regenerate series labels
self.setList() self.setList()
@ -205,6 +310,10 @@ class TaskPanel:
if not plt: if not plt:
self.updateUI() self.updateUI()
return return
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.color = self.widget(QtGui.QPushButton, "color")
# Ensure that selected serie exist # Ensure that selected serie exist
if self.item >= len(Plot.series()): if self.item >= len(Plot.series()):
self.updateUI() self.updateUI()
@ -214,13 +323,15 @@ class TaskPanel:
# Send color to widget and serie # Send color to widget and serie
if col.isValid(): if col.isValid():
serie = plt.series[self.item] serie = plt.series[self.item]
self.form.color.setStyleSheet("background-color: rgb(%d, %d, %d);" % (col.red(), form.color.setStyleSheet(
col.green(), col.blue())) "background-color: rgb({}, {}, {});".format(col.red(),
col.green(),
col.blue()))
serie.line.set_color((col.redF(), col.greenF(), col.blueF())) serie.line.set_color((col.redF(), col.greenF(), col.blueF()))
plt.update() plt.update()
def onRemove(self): def onRemove(self):
""" Executed when data serie must be removed. """ """Executed when the data serie must be removed."""
plt = Plot.getPlot() plt = Plot.getPlot()
if not plt: if not plt:
self.updateUI() self.updateUI()
@ -236,8 +347,10 @@ class TaskPanel:
plt.update() plt.update()
def onMdiArea(self, subWin): def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area. """Executed when a new window is selected on the mdi area.
@param subWin Selected window.
Keyword arguments:
subWin -- Selected window.
""" """
plt = Plot.getPlot() plt = Plot.getPlot()
if plt != subWin: if plt != subWin:
@ -245,83 +358,100 @@ class TaskPanel:
def updateUI(self): def updateUI(self):
""" Setup UI controls values if possible """ """ Setup UI controls values if possible """
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.label = self.widget(QtGui.QLineEdit, "label")
form.isLabel = self.widget(QtGui.QCheckBox, "isLabel")
form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = self.widget(QtGui.QComboBox, "markers")
form.width = self.widget(QtGui.QDoubleSpinBox, "lineWidth")
form.size = self.widget(QtGui.QSpinBox, "markerSize")
form.color = self.widget(QtGui.QPushButton, "color")
form.remove = self.widget(QtGui.QPushButton, "remove")
plt = Plot.getPlot() plt = Plot.getPlot()
self.form.items.setEnabled(bool(plt)) form.items.setEnabled(bool(plt))
self.form.label.setEnabled(bool(plt)) form.label.setEnabled(bool(plt))
self.form.isLabel.setEnabled(bool(plt)) form.isLabel.setEnabled(bool(plt))
self.form.style.setEnabled(bool(plt)) form.style.setEnabled(bool(plt))
self.form.marker.setEnabled(bool(plt)) form.marker.setEnabled(bool(plt))
self.form.width.setEnabled(bool(plt)) form.width.setEnabled(bool(plt))
self.form.size.setEnabled(bool(plt)) form.size.setEnabled(bool(plt))
self.form.color.setEnabled(bool(plt)) form.color.setEnabled(bool(plt))
self.form.remove.setEnabled(bool(plt)) form.remove.setEnabled(bool(plt))
if not plt: if not plt:
self.plt = plt self.plt = plt
self.form.items.clear() form.items.clear()
return return
self.skip = True self.skip = True
# Refill list # Refill list
if self.plt != plt or len(Plot.series()) != self.form.items.count(): if self.plt != plt or len(Plot.series()) != form.items.count():
self.plt = plt self.plt = plt
self.setList() self.setList()
# Ensure that have series # Ensure that have series
if not len(Plot.series()): if not len(Plot.series()):
self.form.label.setEnabled(False) form.label.setEnabled(False)
self.form.isLabel.setEnabled(False) form.isLabel.setEnabled(False)
self.form.style.setEnabled(False) form.style.setEnabled(False)
self.form.marker.setEnabled(False) form.marker.setEnabled(False)
self.form.width.setEnabled(False) form.width.setEnabled(False)
self.form.size.setEnabled(False) form.size.setEnabled(False)
self.form.color.setEnabled(False) form.color.setEnabled(False)
self.form.remove.setEnabled(False) form.remove.setEnabled(False)
return return
# Set label # Set label
serie = Plot.series()[self.item] serie = Plot.series()[self.item]
if serie.name == None: if serie.name is None:
self.form.isLabel.setChecked(True) form.isLabel.setChecked(True)
self.form.label.setEnabled(False) form.label.setEnabled(False)
self.form.label.setText("") form.label.setText("")
else: else:
self.form.isLabel.setChecked(False) form.isLabel.setChecked(False)
self.form.label.setText(serie.name) form.label.setText(serie.name)
# Set line style and marker # Set line style and marker
self.form.style.setCurrentIndex(0) form.style.setCurrentIndex(0)
linestyles = Line2D.lineStyles.keys() linestyles = Line2D.lineStyles.keys()
for i in range(0, len(linestyles)): for i in range(0, len(linestyles)):
style = linestyles[i] style = linestyles[i]
if style == serie.line.get_linestyle(): if style == serie.line.get_linestyle():
self.form.style.setCurrentIndex(i) form.style.setCurrentIndex(i)
self.form.marker.setCurrentIndex(0) form.marker.setCurrentIndex(0)
markers = Line2D.markers.keys() markers = Line2D.markers.keys()
for i in range(0, len(markers)): for i in range(0, len(markers)):
marker = markers[i] marker = markers[i]
if marker == serie.line.get_marker(): if marker == serie.line.get_marker():
self.form.marker.setCurrentIndex(i) form.marker.setCurrentIndex(i)
# Set line width and marker size # Set line width and marker size
self.form.width.setValue(serie.line.get_linewidth()) form.width.setValue(serie.line.get_linewidth())
self.form.size.setValue(serie.line.get_markersize()) form.size.setValue(serie.line.get_markersize())
# Set color # Set color
color = Colors.colorConverter.to_rgb(serie.line.get_color()) color = Colors.colorConverter.to_rgb(serie.line.get_color())
self.form.color.setStyleSheet("background-color: rgb(%d, %d, %d);" % (int(color[0]*255), form.color.setStyleSheet("background-color: rgb({}, {}, {});".format(
int(color[1]*255), int(color[2]*255))) int(color[0] * 255),
int(color[1] * 255),
int(color[2] * 255)))
self.skip = False self.skip = False
def setList(self): def setList(self):
""" Setup UI controls values if possible """ """Setup the UI control values if it is possible."""
self.form.items.clear() mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.items.clear()
series = Plot.series() series = Plot.series()
for i in range(0, len(series)): for i in range(0, len(series)):
serie = series[i] serie = series[i]
string = 'serie ' + str(i) + ': ' string = 'serie ' + str(i) + ': '
if serie.name == None: if serie.name is None:
string = string + '\"No label\"' string = string + '\"No label\"'
else: else:
string = string + serie.name string = string + serie.name
self.form.items.addItem(string) form.items.addItem(string)
# Ensure that selected item is correct # Ensure that selected item is correct
if len(series) and self.item >= len(series): if len(series) and self.item >= len(series):
self.item = len(series) - 1 self.item = len(series) - 1
self.form.items.setCurrentIndex(self.item) form.items.setCurrentIndex(self.item)
def createTask(): def createTask():
panel = TaskPanel() panel = TaskPanel()

View File

@ -21,16 +21,9 @@
#* * #* *
#*************************************************************************** #***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel import TaskPanel
def load(): def load():
""" Loads the tool """ """Load the tool"""
TaskPanel.createTask() TaskPanel.createTask()

View File

@ -21,11 +21,13 @@
#* * #* *
#*************************************************************************** #***************************************************************************
import FreeCAD, FreeCADGui, os import FreeCAD
import FreeCADGui
import os
def modulePath(): def modulePath():
"""returns the current Plot module path """returns the current Plot module path."""
@return Module path"""
path1 = FreeCAD.ConfigGet("AppHomePath") + "Mod/Plot" path1 = FreeCAD.ConfigGet("AppHomePath") + "Mod/Plot"
path2 = FreeCAD.ConfigGet("UserAppData") + "Mod/Plot" path2 = FreeCAD.ConfigGet("UserAppData") + "Mod/Plot"
if os.path.exists(path2): if os.path.exists(path2):
@ -33,29 +35,14 @@ def modulePath():
else: else:
return path1 return path1
def iconsPath(): def iconsPath():
"""returns the current Plot module icons path """returns the current Plot module icons path."""
@return Icons path"""
path = modulePath() + "/resources/icons" path = modulePath() + "/resources/icons"
return path return path
def translationsPath(): def translationsPath():
"""returns the current Plot module translations path """returns the current Plot module translations path."""
@return Icons path"""
path = modulePath() + "/resources/translations" path = modulePath() + "/resources/translations"
return path return path
def getPathFromFile(fileName):
""" Gets the directory path from a file name
@param fileName Name of the file
@return Directory path.
"""
if not fileName:
return ''
i = 1
try:
while 1:
i = fileName.index("/", i+1)
except ValueError:
pass
return fileName[0:i+1]

View File

@ -20,6 +20,3 @@
#* USA * #* USA *
#* * #* *
#*************************************************************************** #***************************************************************************
# Empty file to treat the folder as a package