def __get_arg_triple_errorbar(self, args): """Convert MATLAB-like arguments into x, y, style""" if len(args)==2: y, dy = args x = arange(len(y)) dx = zeros(len(y)) style = next(self.style) elif len(args)==3: a1, a2, a3 = args if is_text_string(a3): y, dy = a1, a2 x = arange(len(y)) dx = zeros(len(y)) style = a3 else: x, y, dy = args dx = zeros(len(y)) style = next(self.style) elif len(args)==4: a1, a2, a3, a4 = args if is_text_string(a4): x, y, dy = a1, a2, a3 dx = zeros(len(y)) style = a4 else: x, y, dx, dy = args style = next(self.style) elif len(args)==5: x, y, dx, dy, style = args else: raise TypeError("Wrong number of arguments") return x, y, dx, dy, style
def __check_section_option(self, section, option): """ Private method to check section and option types """ if section is None: section = self.default_section_name elif not is_text_string(section): raise RuntimeError("Argument 'section' must be a string") if not is_text_string(option): raise RuntimeError("Argument 'option' must be a string") return section
def initialize_widget(self): if self.is_radio: for button in self._buttons: button.toggled.disconnect(self.index_changed) self.vbox.removeWidget(button) button.deleteLater() self._buttons = [] else: self.combobox.blockSignals(True) while self.combobox.count(): self.combobox.removeItem(0) _choices = self.item.get_prop_value("data", "choices") for key, lbl, img in _choices: if self.is_radio: button = QRadioButton(lbl, self.group) if img: if is_text_string(img): if not osp.isfile(img): img = get_image_file_path(img) img = QIcon(img) elif isinstance(img, collections.Callable): img = img(key) if self.is_radio: button.setIcon(img) else: self.combobox.addItem(img, lbl) elif not self.is_radio: self.combobox.addItem(lbl) if self.is_radio: self._buttons.append(button) self.vbox.addWidget(button) button.toggled.connect(self.index_changed) if not self.is_radio: self.combobox.blockSignals(False)
def save(self, fname, format, draft): if is_text_string(fname): if format == "pdf": self.app = guidata.qapplication() if draft: mode = QPrinter.ScreenResolution else: mode = QPrinter.HighResolution printer = QPrinter(mode) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Landscape) printer.setOutputFileName(fname) printer.setCreator('guiqwt.pyplot') self.print_(printer) else: if self.win is None: self.show() if PYQT5: pixmap = self.win.centralWidget().grab() else: pixmap = QPixmap.grabWidget(self.win.centralWidget()) pixmap.save(fname, format.upper()) else: # Buffer fd = fname assert hasattr(fd, 'write'), "object is not file-like as expected" if self.win is None: self.show() pixmap = QPixmap.grabWidget(self.win.centralWidget()) buff = QBuffer() buff.open(QIODevice.ReadWrite) pixmap.save(buff, format.upper()) fd.write(buff.data()) buff.close() fd.seek(0)
def __init__(self, label, formats='*', default=None, basedir=None, all_files_first=False, help='', check=True): if is_text_string(default): default = [default] FileSaveItem.__init__(self, label, formats=formats, default=default, basedir=basedir, all_files_first=all_files_first, help=help, check=check)
def create_toolbutton(parent, icon=None, text=None, triggered=None, tip=None, toggled=None, shortcut=None, autoraise=True, enabled=None): """Create a QToolButton""" if autoraise: button = QToolButton(parent) else: button = QPushButton(parent) if text is not None: button.setText(text) if icon is not None: if is_text_string(icon): icon = get_icon(icon) button.setIcon(icon) if text is not None or tip is not None: button.setToolTip(text if tip is None else tip) if autoraise: button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) button.setAutoRaise(True) if triggered is not None: button.clicked.connect(triggered) if toggled is not None: button.toggled.connect(toggled) button.setCheckable(True) if shortcut is not None: button.setShortcut(shortcut) if enabled is not None: button.setEnabled(enabled) return button
def create_toolbutton(parent, icon=None, text=None, triggered=None, tip=None, toggled=None, shortcut=None, autoraise=True, enabled=None): """Create a QToolButton""" if autoraise: button = QToolButton(parent) else: button = QPushButton(parent) if text is not None: button.setText(text) if icon is not None: if is_text_string(icon): icon = get_icon(icon) button.setIcon(icon) if text is not None or tip is not None: button.setToolTip(text if tip is None else tip) if autoraise: button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) button.setAutoRaise(True) if triggered is not None: parent.connect(button, SIGNAL('clicked()'), triggered) if toggled is not None: parent.connect(button, SIGNAL("toggled(bool)"), toggled) button.setCheckable(True) if shortcut is not None: button.setShortcut(shortcut) if enabled is not None: button.setEnabled(enabled) return button
def __init__(self, label, klass, button_text=None, button_icon=None, show_button=True, wordwrap=False, **kwargs): DataSetShowGroupBox.__init__(self, label, klass, wordwrap=wordwrap, **kwargs) if show_button: if button_text is None: button_text = _("Apply") if button_icon is None: button_icon = get_icon("apply.png") elif is_text_string(button_icon): button_icon = get_icon(button_icon) apply_btn = QPushButton(button_icon, button_text, self) apply_btn.clicked.connect(self.set) layout = self.edit.layout layout.addWidget(apply_btn, layout.rowCount(), 0, 1, -1, Qt.AlignRight)
def _make_figure_title(N=None): global _figures if N is None: N = len(_figures)+1 if is_text_string(N): return N else: return "Figure %d" % N
def translate_gettext(x): if not PY3 and is_unicode(x): x = x.encode("utf-8") y = lgettext(x) if is_text_string(y) and PY3: return y else: return to_text_string(y, "utf-8")
def _make_figure_title(N=None): global _figures if N is None: N = len(_figures) + 1 if is_text_string(N): return N else: return "Figure %d" % N
def setup_widget_properties(self, wintitle, icon): self.setWindowTitle(wintitle) if is_text_string(icon): icon = get_icon(icon) if icon is not None: self.setWindowIcon(icon) self.setMinimumSize(320, 240) self.resize(640, 480)
def __get_arg_triple_plot(self, args): """Convert MATLAB-like arguments into x, y, style""" def get_x_y_from_data(data): if isinstance(data, (tuple, list)): data = array(data) if len(data.shape) == 1 or 1 in data.shape: x = arange(data.size) y = data else: x = arange(len(data[:, 0])) y = [data[:, i] for i in range(len(data[0, :]))] return x, y if len(args) == 1: if is_text_string(args[0]): x = array((), float) y = array((), float) style = args[0] else: x, y = get_x_y_from_data(args[0]) y_matrix = not isinstance(y, ndarray) if y_matrix: style = [next(self.style) for yi in y] else: style = next(self.style) elif len(args) == 2: a1, a2 = args if is_text_string(a2): x, y = get_x_y_from_data(a1) style = a2 else: x = a1 y = a2 style = next(self.style) elif len(args) == 3: x, y, style = args else: raise TypeError("Wrong number of arguments") if isinstance(x, (list, tuple)): x = array(x) if isinstance(y, (list, tuple)) and not y_matrix: y = array(y) return x, y, style
def __get_arg_triple_plot(self, args): """Convert MATLAB-like arguments into x, y, style""" def get_x_y_from_data(data): if isinstance(data, (tuple, list)): data = array(data) if len(data.shape) == 1 or 1 in data.shape: x = arange(data.size) y = data else: x = arange(len(data[:, 0])) y = [data[:, i] for i in range(len(data[0,:]))] return x, y if len(args) == 1: if is_text_string(args[0]): x = array((), float) y = array((), float) style = args[0] else: x, y = get_x_y_from_data(args[0]) y_matrix = not isinstance(y, ndarray) if y_matrix: style = [next(self.style) for yi in y] else: style = next(self.style) elif len(args) == 2: a1, a2 = args if is_text_string(a2): x, y = get_x_y_from_data(a1) style = a2 else: x = a1 y = a2 style = next(self.style) elif len(args)==3: x, y, style = args else: raise TypeError("Wrong number of arguments") if isinstance(x, (list, tuple)): x = array(x) if isinstance(y, (list, tuple)) and not y_matrix: y = array(y) return x, y, style
def set_axis_color(self, axis_id, color): """ Set axis color color: color name (string) or QColor instance """ axis_id = self.get_axis_id(axis_id) if is_text_string(color): color = QColor(color) self.axes_styles[axis_id].color = str(color.name()) self.update_axis_style(axis_id)
def __init__(self, name, extensions, read_func=None, write_func=None, data_types=None, requires_template=False): self.name = name if is_text_string(extensions): extensions = extensions.split() self.extensions = [osp.splitext(' '+ext)[1] for ext in extensions] self.read_func = read_func self.write_func = write_func self.data_types = data_types self.requires_template = requires_template
def __set(self, section, option, value, verbose): """ Private set method """ if not self.has_section(section): self.add_section(section) if not is_text_string(value): value = repr(value) if verbose: print('%s[ %s ] = %s' % (section, option, value)) cp.ConfigParser.set(self, section, option, encode_to_utf8(value))
def __set(self, section, option, value, verbose): """ Private set method """ if not self.has_section(section): self.add_section( section ) if not is_text_string(value): value = repr( value ) if verbose: print('%s[ %s ] = %s' % (section, option, value)) cp.ConfigParser.set(self, section, option, encode_to_utf8(value))
def __init__(self, item, parent_layout): super(ButtonWidget, self).__init__(item, parent_layout) _label = self.item.get_prop_value("display", "label") self.button = self.group = QPushButton(_label) self.button.setToolTip(item.get_help()) _icon = self.item.get_prop_value("display", "icon") if _icon is not None: if is_text_string(_icon): _icon = get_icon(_icon) self.button.setIcon(_icon) self.button.clicked.connect(self.clicked) self.cb_value = None
def utf8_to_unicode(string): """Convert UTF-8 string to Unicode""" if not is_text_string(string): string = to_text_string(string) if not is_unicode(string): try: string = to_text_string(string, "utf-8") except UnicodeDecodeError: # This is border line... but we admit here string which has been # erroneously encoded in file system charset instead of UTF-8 string = decode_fs_string(string) return string
def text_to_qcolor(text): """Create a QColor from specified string""" color = QColor() if not is_text_string(text): # testing for QString (PyQt API#1) text = str(text) if text.startswith('#') and len(text)==7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
def text_to_qcolor(text): """Create a QColor from specified string""" color = QColor() if not is_text_string(text): # testing for QString (PyQt API#1) text = str(text) if text.startswith('#') and len(text) == 7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
def __init__(self, name, extensions, read_func=None, write_func=None, data_types=None, requires_template=False): self.name = name if is_text_string(extensions): extensions = extensions.split() self.extensions = [osp.splitext(' ' + ext)[1] for ext in extensions] self.read_func = read_func self.write_func = write_func self.data_types = data_types self.requires_template = requires_template
def imwrite(fname, arr, ext=None, dtype=None, max_range=None, **kwargs): """Save a NumPy array to an image filename `fname`. If `to_grayscale` is True, convert RGB images to grayscale The `ext` (optional) argument is a string that specifies the file extension which defines the input format: when not specified, the input format is guessed from filename. If `max_range` is True, array data is scaled to fit the `dtype` (or data type itself if `dtype` is None) dynamic range Warning: option `max_range` changes data in place""" if not is_text_string(fname): fname = to_text_string(fname) # in case filename is a QString instance if ext is None: _base, ext = osp.splitext(fname) if max_range: arr = scale_data_to_dtype(arr, arr.dtype if dtype is None else dtype) iohandler.get_writefunc(ext)(fname, arr, **kwargs)
def imread(fname, ext=None, to_grayscale=False): """Return a NumPy array from an image filename `fname`. If `to_grayscale` is True, convert RGB images to grayscale The `ext` (optional) argument is a string that specifies the file extension which defines the input format: when not specified, the input format is guessed from filename.""" if not is_text_string(fname): fname = to_text_string(fname) # in case filename is a QString instance if ext is None: _base, ext = osp.splitext(fname) arr = iohandler.get_readfunc(ext)(fname) if to_grayscale and arr.ndim == 3: # Converting to grayscale return arr[..., :4].mean(axis=2) else: return arr
def fill_combo(self): self.combobox.blockSignals(True) while self.combobox.count(): self.combobox.removeItem(0) _choices = self.item.get_prop_value("data", "choices") for key, lbl, img in _choices: if img: if is_text_string(img): if not osp.isfile(img): img = get_image_file_path(img) img = QIcon(img) elif isinstance(img, collections.Callable): img = img(key) self.combobox.addItem(img, lbl) else: self.combobox.addItem(lbl) self.combobox.blockSignals(False)
def getexistingdirectory(parent=None, caption='', basedir='', options=QFileDialog.ShowDirsOnly): """Wrapper around QtGui.QFileDialog.getExistingDirectory static method Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0""" # Calling QFileDialog static method if sys.platform == "win32": # On Windows platforms: redirect standard outputs _temp1, _temp2 = sys.stdout, sys.stderr sys.stdout, sys.stderr = None, None try: result = QFileDialog.getExistingDirectory(parent, caption, basedir, options) finally: if sys.platform == "win32": # On Windows platforms: restore standard outputs sys.stdout, sys.stderr = _temp1, _temp2 if not is_text_string(result): # PyQt API #1 result = to_text_string(result) return result
def savefig(fname, format=None, draft=False): """ Save figure Currently supports PDF and PNG formats only """ if not is_text_string(fname) and format is None: # Buffer/fd format = 'png' if format is None: format = fname.rsplit(".", 1)[-1].lower() fmts = [str(fmt).lower() for fmt in QImageWriter.supportedImageFormats()] assert format in fmts, _("Function 'savefig' currently supports the " "following formats:\n%s" ) % ','.join(fmts) else: format = format.lower() fig = gcf() fig.save(fname, format, draft)
def savefig(fname, format=None, draft=False): """ Save figure Currently supports PDF and PNG formats only """ if not is_text_string(fname) and format is None: # Buffer/fd format = 'png' if format is None: format = fname.rsplit(".", 1)[-1].lower() fmts = [ str(fmt).lower() for fmt in QImageWriter.supportedImageFormats() ] assert format in fmts, _("Function 'savefig' currently supports the " "following formats:\n%s") % ','.join(fmts) else: format = format.lower() fig = gcf() fig.save(fname, format, draft)
def set(self, section, option, value, verbose=False, save=True): """ Set an option section=None: attribute a default section name """ section = self.__check_section_option(section, option) default_value = self.get_default(section, option) if default_value is NoDefault: default_value = value self.set_default(section, option, default_value) if isinstance(default_value, bool): value = bool(value) elif isinstance(default_value, float): value = float(value) elif isinstance(default_value, int): value = int(value) elif not is_text_string(default_value): value = repr(value) self.__set(section, option, value, verbose) if save: self.__save()
def get_string_value(self, instance): """ Return a formatted unicode representation of the item's value obeying 'display' or 'repr' properties """ value = self.get_value(instance) repval = self.get_prop_value("display", instance, "repr", None) if repval is not None: return repval else: fmt = self.get_prop_value("display", instance, "format", "%s") func = self.get_prop_value("display", instance, "func", lambda x:x) if isinstance(fmt, collections.Callable) and value is not None: return fmt(func(value)) elif is_text_string(fmt): # This is only necessary with Python 2: converting to unicode fmt = to_text_string(fmt) if value is not None: text = self.format_string(instance, value, fmt, func) else: text = "" return text
def get_string_value(self, instance): """ Return a formatted unicode representation of the item's value obeying 'display' or 'repr' properties """ value = self.get_value(instance) repval = self.get_prop_value("display", instance, "repr", None) if repval is not None: return repval else: fmt = self.get_prop_value("display", instance, "format", "%s") func = self.get_prop_value("display", instance, "func", lambda x: x) if isinstance(fmt, collections.Callable) and value is not None: return fmt(func(value)) elif is_text_string(fmt): # This is only necessary with Python 2: converting to unicode fmt = to_text_string(fmt) if value is not None: text = self.format_string(instance, value, fmt, func) else: text = "" return text
def xlabel(bottom="", top=""): """Set current x-axis label""" assert is_text_string(bottom) and is_text_string(top) axe = gca() axe.xlabel = (bottom, top)
def zlabel(label): """Set current z-axis label""" assert is_text_string(label) axe = gca() axe.zlabel = label
def ylabel(left="", right=""): """Set current y-axis label""" assert is_text_string(left) and is_text_string(right) axe = gca() axe.ylabel = (left, right)