source: sasview/src/sas/qtgui/Plotting/SlicerParameters.py @ 531dd64

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 531dd64 was 2f55df6, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 6 years ago

Slicer Parameters should also close the corresponding subwindow on exit.
Also: fixed toFloat() conversion.
SASVIEW-1115

  • Property mode set to 100644
File size: 6.1 KB
Line 
1"""
2Allows users to modify the box slicer parameters.
3"""
4import numpy
5import functools
6
7from PyQt5 import QtCore
8from PyQt5 import QtGui
9from PyQt5 import QtWidgets
10
11import sas.qtgui.Utilities.GuiUtils as GuiUtils
12
13# Local UI
14from sas.qtgui.UI import main_resources_rc
15from sas.qtgui.Plotting.UI.SlicerParametersUI import Ui_SlicerParametersUI
16
17class SlicerParameters(QtWidgets.QDialog, Ui_SlicerParametersUI):
18    """
19    Interaction between the QTableView and the underlying model,
20    passed from a slicer instance.
21    """
22    closeWidgetSignal = QtCore.pyqtSignal()
23    def __init__(self, model=None, validate_method=None):
24        super(SlicerParameters, self).__init__()
25
26        self.setupUi(self)
27
28        assert isinstance(model, QtGui.QStandardItemModel)
29
30        self.model = model
31        self.validate_method = validate_method
32
33        # Define a proxy model so cell enablement can be finegrained.
34        self.proxy = ProxyModel(self)
35        self.proxy.setSourceModel(self.model)
36
37        # Set the proxy model for display in the Table View.
38        self.lstParams.setModel(self.proxy)
39
40        # Disallow edit of the parameter name column.
41        self.lstParams.model().setColumnReadOnly(0, True)
42
43        # Specify the validator on the parameter value column.
44        self.delegate = EditDelegate(self, validate_method=self.validate_method)
45        self.lstParams.setItemDelegate(self.delegate)
46        self.delegate.refocus_signal.connect(self.onFocus)
47
48        # Display Help on clicking the button
49        self.buttonBox.button(QtWidgets.QDialogButtonBox.Help).clicked.connect(self.onHelp)
50
51        # Close doesn't trigger closeEvent automatically, so force it
52        self.buttonBox.button(QtWidgets.QDialogButtonBox.Close).clicked.connect(functools.partial(self.closeEvent, None))
53
54        # Disable row number display
55        self.lstParams.verticalHeader().setVisible(False)
56        self.lstParams.setAlternatingRowColors(True)
57        self.lstParams.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding)
58
59        # Header properties for nicer display
60        header = self.lstParams.horizontalHeader()
61        header.setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
62        header.setStretchLastSection(True)
63
64    def onFocus(self, row, column):
65        """ Set the focus on the cell (row, column) """
66        selection_model = self.lstParams.selectionModel()
67        selection_model.select(self.model.index(row, column), QtGui.QItemSelectionModel.Select)
68        self.lstParams.setSelectionModel(selection_model)
69        self.lstParams.setCurrentIndex(self.model.index(row, column))
70
71    def setModel(self, model):
72        """ Model setter """
73        self.model = model
74        self.proxy.setSourceModel(self.model)
75
76    def closeEvent(self, event):
77        """
78        Overwritten close widget method in order to send the close
79        signal to the parent.
80        """
81        self.closeWidgetSignal.emit()
82        if event:
83            event.accept()
84
85    def onHelp(self):
86        """
87        Display generic data averaging help
88        """
89        url = "/user/qtgui/MainWindow/graph_help.html#d-data-averaging"
90        GuiUtils.showHelp(url)
91
92class ProxyModel(QtCore.QIdentityProxyModel):
93    """
94    Trivial proxy model with custom column edit flag
95    """
96    def __init__(self, parent=None):
97        super(ProxyModel, self).__init__(parent)
98        self._columns = set()
99
100    def columnReadOnly(self, column):
101        '''Returns True if column is read only, false otherwise'''
102        return column in self._columns
103
104    def setColumnReadOnly(self, column, readonly=True):
105        '''Add/removes a column from the readonly list'''
106        if readonly:
107            self._columns.add(column)
108        else:
109            self._columns.discard(column)
110
111    def flags(self, index):
112        '''Sets column flags'''
113        flags = super(ProxyModel, self).flags(index)
114        if self.columnReadOnly(index.column()):
115            flags &= ~QtCore.Qt.ItemIsEditable
116        return flags
117
118class PositiveDoubleEditor(QtWidgets.QLineEdit):
119    # a signal to tell the delegate when we have finished editing
120    editingFinished = QtCore.Signal()
121
122    def __init__(self, parent=None):
123            # Initialize the editor object
124            super(PositiveDoubleEditor, self).__init__(parent)
125            self.setAutoFillBackground(True)
126            validator = GuiUtils.DoubleValidator()
127            # Don't use the scientific notation, cause 'e'.
128            validator.setNotation(GuiUtils.DoubleValidator.StandardNotation)
129
130            self.setValidator(validator)
131
132    def focusOutEvent(self, event):
133            # Once focus is lost, tell the delegate we're done editing
134            self.editingFinished.emit()
135
136
137class EditDelegate(QtWidgets.QStyledItemDelegate):
138    refocus_signal = QtCore.pyqtSignal(int, int)
139    def __init__(self, parent=None, validate_method=None):
140        super(EditDelegate, self).__init__(parent)
141        self.editor = None
142        self.index = None
143        self.validate_method = validate_method
144
145    def createEditor(self, parent, option, index):
146        # Creates and returns the custom editor object we will use to edit the cell
147        if not index.isValid():
148            return 0
149
150        result = index.column()
151        if result==1:
152                self.editor = PositiveDoubleEditor(parent)
153                self.index = index
154                return self.editor
155        else:
156                return QtWidgets.QStyledItemDelegate.createEditor(self, parent, option, index)
157
158    def setModelData(self, editor, model, index):
159        """
160        Custom version of the model update, rejecting bad values
161        """
162        self.index = index
163
164        # Find out the changed parameter name and proposed value
165        new_value = GuiUtils.toDouble(self.editor.text())
166        param_name = model.sourceModel().item(index.row(),0).text()
167
168        validated = True
169        if self.validate_method:
170            # Validate the proposed value in the slicer
171            value_accepted = self.validate_method(param_name, new_value)
172
173        if value_accepted:
174            # Update the model only if value accepted
175            return super(EditDelegate, self).setModelData(editor, model, index)         
Note: See TracBrowser for help on using the repository browser.