def createList(labelText, slot, changedSlot, validator=None): widget = QWidget() layout = QVBoxLayout() layout.setObjectName('listLayout') widget.setLayout(layout) hboxWidget = QWidget() hboxLayout = QHBoxLayout() hboxLayout.setObjectName('hboxLayout for tableWidget') hboxWidget.setLayout(hboxLayout) tableWidget = QTableWidget(0, 2) tableWidget.setAlternatingRowColors(True) widget.connect(tableWidget, SIGNAL('cellChanged(int, int)'), changedSlot) tableWidget.setHorizontalHeaderLabels(createQStringList([labelText, ''])) tableWidget.setColumnWidth(INPUT_IDX, contentColumnWidth) tableWidget.setColumnWidth(BUTTON_IDX, deleteButtonColumnWidth) hboxLayout.addWidget(tableWidget) add = QWidget() addLayout = QHBoxLayout() addLayout.setObjectName('addLayout') add.setLayout(addLayout) addLineEdit = createLineEdit(add, None, validator) addButton = createButton(translate('MainWindow', 'Add'), add, add, slot) add.connect(addLineEdit, SIGNAL('returnPressed()'), slot) for wid in addLineEdit, addButton: addLayout.addWidget(wid) for wid in add, hboxWidget: layout.addWidget(wid) return (widget, tableWidget, addLineEdit)
class UpdatesWidget(QWidget): """ This widget show the availables plugins to update """ def __init__(self, parent, updates): QWidget.__init__(self, parent) self._parent = parent self._updates = updates vbox = QVBoxLayout(self) self._table = QTableWidget(1, 5) self._table.removeRow(0) self._headers = ('Name', 'Version', 'Description', 'Authors', 'Web') vbox.addWidget(self._table) ui_tools.load_table(self._table, self._headers, _format_for_table(updates)) self._table.setColumnWidth(0, 200) btnUpdate = QPushButton(self.tr("Update")) btnUpdate.setMaximumWidth(100) vbox.addWidget(btnUpdate) self.connect(btnUpdate, SIGNAL("clicked()"), self._update_plugins) def _update_plugins(self): data = _format_for_table(self._updates) plugins = ui_tools.remove_get_selected_items(self._table, data) #get the download link of each plugin for p_row in plugins: #search the plugin for p_dict in self._updates: if unicode(p_dict["name"]) == unicode(p_row[0]): p_data = p_dict break #append the downlod link p_row.append(p_data["download"]) self._parent.update_plugin(plugins)
class UpdatesWidget(QWidget): """ This widget show the availables plugins to update """ def __init__(self, parent, updates): QWidget.__init__(self, parent) self._parent = parent self._updates = updates vbox = QVBoxLayout(self) self._table = QTableWidget(1, 5) self._table.removeRow(0) self._headers = ("Name", "Version", "Description", "Authors", "Web") vbox.addWidget(self._table) ui_tools.load_table(self._table, self._headers, _format_for_table(updates)) self._table.setColumnWidth(0, 200) btnUpdate = QPushButton(self.tr("Update")) btnUpdate.setMaximumWidth(100) vbox.addWidget(btnUpdate) self.connect(btnUpdate, SIGNAL("clicked()"), self._update_plugins) def _update_plugins(self): data = _format_for_table(self._updates) plugins = ui_tools.remove_get_selected_items(self._table, data) # get the download link of each plugin for p_row in plugins: # search the plugin for p_dict in self._updates: if unicode(p_dict["name"]) == unicode(p_row[0]): p_data = p_dict break # append the downlod link p_row.append(p_data["download"]) self._parent.update_plugin(plugins)
class InstalledWidget(QWidget): """ This widget show the installed plugins """ def __init__(self, parent, installed): QWidget.__init__(self, parent) self._parent = parent self._installed = installed vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, (self.tr('Name'), self.tr('Version')), _format_for_table(installed)) self._table.setColumnWidth(0, 500) self._table.setSortingEnabled(True) self._table.setAlternatingRowColors(True) btnUninstall = QPushButton(self.tr("Uninstall")) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self.connect(btnUninstall, SIGNAL("clicked()"), self._uninstall_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def remove_item(self, plugin_name): plugin = _get_plugin(plugin_name, self._installed) self._installed.remove(plugin) def add_table_items(self, plugs): self._installed += plugs data = _format_for_table(self._installed) ui_tools.load_table(self._table, (self.tr('Name'), self.tr('Version')), data) def _uninstall_plugins(self): data = _format_for_table(self._installed) plugins = ui_tools.remove_get_selected_items(self._table, data) self._parent.mark_as_available(plugins) def reset_table(self, installed): self._installed = installed while self._table.rowCount() > 0: self._table.removeRow(0) ui_tools.load_table(self._table, (self.tr('Name'), self.tr('Version')), self._installed)
class InstalledWidget(QWidget): """ This widget show the installed plugins """ def __init__(self, parent, installed): QWidget.__init__(self, parent) self._parent = parent self._installed = installed vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, (self.tr('Name'), self.tr('Version')), _format_for_table(installed)) self._table.setColumnWidth(0, 500) btnUninstall = QPushButton(self.tr("Uninstall")) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self.connect(btnUninstall, SIGNAL("clicked()"), self._uninstall_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def remove_item(self, plugin_name): plugin = _get_plugin(plugin_name, self._installed) self._installed.remove(plugin) def add_table_items(self, plugs): self._installed += plugs data = _format_for_table(self._installed) ui_tools.load_table(self._table, (self.tr('Name'), self.tr('Version')), data) def _uninstall_plugins(self): data = _format_for_table(self._installed) plugins = ui_tools.remove_get_selected_items(self._table, data) self._parent.mark_as_available(plugins) def reset_table(self, installed): self._installed = installed while self._table.rowCount() > 0: self._table.removeRow(0) ui_tools.load_table(self._table, (self.tr('Name'), self.tr('Version')), self._installed)
class UpdatesWidget(QWidget): """ This widget show the availables plugins to update """ def __init__(self, parent, updates): QWidget.__init__(self, parent) self._parent = parent self._updates = updates vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.removeRow(0) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.setColumnWidth(0, 500) self._table.setSortingEnabled(True) self._table.setAlternatingRowColors(True) vbox.addWidget(self._table) ui_tools.load_table(self._table, (self.tr('Name'), self.tr('Version')), _format_for_table(updates)) btnUpdate = QPushButton(self.tr("Update")) btnUpdate.setMaximumWidth(100) vbox.addWidget(btnUpdate) self.connect(btnUpdate, SIGNAL("clicked()"), self._update_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def _update_plugins(self): data = _format_for_table(self._updates) plugins = ui_tools.remove_get_selected_items(self._table, data) #get the download link of each plugin for p_row in plugins: #search the plugin for p_dict in self._updates: if p_dict["name"] == p_row[0]: p_data = p_dict break #append the downlod link p_row.append(p_data["download"]) self._parent.update_plugin(plugins)
class UpdatesWidget(QWidget): """ This widget show the availables plugins to update """ def __init__(self, parent, updates): QWidget.__init__(self, parent) self._parent = parent self._updates = updates vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.removeRow(0) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.setColumnWidth(0, 500) vbox.addWidget(self._table) ui_tools.load_table(self._table, TABLE_HEADER, _format_for_table(updates)) btnUpdate = QPushButton(self.tr("Update")) btnUpdate.setMaximumWidth(100) vbox.addWidget(btnUpdate) self.connect(btnUpdate, SIGNAL("clicked()"), self._update_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def _update_plugins(self): data = _format_for_table(self._updates) plugins = ui_tools.remove_get_selected_items(self._table, data) #get the download link of each plugin for p_row in plugins: #search the plugin for p_dict in self._updates: if p_dict["name"] == p_row[0]: p_data = p_dict break #append the downlod link p_row.append(p_data["download"]) self._parent.update_plugin(plugins)
class InstalledWidget(QWidget): """ This widget show the installed plugins """ def __init__(self, parent, installed): QWidget.__init__(self, parent) self._parent = parent self._installed = installed vbox = QVBoxLayout(self) self._table = QTableWidget(1, 5) self._table.removeRow(0) self._headers = ('Name', 'Version', 'Description', "Authors", "Web") vbox.addWidget(self._table) ui_tools.load_table(self._table, self._headers, _format_for_table(installed)) self._table.setColumnWidth(0, 200) btnUninstall = QPushButton(self.tr("Uninstall")) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self.connect(btnUninstall, SIGNAL("clicked()"), self._uninstall_plugins) def remove_item(self, plugin_name): plugin = _get_plugin(plugin_name, self._installed) self._installed.remove(plugin) def add_table_items(self, plugs): self._installed += plugs data = _format_for_table(self._installed) ui_tools.load_table(self._table, self._headers, data) def _uninstall_plugins(self): data = _format_for_table(self._installed) plugins = ui_tools.remove_get_selected_items(self._table, data) self._parent.mark_as_available(plugins) def reset_table(self, installed): self._installed = installed while self._table.rowCount() > 0: self._table.removeRow(0) ui_tools.load_table(self._table, self._headers, self._installed)
class InstalledWidget(QWidget): """ This widget show the installed plugins """ def __init__(self, parent, installed): QWidget.__init__(self, parent) self._parent = parent self._installed = installed vbox = QVBoxLayout(self) self._table = QTableWidget(1, 5) self._table.removeRow(0) self._headers = ('Name', 'Version', 'Description', "Authors", "Web") vbox.addWidget(self._table) ui_tools.load_table(self._table, self._headers, _format_for_table(installed)) self._table.setColumnWidth(0, 200) btnUninstall = QPushButton(self.tr("Uninstall")) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self.connect(btnUninstall, SIGNAL("clicked()"), self._uninstall_plugins) def remove_item(self, plugin_name): plugin = _get_plugin(plugin_name, self._installed) self._installed.remove(plugin) def add_table_items(self, plugs): self._installed += plugs data = _format_for_table(self._installed) ui_tools.load_table(self._table, self._headers, data) def _uninstall_plugins(self): data = _format_for_table(self._installed) plugins = ui_tools.remove_get_selected_items(self._table, data) self._parent.mark_as_available(plugins) def reset_table(self, installed): self._installed = installed while self._table.rowCount() > 0: self._table.removeRow(0) ui_tools.load_table(self._table, self._headers, self._installed)
class SchemeWidget(QWidget): def __init__(self, parent, schemes): QWidget.__init__(self, parent) self._parent = parent self._schemes = schemes vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, ['Name', 'URL'], self._schemes) btnUninstall = QPushButton('Download') btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self._table.setColumnWidth(0, 200) self.connect(btnUninstall, SIGNAL("clicked()"), self._download_scheme) def _download_scheme(self): schemes = ui_tools.remove_get_selected_items(self._table, self._schemes) self._parent.download_scheme(schemes)
class SchemeWidget(QWidget): def __init__(self, parent, schemes): QWidget.__init__(self, parent) self._parent = parent self._schemes = schemes vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, ['Name', 'URL'], self._schemes) btnUninstall = QPushButton('Download') btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self._table.setColumnWidth(0, 200) self.connect(btnUninstall, SIGNAL("clicked()"), self._download_scheme) def _download_scheme(self): schemes = ui_tools.remove_get_selected_items(self._table, self._schemes) self._parent.download_scheme(schemes)
class LanguageWidget(QWidget): def __init__(self, parent, languages): QWidget.__init__(self, parent) self._parent = parent self._languages = languages vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table( self._table, [self.tr('Language'), self.tr('URL')], self._languages) btnUninstall = QPushButton(self.tr('Download')) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self._table.setColumnWidth(0, 200) self.connect(btnUninstall, SIGNAL("clicked()"), self._download_language) def _download_language(self): languages = ui_tools.remove_get_selected_items(self._table, self._languages) self._parent.download_language(languages)
class LanguageWidget(QWidget): def __init__(self, parent, languages): QWidget.__init__(self, parent) self._parent = parent self._languages = languages vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, [self.tr('Language'), self.tr('URL')], self._languages) btnUninstall = QPushButton(self.tr('Download')) btnUninstall.setMaximumWidth(100) vbox.addWidget(btnUninstall) self._table.setColumnWidth(0, 200) self.connect(btnUninstall, SIGNAL("clicked()"), self._download_language) def _download_language(self): languages = ui_tools.remove_get_selected_items(self._table, self._languages) self._parent.download_language(languages)
class AvailableWidget(QWidget): def __init__(self, parent, available): QWidget.__init__(self, parent) self._parent = parent self._available = available vbox = QVBoxLayout(self) self._table = QTableWidget(1, 2) self._table.setSelectionMode(QTableWidget.SingleSelection) self._table.removeRow(0) vbox.addWidget(self._table) ui_tools.load_table(self._table, TABLE_HEADER, _format_for_table(available)) self._table.setColumnWidth(0, 500) hbox = QHBoxLayout() btnInstall = QPushButton('Install') btnInstall.setMaximumWidth(100) hbox.addWidget(btnInstall) hbox.addWidget(QLabel(self.tr("NINJA needs to be restarted for " "changes to take effect."))) vbox.addLayout(hbox) self.connect(btnInstall, SIGNAL("clicked()"), self._install_plugins) self.connect(self._table, SIGNAL("itemSelectionChanged()"), self._show_item_description) def _show_item_description(self): item = self._table.currentItem() if item is not None: data = list(item.data(Qt.UserRole)) self._parent.show_plugin_info(data) def _install_plugins(self): data = _format_for_table(self._available) plugins = ui_tools.remove_get_selected_items(self._table, data) #get the download link of each plugin for p_row in plugins: #search the plugin for p_dict in self._available: if p_dict["name"] == p_row[0]: p_data = p_dict break #append the downlod link p_row.append(p_data["download"]) #download self._parent.download_plugins(plugins) def remove_item(self, plugin_name): plugin = _get_plugin(plugin_name, self._available) self._available.remove(plugin) def _install_external(self): if self._link.text().isEmpty(): QMessageBox.information(self, self.tr("External Plugins"), self.tr("URL from Plugin missing...")) return plug = [ file_manager.get_module_name(str(self._link.text())), 'External Plugin', '1.0', str(self._link.text())] self.parent().download_plugins(plug) self._link.setText('') def add_table_items(self, plugs): self._available += plugs data = _format_for_table(self._available) ui_tools.load_table(self._table, TABLE_HEADER, data)
class AvailableWidget(QWidget): def __init__(self, parent, available): QWidget.__init__(self, parent) self._parent = parent self._available = available vbox = QVBoxLayout(self) self._table = QTableWidget(1, 5) self._table.removeRow(0) vbox.addWidget(self._table) self._headers = ('Name', 'Version', 'Description', "Authors", "Web") ui_tools.load_table(self._table, self._headers, _format_for_table(available)) self._table.setColumnWidth(0, 200) hbox = QHBoxLayout() btnInstall = QPushButton('Install') btnInstall.setMaximumWidth(100) hbox.addWidget(btnInstall) hbox.addWidget(QLabel(self.tr("NINJA needs to be restarted for " \ "changes to take effect."))) vbox.addLayout(hbox) # hbox = QHBoxLayout() # hbox.addWidget(QLabel( # self.tr("Add an external Plugin. URL Zip File:"))) # self._link = QLineEdit() # hbox.addWidget(self._link) # btnAdd = QPushButton(self.tr("Add")) # hbox.addWidget(btnAdd) # vbox.addLayout(hbox) # lblExternalPlugin = QLabel( # self.tr("(Write the URL of the Plugin and press 'Add')")) # lblExternalPlugin.setAlignment(Qt.AlignRight) # vbox.addWidget(lblExternalPlugin) self.connect(btnInstall, SIGNAL("clicked()"), self._install_plugins) # self.connect(btnAdd, SIGNAL("clicked()"), self._install_external) def _install_plugins(self): data = _format_for_table(self._available) plugins = ui_tools.remove_get_selected_items(self._table, data) #get the download link of each plugin for p_row in plugins: #search the plugin for p_dict in self._available: if unicode(p_dict["name"]) == unicode(p_row[0]): p_data = p_dict break #append the downlod link p_row.append(p_data["download"]) #download self._parent.download_plugins(plugins) def remove_item(self, plugin_name): plugin = _get_plugin(plugin_name, self._available) self._available.remove(plugin) def _install_external(self): if self._link.text().isEmpty(): QMessageBox.information(self, self.tr("External Plugins"), self.tr("URL from Plugin missing...")) return plug = [ file_manager.get_module_name(str(self._link.text())), 'External Plugin', '1.0', str(self._link.text())] self.parent().download_plugins(plug) self._link.setText('') def add_table_items(self, plugs): self._available += plugs data = _format_for_table(self._available) ui_tools.load_table(self._table, self._headers, data)
class BarcodeTable(QGroupBox): """ GUI component. Displays a list of barcodes for the currently selected puck. """ def __init__(self, options): super(BarcodeTable, self).__init__() self._barcodes = [] self._options = options self.setTitle("Barcodes") self._init_ui() def _init_ui(self): # Create record table - lists all the records in the store self._table = QTableWidget() # Create barcode table - lists all the barcodes in a record self._table = QtGui.QTableWidget() self._table.setFixedWidth(110) self._table.setFixedHeight(600) self._table.setColumnCount(1) self._table.setRowCount(10) self._table.setHorizontalHeaderLabels(['Barcode']) self._table.setColumnWidth(0, 100) # Clipboard button - copy the selected barcodes to the clipboard self._btn_clipboard = QtGui.QPushButton('Copy To Clipboard') self._btn_clipboard.setToolTip( 'Copy barcodes for the selected record to the clipboard') self._btn_clipboard.resize(self._btn_clipboard.sizeHint()) self._btn_clipboard.clicked.connect(self.copy_selected_to_clipboard) self._btn_clipboard.setEnabled(False) hbox = QHBoxLayout() hbox.setSpacing(10) hbox.addWidget(self._btn_clipboard) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self._table) vbox.addLayout(hbox) self.setLayout(vbox) def populate(self, barcodes): """ Called when a new row is selected on the record table. Displays all of the barcodes from the selected record in the barcode table. By default, valid barcodes are highlighted green, invalid barcodes are highlighted red, and empty slots are grey. """ num_slots = len(barcodes) self._table.clearContents() self._table.setRowCount(num_slots) for index, barcode in enumerate(barcodes): # Select appropriate background color if barcode == NOT_FOUND_SLOT_SYMBOL: color = self._options.col_bad() elif barcode == EMPTY_SLOT_SYMBOL: color = self._options.col_empty() else: color = self._options.col_ok() color.a = 192 # Set table item barcode = QtGui.QTableWidgetItem(barcode) barcode.setBackgroundColor(color.to_qt()) barcode.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._table.setItem(index, 0, barcode) self._barcodes = barcodes[:] for i, barcode in enumerate(self._barcodes): if barcode in [NOT_FOUND_SLOT_SYMBOL, EMPTY_SLOT_SYMBOL]: self._barcodes[i] = "" self._update_button_state() def _update_button_state(self): if self._barcodes is None or len(self._barcodes) == 0: self._btn_clipboard.setEnabled(False) else: self._btn_clipboard.setEnabled(True) def copy_selected_to_clipboard(self): """ Called when the copy to clipboard button is pressed. Copies the list/s of barcodes for the currently selected records to the clipboard so that the user can paste it elsewhere. """ sep = os.linesep if self._barcodes: pyperclip.copy(sep.join(self._barcodes))
class ModiaWindow(QMainWindow): CursorLocation = Enum([ 'WINDOW_LEFT', 'WINDOW_RIGHT', 'WINDOW_TOP', 'WINDOW_BOTTOM', 'WINDOW_LEFT_TOP', 'WINDOW_RIGHT_TOP', 'WINDOW_LEFT_BOTTOM', 'WINDOW_RIGHT_BOTTOM', 'WINDOW_TITLE_BAR', 'SCREEN_LEFT', 'SCREEN_RIGHT', 'SCREEN_TOP' ]) StickType = Enum(['LEFT', 'RIGHT', 'FULL_SCREEN']) def __init__(self, parent=None): super(ModiaWindow, self).__init__(parent) self.__pic_bg = QPixmap(':resource') self.WIDTH_MIN = 721 self.HEIGHT_MIN = 500 self.WIDTH_DEFAULT = 721 self.HEIGHT_DEFAULT = 599 self.WIDTH_BORDER_TOP = 28 self.WIDTH_BORDER_RIGHT = 12 self.WIDTH_BORDER_BOTTOM = 14 self.WIDTH_BORDER_LEFT = 12 self.OFFSET_BORDER_TOP = 6 self.OFFSET_BORDER_RIGHT = 8 self.OFFSET_BORDER_BOTTOM = 10 self.OFFSET_BORDER_LEFT = 8 self.WIDTH_FRAME_LEFT = 360 self.__cursor_loc = None self.__is_fixed_size = False self.__is_fixed_width = False self.__is_fixed_height = False self.__is_maximized = False self.__is_zdt = False self.__is_sticking = False self.__is_sticked = False self.__lyric_shown = True self.__is_suspended = True self.__move_point = None self.__cursor_changed = False self.__mouse_pressed = False self.__window_resizing = False self.__setup_ui() self.__geometry_frame = self.geometry() self.__register_actions() self.__audio_manager = AudioManager(self, self.lyric_panel) def __setup_ui(self): self.setWindowTitle(QApplication.applicationName()) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowMinMaxButtonsHint) self.setWindowModality(Qt.WindowModal) self.setAttribute(Qt.WA_TranslucentBackground) self.setMouseTracking(True) self.setAnimated(True) self.setMinimumSize( self.WIDTH_MIN + self.OFFSET_BORDER_RIGHT + self.OFFSET_BORDER_LEFT, self.HEIGHT_MIN + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM) self.resize( self.WIDTH_DEFAULT + self.OFFSET_BORDER_RIGHT + self.OFFSET_BORDER_LEFT, self.HEIGHT_DEFAULT + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM) self.setWindowIcon(QIcon(':logo')) # Title bar initialization start. self.__btn_title_close = MButton(self, MButton.Type.Close) self.__btn_title_close.setGeometry(14, 11, 12, 13) self.__btn_title_close.setToolTip('退出') self.__btn_title_maximize = MButton(self, MButton.Type.Maximize) self.__btn_title_maximize.setGeometry(self.__btn_title_close.x() + 16, 11, 12, 13) self.__btn_title_maximize.setToolTip('最大化') self.__btn_title_minimize = MButton(self, MButton.Type.Minimize) self.__btn_title_minimize.setGeometry( self.__btn_title_maximize.x() + 16, 11, 12, 13) self.__btn_title_minimize.setToolTip('最小化') self.frame = MFrame(self) horizontal_layout = QHBoxLayout(self.frame) horizontal_layout.setContentsMargins(0, 0, 4, 0) horizontal_layout.setSpacing(5) # Left panel initialization start. frame_main_panel = MFrame(self.frame) size_policy_v_expand = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) size_policy_v_expand.setHorizontalStretch(0) size_policy_v_expand.setVerticalStretch(0) size_policy_v_expand.setHeightForWidth( frame_main_panel.sizePolicy().hasHeightForWidth()) frame_main_panel.setSizePolicy(size_policy_v_expand) frame_main_panel.setMinimumSize(self.WIDTH_FRAME_LEFT, 0) horizontal_layout.addWidget(frame_main_panel) verticalLayout = QVBoxLayout(frame_main_panel) verticalLayout.setContentsMargins(0, 0, 0, 0) verticalLayout.setSpacing(0) self.__action_bar = MActionBar(frame_main_panel) size_policy_h_expand = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) size_policy_h_expand.setHorizontalStretch(0) size_policy_h_expand.setVerticalStretch(0) size_policy_h_expand.setHeightForWidth( self.__action_bar.sizePolicy().hasHeightForWidth()) self.__action_bar.setSizePolicy(size_policy_h_expand) self.__action_bar.setMinimumSize(0, 136) verticalLayout.addWidget(self.__action_bar) frame_music_list = MFrame(frame_main_panel) size_policy_all_expand = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) size_policy_all_expand.setHorizontalStretch(0) size_policy_all_expand.setVerticalStretch(0) size_policy_all_expand.setHeightForWidth( frame_music_list.sizePolicy().hasHeightForWidth()) frame_music_list.setSizePolicy(size_policy_all_expand) verticalLayout.addWidget(frame_music_list) gridLayout = QGridLayout(frame_music_list) gridLayout.setContentsMargins(9, 2, 9, 5) self.__music_table = QTableWidget(0, 2, frame_music_list) self.__music_table.setFrameShape(QFrame.StyledPanel) self.__music_table.setHorizontalHeaderLabels(('标题', '时长')) self.__music_table.setSelectionMode(QAbstractItemView.SingleSelection) self.__music_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.__music_table.horizontalHeader().setVisible(False) self.__music_table.verticalHeader().setVisible(False) self.__music_table.setColumnWidth(0, 290) self.__music_table.setColumnWidth(1, 50) MStyleSetter.setStyle(self.__music_table, ':qss_tbl_music_list') gridLayout.addWidget(self.__music_table, 0, 0, 1, 1) # Lyric panel initialization start. self.lyric_panel = MLyricPanel(self.frame) size_policy_all_expand.setHeightForWidth( self.lyric_panel.sizePolicy().hasHeightForWidth()) self.lyric_panel.setSizePolicy(size_policy_all_expand) horizontal_layout.addWidget(self.lyric_panel) def __register_actions(self): QObject.connect(self.__btn_title_close, SIGNAL('clicked()'), self, SLOT('close()')) QObject.connect(self.__btn_title_maximize, SIGNAL('clicked()'), self, SLOT('showMaximized()')) QObject.connect(self.__btn_title_minimize, SIGNAL('clicked()'), self, SLOT('showMinimized()')) QObject.connect(self.__action_bar.get_widget('BTN_PREVIOUS'), SIGNAL('clicked()'), self, SLOT('__previous()')) QObject.connect(self.__action_bar.get_widget('BTN_NEXT'), SIGNAL('clicked()'), self, SLOT('__next()')) QObject.connect(self.__action_bar.get_widget('BTN_PLAY_PAUSE'), SIGNAL('clicked()'), self, SLOT('__play_pause()')) QObject.connect(self.__action_bar.get_widget('BTN_STOP'), SIGNAL('clicked()'), self, SLOT('__stop()')) QObject.connect(self.__action_bar.get_widget('BTN_LYRIC'), SIGNAL('clicked()'), self, SLOT('__show_hide_lyric()')) QObject.connect(self.__action_bar.get_widget('BTN_ADD_MUSIC'), SIGNAL('clicked()'), self, SLOT('__add_music()')) self.__music_table.cellDoubleClicked.connect( self.__cell_double_clicked) @pyqtSlot() def __previous(self): self.__audio_manager.previous() @pyqtSlot() def __next(self): self.__audio_manager.next() @pyqtSlot() def __play_pause(self): if self.__is_suspended: self.__audio_manager.play() else: self.__audio_manager.pause() @pyqtSlot() def __stop(self): self.__audio_manager.stop() def __cell_double_clicked(self, row, column): self.__stop() self.__audio_manager.clearQueue() self.__audio_manager.setCurrentSourceByIndex(row) if self.__audio_manager.getMediaObjectState() == Phonon.PlayingState: self.__audio_manager.stop() else: self.__audio_manager.play() @pyqtSlot() def __show_hide_lyric(self): if self.__lyric_shown: self.__action_bar.get_widget('BTN_LYRIC').setMStyle( MButton.Type.Show_Lyric) self.__geometry_frame = self.geometry() self.setMinimumSize( 360, self.HEIGHT_MIN + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM) self.resize(376, self.height()) self.__is_fixed_size = True else: self.__action_bar.get_widget('BTN_LYRIC').setMStyle( MButton.Type.Hide_Lyric) self.resize(self.__geometry_frame.width(), self.__geometry_frame.height()) self.setMinimumSize( self.WIDTH_MIN + self.OFFSET_BORDER_RIGHT + self.OFFSET_BORDER_LEFT, self.HEIGHT_MIN + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM) self.__is_fixed_size = False self.__lyric_shown = not self.__lyric_shown @pyqtSlot() def __add_music(self): self.__audio_manager.addMusic() def getActionBar(self): return self.__action_bar def getMusicTable(self): return self.__music_table def __get_cursor_location(self, event): if event.globalX() == 0: return self.CursorLocation.SCREEN_LEFT if QApplication.desktop().screenGeometry().width() - event.globalX( ) == 1: return self.CursorLocation.SCREEN_RIGHT if event.globalY() == 0: return self.CursorLocation.SCREEN_TOP if event.pos().y( ) < 27 and event.pos().y() - 2 > self.OFFSET_BORDER_TOP and event.pos( ).x() + self.OFFSET_BORDER_RIGHT < self.width( ) and event.pos().x() + 1 > self.OFFSET_BORDER_LEFT: return self.CursorLocation.WINDOW_TITLE_BAR permissible_var = 2 if event.pos().x( ) + permissible_var >= self.OFFSET_BORDER_LEFT and event.pos().x( ) - permissible_var <= self.OFFSET_BORDER_LEFT: if event.pos().y( ) + self.OFFSET_BORDER_BOTTOM + permissible_var >= self.rect( ).bottom() and event.pos().y( ) + self.OFFSET_BORDER_BOTTOM - permissible_var <= self.rect( ).bottom(): return self.CursorLocation.WINDOW_LEFT_BOTTOM if event.pos().y( ) + permissible_var >= self.OFFSET_BORDER_TOP and event.pos().y( ) - permissible_var <= self.OFFSET_BORDER_TOP: return self.CursorLocation.WINDOW_LEFT_TOP return self.CursorLocation.WINDOW_LEFT if event.pos().x( ) + self.OFFSET_BORDER_RIGHT + permissible_var >= self.rect().right( ) and event.pos().x( ) + self.OFFSET_BORDER_RIGHT - permissible_var <= self.rect().right(): if event.pos().y( ) + self.OFFSET_BORDER_BOTTOM + permissible_var >= self.rect( ).bottom() and event.pos().y( ) + self.OFFSET_BORDER_BOTTOM - permissible_var <= self.rect( ).bottom(): return self.CursorLocation.WINDOW_RIGHT_BOTTOM if event.pos().y( ) + permissible_var >= self.OFFSET_BORDER_TOP and event.pos().y( ) - permissible_var <= self.OFFSET_BORDER_TOP: return self.CursorLocation.WINDOW_RIGHT_TOP return self.CursorLocation.WINDOW_RIGHT if event.pos().y( ) + permissible_var >= self.OFFSET_BORDER_TOP and event.pos().y( ) - permissible_var <= self.OFFSET_BORDER_TOP: return self.CursorLocation.WINDOW_TOP if event.pos().y( ) + self.OFFSET_BORDER_BOTTOM + permissible_var >= self.rect().bottom( ) and event.pos().y( ) + self.OFFSET_BORDER_BOTTOM - permissible_var <= self.rect().bottom( ): return self.CursorLocation.WINDOW_BOTTOM return -1 def __set_cursor_shape(self, flag): if self.__is_fixed_size: return if flag == self.CursorLocation.WINDOW_LEFT or flag == self.CursorLocation.WINDOW_RIGHT: if self.__is_fixed_width: self.setCursor(Qt.ArrowCursor) return False self.setCursor(Qt.SizeHorCursor) return True if flag == self.CursorLocation.WINDOW_TOP or flag == self.CursorLocation.WINDOW_BOTTOM: if self.__is_fixed_height: self.setCursor(Qt.ArrowCursor) return False self.setCursor(Qt.SizeVerCursor) return True if self.__is_fixed_width or self.__is_fixed_height: self.setCursor(Qt.ArrowCursor) return False if flag == self.CursorLocation.WINDOW_LEFT_TOP or flag == self.CursorLocation.WINDOW_RIGHT_BOTTOM: self.setCursor(Qt.SizeFDiagCursor) return True if flag == self.CursorLocation.WINDOW_RIGHT_TOP or flag == self.CursorLocation.WINDOW_LEFT_BOTTOM: self.setCursor(Qt.SizeBDiagCursor) return True self.setCursor(Qt.ArrowCursor) return False def __change_window_size(self, flag, pos_global): pos_global = self.mapToParent(pos_global) global_x = pos_global.x() - self.OFFSET_BORDER_LEFT global_y = pos_global.y() - self.OFFSET_BORDER_TOP widget_x = self.pos().x() widget_y = self.pos().y() length_l = widget_x + self.width() - global_x length_r = global_x - widget_x + 1 + self.OFFSET_BORDER_RIGHT + self.OFFSET_BORDER_LEFT length_t = widget_y + self.height() - global_y length_b = global_y - widget_y + 1 + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM if length_l <= self.WIDTH_MIN: global_x = self.pos().x() if length_t <= self.HEIGHT_MIN: global_y = self.pos().y() if flag == self.CursorLocation.WINDOW_LEFT: self.setGeometry(global_x, widget_y, length_l, self.height()) self.__geometry_frame = self.geometry() return if flag == self.CursorLocation.WINDOW_RIGHT: self.setGeometry(widget_x, widget_y, length_r, self.height()) self.__geometry_frame = self.geometry() return if flag == self.CursorLocation.WINDOW_TOP: self.setGeometry(widget_x, global_y, self.width(), length_t) self.__geometry_frame = self.geometry() return if flag == self.CursorLocation.WINDOW_BOTTOM: self.setGeometry(widget_x, widget_y, self.width(), length_b) self.__geometry_frame = self.geometry() return if flag == self.CursorLocation.WINDOW_LEFT_TOP: self.setGeometry(global_x, global_y, length_l, length_t) self.__geometry_frame = self.geometry() return if flag == self.CursorLocation.WINDOW_LEFT_BOTTOM: self.setGeometry(global_x, widget_y, length_l, length_b) self.__geometry_frame = self.geometry() return if flag == self.CursorLocation.WINDOW_RIGHT_TOP: self.setGeometry(widget_x, global_y, length_r, length_t) self.__geometry_frame = self.geometry() return if flag == self.CursorLocation.WINDOW_RIGHT_BOTTOM: self.setGeometry(widget_x, widget_y, length_r, length_b) self.__geometry_frame = self.geometry() return def __switch_max_button(self, b_style): self.__btn_title_maximize.setMStyle(b_style) if b_style == MButton.Type.Maximize: self.__btn_title_maximize.setToolTip('最大化') return if b_style == MButton.Type.Restore: self.__btn_title_maximize.setToolTip('向下还原') return def __window_stick_to(self, s_type): if self.__is_sticking: return if s_type == self.StickType.LEFT: geometry_tgt = QRect( -self.OFFSET_BORDER_LEFT, -self.OFFSET_BORDER_TOP, QApplication.desktop().screenGeometry().width() / 2 + self.OFFSET_BORDER_LEFT + self.OFFSET_BORDER_RIGHT, QApplication.desktop().availableGeometry().height() + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM) if self.geometry() != geometry_tgt: self.setGeometry(geometry_tgt) self.__is_sticking = True return if s_type == self.StickType.RIGHT: geometry_tgt = QRect( QApplication.desktop().screenGeometry().width() / 2 - self.OFFSET_BORDER_LEFT, -self.OFFSET_BORDER_TOP, QApplication.desktop().screenGeometry().width() / 2 + self.OFFSET_BORDER_LEFT + self.OFFSET_BORDER_RIGHT, QApplication.desktop().availableGeometry().height() + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM) if self.geometry() != geometry_tgt: self.setGeometry(geometry_tgt) self.__is_sticking = True return if s_type == self.StickType.FULL_SCREEN: self.setGeometry( -self.OFFSET_BORDER_LEFT, -self.OFFSET_BORDER_TOP, QApplication.desktop().availableGeometry().width() + self.OFFSET_BORDER_RIGHT + self.OFFSET_BORDER_LEFT, QApplication.desktop().availableGeometry().height() + self.OFFSET_BORDER_TOP + self.OFFSET_BORDER_BOTTOM) self.__is_sticking = True return def paintEvent(self, *args, **kwargs): painter = QPainter(self) painter.drawPixmap(0, 0, 12, self.WIDTH_BORDER_TOP, self.__pic_bg, 0, 0, 12, self.WIDTH_BORDER_TOP) painter.drawPixmap( self.WIDTH_BORDER_LEFT, 0, self.width() - self.WIDTH_BORDER_RIGHT - self.WIDTH_BORDER_LEFT, self.WIDTH_BORDER_TOP, self.__pic_bg, 12, 0, 1, self.WIDTH_BORDER_TOP) painter.drawPixmap(self.width() - self.WIDTH_BORDER_RIGHT, 0, self.__pic_bg, 13, 0, 12, self.WIDTH_BORDER_TOP) painter.drawPixmap(0, self.height() - self.WIDTH_BORDER_BOTTOM, self.__pic_bg, 0, 90, 12, 14) painter.drawPixmap( 0, self.WIDTH_BORDER_TOP, self.WIDTH_BORDER_LEFT, self.height() - self.WIDTH_BORDER_BOTTOM - self.WIDTH_BORDER_TOP, self.__pic_bg, 0, 89, 12, 1) painter.drawPixmap( self.width() - self.WIDTH_BORDER_RIGHT, self.WIDTH_BORDER_TOP, self.WIDTH_BORDER_LEFT, self.height() - self.WIDTH_BORDER_BOTTOM - self.WIDTH_BORDER_TOP, self.__pic_bg, 13, 89, 12, 1) painter.drawPixmap( self.WIDTH_BORDER_LEFT, self.height() - self.WIDTH_BORDER_BOTTOM, self.width() - self.WIDTH_BORDER_RIGHT - self.WIDTH_BORDER_LEFT, self.WIDTH_BORDER_BOTTOM, self.__pic_bg, 12, 90, 1, 14) painter.drawPixmap(self.width() - self.WIDTH_BORDER_RIGHT, self.height() - self.WIDTH_BORDER_BOTTOM, self.__pic_bg, 13, 90, 12, 14) painter.fillRect( self.WIDTH_BORDER_LEFT - 4, self.WIDTH_BORDER_TOP, self.width() - self.WIDTH_BORDER_LEFT - self.WIDTH_BORDER_RIGHT + 8, self.height() - self.WIDTH_BORDER_BOTTOM - self.WIDTH_BORDER_TOP, QBrush(QColor(255, 255, 255))) painter.setFont(QFont('Microsoft Yahei', 8, QFont.Bold)) painter.setPen(QColor(250, 250, 250, 220)) painter.drawText(1, 5, self.width(), 27, Qt.AlignHCenter | Qt.AlignVCenter, self.windowTitle()) painter.setPen(QColor(50, 50, 50, 255)) painter.drawText(0, 4, self.width(), 27, Qt.AlignHCenter | Qt.AlignVCenter, self.windowTitle()) painter.setPen(QColor(142, 142, 142, 255)) if self.width() > 380: painter.drawLine(self.WIDTH_FRAME_LEFT + self.OFFSET_BORDER_LEFT, self.OFFSET_BORDER_TOP + 22, self.WIDTH_FRAME_LEFT + self.OFFSET_BORDER_LEFT, self.height() - self.OFFSET_BORDER_BOTTOM - 1) @pyqtSlot() def showMaximized(self): if self.__is_sticked: return if self.__is_maximized: self.setGeometry(self.__geometry_frame) self.__switch_max_button(MButton.Type.Maximize) self.__is_maximized = False else: self.__geometry_frame = self.geometry() self.__window_stick_to(self.StickType.FULL_SCREEN) self.__switch_max_button(MButton.Type.Restore) self.__is_maximized = True def mouseDoubleClickEvent(self, event): if event.button() != Qt.LeftButton: return if self.__get_cursor_location( event) == self.CursorLocation.WINDOW_TITLE_BAR: self.showMaximized() def mousePressEvent(self, event): if event.button() != Qt.LeftButton: return if self.__get_cursor_location( event) == self.CursorLocation.WINDOW_TITLE_BAR: self.__mouse_pressed = True if self.__cursor_changed: self.__window_resizing = True self.__move_point = event.globalPos() - self.pos() def mouseMoveEvent(self, event): if self.__window_resizing: self.__change_window_size(self.__cursor_loc, event.pos()) return else: self.__cursor_loc = self.__get_cursor_location(event) self.__cursor_changed = self.__set_cursor_shape(self.__cursor_loc) if not self.__mouse_pressed: return if self.__is_maximized and not self.__is_sticked: self.resize(self.__geometry_frame.size()) self.__switch_max_button(MButton.Type.Maximize) self.__is_maximized = False if event.pos().x() < self.__geometry_frame.width(): self.__is_zdt = False else: self.__is_zdt = True self.move(event.globalPos() - QPoint(self.width() / 2, 15)) elif not self.__is_sticking and event.globalPos().y( ) < QApplication.desktop().availableGeometry().height(): if not self.__is_zdt: self.move(event.globalPos() - self.__move_point) else: self.move(event.globalPos() - QPoint(self.width() / 2, 15)) self.__cursor_loc = self.__get_cursor_location(event) if self.__cursor_loc == self.CursorLocation.SCREEN_LEFT: if self.__lyric_shown: self.__window_stick_to(self.StickType.LEFT) elif self.__cursor_loc == self.CursorLocation.SCREEN_RIGHT: if self.__lyric_shown: self.__window_stick_to(self.StickType.RIGHT) elif self.__cursor_loc == self.CursorLocation.SCREEN_TOP: if self.__lyric_shown: self.showMaximized() self.__is_sticked = True else: if self.width( ) - self.OFFSET_BORDER_LEFT - self.OFFSET_BORDER_RIGHT >= QApplication.desktop( ).screenGeometry().width(): self.resize(800, self.height()) if self.height( ) - self.OFFSET_BORDER_TOP - self.OFFSET_BORDER_BOTTOM >= QApplication.desktop( ).availableGeometry().height(): self.resize(self.width(), 600) self.__is_sticking = False self.__is_sticked = False def mouseReleaseEvent(self, event): if event.button() != Qt.LeftButton: return if self.geometry().y() < -self.OFFSET_BORDER_TOP: self.setGeometry(self.geometry().x(), -self.OFFSET_BORDER_TOP, self.geometry().width(), self.geometry().height()) self.__mouse_pressed = False self.__window_resizing = False self.__is_sticking = False self.__is_sticked = False if not self.__is_maximized: self.__is_zdt = False def resizeEvent(self, event): self.frame.setGeometry( self.OFFSET_BORDER_LEFT, self.OFFSET_BORDER_TOP + 22, self.width() - self.OFFSET_BORDER_LEFT - self.OFFSET_BORDER_RIGHT, self.height() - self.OFFSET_BORDER_TOP - self.OFFSET_BORDER_BOTTOM - 26) def setFixedSize(self, *__args): count_parm = len(__args) if count_parm == 0 or count_parm > 2: raise TypeError('Argument error occurred. (1 or 2 given)') if count_parm == 1: if isinstance(__args[0], QSize): super(ModiaWindow, self).setFixedSize(__args[0]) self.__is_fixed_size = True else: raise ValueError( 'Given argument not QSize type. (QSize type required for 1 argument)' ) else: if isinstance(__args[0], int) and isinstance(__args[1], int): super(ModiaWindow, self).setFixedSize(__args[0], __args[1]) self.__is_fixed_size = True else: raise ValueError( 'Given arguments not int type. (int type required for 2 arguments)' ) def setFixedWidth(self, p_int): if not isinstance(p_int, int): raise ValueError( 'Given argument not int type. (int type required)') self.resize(p_int, self.height()) self.__is_fixed_width = True def setFixedHeight(self, p_int): if not isinstance(p_int, int): raise ValueError( 'Given argument not int type. (int type required)') self.resize(self.width(), p_int) self.__is_fixed_height = True def setSuspendStatus(self, bool_suspended): self.__is_suspended = bool_suspended
def initUI(self): exitAction = QtGui.QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) # infoAction = QtGui.q # infoAction.triggered.connect() menubar = self.menuBar() fileMenu = menubar.addMenu('File') fileMenu.addAction(exitAction) fileMenu = menubar.addMenu('Help'); # fileMenu.addAction(infoAction) # toolbar = self.addToolBar('Exit') # toolbar.addAction(exitAction) # Button # redb = QtGui.QPushButton('Play', self) # redb.move(10, 22) # Slider sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) # Do not accept keyboard shortcuts to focus sld.setFocusPolicy(QtCore.Qt.NoFocus) # Initial X, Initial Y, Width, Height sld.setGeometry(10, 210, 500, 15) sld.valueChanged[int].connect(self.updateSlider) # Table of songs table = QTableWidget(self) table.setColumnCount(4) table.setRowCount(4) table.setHorizontalHeaderLabels(['Title', 'Artist', 'Album', 'Year']) table.move(10, 30) table.resize(580, 170) table.setColumnWidth(0, 250) table.setColumnWidth(1, 130) table.setColumnWidth(2, 120) table.setColumnWidth(3, 60) # Play self.playb = QtGui.QLabel(self) # Todo: Change icon self.playb.setPixmap(QtGui.QPixmap('D:\Documents\Pictures\L.jpg')) self.playb.setGeometry(15, 235, 40, 40) self.playb.setScaledContents(True) self.connect(self.playb, QtCore.SIGNAL("clicked()"), self.play) self.playb.pressed.connect(self.play) # Pause self.label = QtGui.QLabel(self) # Todo: Change icon self.label.setPixmap(QtGui.QPixmap('D:\Documents\Pictures\L.jpg')) self.label.setGeometry(65, 235, 40, 40) self.label.setScaledContents(True) # Timer self.timer = QtGui.QLabel(self) # Todo: Change icon self.timer.setText("00:00") self.timer.setStyleSheet("font: 15pt;") self.timer.setGeometry(520, 195, 60, 40) self.timer.setScaledContents(True) # Initial X, Initial Y, Width, Height self.setGeometry(100, 100, 600, 300) self.setWindowTitle('Music Player') # Todo: Change icon path self.setWindowIcon(QtGui.QIcon('D:\Documents\Pictures\L.jpg')) self.show()
class ThirdPart(QWizardPage): def __init__(self): super(ThirdPart, self).__init__() self.completed = False self.setTitle(u'第三方库设置') self.setSubTitle(u'需要设置的第三方库') rootLayout = QVBoxLayout() rootLayout.setContentsMargins(14, 20, 10, 20) self.tw_interface = QTableWidget(0, 3) headerLabels = QStringList() headerLabels.append(u'库名') headerLabels.append(u'库路径') headerLabels.append(u'打开') self.tw_interface.setHorizontalHeaderLabels(headerLabels) self.tw_interface.setSelectionBehavior(1) self.tw_interface.setRowCount(0) self.tw_interface.setColumnWidth(0, 200) self.tw_interface.setColumnWidth(1, 280) self.tw_interface.horizontalHeader().setStretchLastSection(True) self.mhlayout = QHBoxLayout() on_new_btn = QPushButton() on_new_btn.setText(u'添加类库') on_new_btn.clicked.connect(self.on_new) on_delete_btn = QPushButton() on_delete_btn.setText(u'删除类库') on_delete_btn.clicked.connect(self.on_delete) space = QSpacerItem(40, 28, QSizePolicy.Expanding) self.mhlayout.addSpacerItem(space) self.mhlayout.addWidget(on_new_btn) self.mhlayout.addWidget(on_delete_btn) rootLayout.addWidget(self.tw_interface) rootLayout.addLayout(self.mhlayout) self.setLayout(rootLayout) self.setStyleSheet(sheetstyle) self.alloneEnv = os.getenv('ALLONEDIR', '../..').replace('\\', '/') def on_new(self): rowIndex = self.tw_interface.rowCount() self.tw_interface.setRowCount(rowIndex + 1) ptn = self.add_button(rowIndex) self.tw_interface.setCellWidget(rowIndex, 2, ptn) def on_delete(self): rowIndex = self.tw_interface.currentRow() if rowIndex != -1: self.tw_interface.removeRow(rowIndex) def updateTable(self, id): filePath = QFileDialog.getOpenFileName(self, "请选择库", self.alloneEnv, "Library(*.lib)") if filePath.isEmpty(): return fileinfo = QFileInfo(filePath) libPath = fileinfo.absoluteDir().absolutePath() libName = fileinfo.baseName() # 支持选择文件后与系统ALLONEDIR比较一下变成相对路径 # 并且能够手动输入相对路径或包含$(ALLONEDIR)的相对路径 env = QString(os.getenv('ALLONEDIR', '../..').replace('\\', '/')) if env.endsWith('/'): env.remove(env.lastIndexOf('/'), 1) if libPath.contains(env): libPath.replace(env, QString('$$ALLONEDIR')) self.tw_interface.setItem(id, 1, QTableWidgetItem(libPath)) self.tw_interface.setItem(id, 0, QTableWidgetItem(libName)) def add_button(self, id): widget = QWidget() fileBtn = QPushButton() fileBtn.setText(u'浏览...') fileBtn.clicked.connect(lambda: self.updateTable(id)) hLayout = QHBoxLayout() hLayout.addWidget(fileBtn) hLayout.setAlignment(Qt.AlignHCenter) hLayout.setContentsMargins(0, 0, 0, 0) widget.setLayout(hLayout) return widget def initializePage(self): super(ThirdPart, self).initializePage() self.tw_interface.setRowCount(len(app.g_configurations.thirdpart_lib)) row = 0 for libinfo in app.g_configurations.thirdpart_lib: twitem0 = QTableWidgetItem(QString(libinfo["libname"])) twitem1 = QTableWidgetItem(QString(libinfo["libpath"])) self.tw_interface.setItem(row, 0, twitem0) self.tw_interface.setItem(row, 1, twitem1) ptn = self.add_button(row) self.tw_interface.setCellWidget(row, 2, ptn) row += 1 def validatePage(self): thirdpart_libs = [] if self.tw_interface.rowCount() > 0: for i in range(self.tw_interface.rowCount()): libinfo = {"libname": "", "libpath": ""} libname = self.tw_interface.item(i, 0).text() libpath = self.tw_interface.item(i, 1).text() #print unicode(libname) #print unicode(libpath) libinfo["libname"] = unicode(libname) libinfo["libpath"] = unicode(libpath) thirdpart_libs.append(libinfo) print thirdpart_libs app.g_configurations.thirdpart_lib = thirdpart_libs return True
class KeywordTable(HelpedWidget): """Shows a table of key/value pairs. The data structure expected and sent to the getter and setter is a dictionary of values.""" def __init__(self, model, table_label="", help_link=""): HelpedWidget.__init__(self, table_label, help_link) self.table = QTableWidget(self) self.table.setColumnCount(2) self.setColumnHeaders() self.table.verticalHeader().setHidden(True) self.table.setColumnWidth(0, 150) self.table.horizontalHeader().setStretchLastSection(True) self.table.setMinimumHeight(110) self.table.setSelectionMode(QAbstractItemView.SingleSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.addWidget(self.table) self.addWidget(AddRemoveWidget(self.addItem, self.removeItem)) self.connect(self.table, SIGNAL('cellChanged(int,int)'), self.tableChanged) assert isinstance(model, DictionaryModelMixin) self.model = model model.observable().attach(DictionaryModelMixin.DICTIONARY_CHANGED_EVENT, self.modelChanged) self.modelChanged() def setColumnHeaders(self, keyword_name="Keyword", value_name="Value"): self.headers = [keyword_name, value_name] self.table.setHorizontalHeaderLabels(self.headers) def addItem(self): """Called by the add button to insert a new keyword""" title = "New %s" % self.headers[0] description = "Enter new %s:" % self.headers[0] (new_keyword, ok) = QInputDialog.getText(self, title, description, QLineEdit.Normal) if ok: new_keyword = str(new_keyword).strip() self.model.addKey(new_keyword) def removeItem(self): """Called by the remove button to remove a selected keyword""" current_row = self.table.currentRow() if current_row >= 0: do_delete = QMessageBox.question(self, "Delete row?", "Are you sure you want to delete the key/value pair?", QMessageBox.Yes | QMessageBox.No ) if do_delete: key_item = self.table.item(current_row, 0) if key_item is not None: key = str(key_item.text()).strip() self.model.removeKey(key) def tableChanged(self, row, column): """Called whenever the contents of a cell changes.""" key_item = self.table.item(row, 0) if key_item is not None: key = str(key_item.text()).strip() value_item = self.table.item(row, 1) if value_item is not None: value = str(value_item.text()).strip() self.model.setValueForKey(key, value) def modelChanged(self): """Retrieves data from the model and inserts it into the table.""" values = self.model.getDictionary() blocked = self.table.blockSignals(True) for row in reversed(range(self.table.rowCount())): self.table.removeRow(row) row = 0 for key in values: key_item = QTableWidgetItem(str(key)) key_item.setFlags(key_item.flags() ^ Qt.ItemIsEditable) value_item = QTableWidgetItem(str(values[key])) self.table.insertRow(row) self.table.setItem(row, 0, key_item) self.table.setItem(row, 1, value_item) row += 1 self.table.blockSignals(blocked)
class OrbitCorrGeneral(QtGui.QWidget): """ A general orbit correction or local bump panel. """ def __init__(self, bpms, cors, parent = None): super(OrbitCorrGeneral, self).__init__(parent) self.bpms, self.cors = bpms, cors self.sb = [bpm.sb for bpm in self.bpms] self.x0, self.y0 = None, None self._update_current_orbit() self.table = QTableWidget(len(self.bpms), 9) self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) hdview = QHeaderView(Qt.Horizontal) self.table.setHorizontalHeaderLabels( ['BPM Name', 's', "Beta X", "Beta Y", "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"]) self._twiss = getTwiss([b.name for b in self.bpms], ["s", "betax", "betay", "etax"]) for i,bpm in enumerate(self.bpms): it = QTableWidgetItem(bpm.name) it.setFlags(it.flags() & (~Qt.ItemIsEditable)) self.table.setItem(i, 0, it) it = QTableWidgetItem(str(bpm.sb)) it.setFlags(it.flags() & (~Qt.ItemIsEditable)) #it.setMinimumWidth(80) self.table.setItem(i, 1, it) self.table.setItem(i, 2, QTableWidgetItem("%.4f" % self._twiss[i,1])) self.table.setItem(i, 3, QTableWidgetItem("%.4f" % self._twiss[i,2])) self.table.setItem(i, 4, QTableWidgetItem("%.4f" % self._twiss[i,3])) for j in range(5, 9): it = QTableWidgetItem(str(0.0)) it.setData(Qt.DisplayRole, str(0.0)) it.setFlags(it.flags() | Qt.ItemIsEditable) self.table.setItem(i, j, it) # use the current orbit #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i])) #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i])) #self.connect(self.table, SIGNAL("cellClicked(int, int)"), # self._cell_clicked) self.table.resizeColumnsToContents() #self.table.horizontalHeader().setStretchLastSection(True) #for i in range(4): # print "width", i, self.table.columnWidth(i) #self.table.setColumnWidth(0, 300) self.table.setColumnWidth(1, 80) vbox1 = QtGui.QVBoxLayout() frmbox = QFormLayout() self.base_orbit_box = QtGui.QComboBox() #self.base_orbit_box.addItems([ # "Current Orbit", "All Zeros"]) self.base_orbit_box.addItems(["All Zeros", "Current Orbit"]) frmbox.addRow("Orbit Base", self.base_orbit_box) grp = QtGui.QGroupBox("Local Bump") grp.setLayout(frmbox) vbox1.addWidget(grp) frmbox = QFormLayout() hln1 = QtGui.QFrame() hln1.setLineWidth(3) hln1.setFrameStyle(QtGui.QFrame.Sunken) hln1.setFrameShape(QtGui.QFrame.HLine) frmbox.addRow(hln1) self.repeatbox = QSpinBox() self.repeatbox.setRange(1, 20) self.repeatbox.setValue(3) # or connect the returnPressed() signal frmbox.addRow("&Repeat correction", self.repeatbox) self.rcondbox = QLineEdit() self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self)) self.rcondbox.setText("1e-2") frmbox.addRow("r&cond for SVD", self.rcondbox) self.scalebox = QDoubleSpinBox() self.scalebox.setRange(0.01, 5.00) self.scalebox.setSingleStep(0.01) self.scalebox.setValue(0.68) frmbox.addRow("&Scale correctors", self.scalebox) #hln2 = QtGui.QFrame() #hln2.setLineWidth(3) #hln2.setFrameStyle(QtGui.QFrame.Sunken) #hln2.setFrameShape(QtGui.QFrame.HLine) #frmbox.addRow(hln2) self.progress = QProgressBar() self.progress.setMaximum(self.repeatbox.value()) self.progress.setMaximumHeight(15) frmbox.addRow("Progress", self.progress) grp = QtGui.QGroupBox("Correction") grp.setLayout(frmbox) vbox1.addWidget(grp) #vbox.addStretch(1.0) #self.qdb = QDialogButtonBox(self) #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole) #self.qdb.addButton("R", QDialogButtonBox.ResetRole) #btn.setDefault(True) #self.qdb.addButton(QDialogButtonBox.Cancel) #self.qdb.addButton(QDialogButtonBox.Help) gbox = QtGui.QGridLayout() btn = QPushButton("Clear") self.connect(btn, SIGNAL("clicked()"), self.resetBumps) gbox.addWidget(btn, 0, 1) self.correctOrbitBtn = QPushButton("Apply") #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }"); self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply) self.correctOrbitBtn.setDefault(True) gbox.addWidget(self.correctOrbitBtn, 1, 1) gbox.setColumnStretch(0, 1) vbox1.addStretch() vbox1.addLayout(gbox) hbox1 = QtGui.QHBoxLayout() hbox1.addWidget(self.table, 2) hbox1.addLayout(vbox1, 0) self.setLayout(hbox1) self.connect(self.base_orbit_box, SIGNAL("currentIndexChanged(QString)"), self.updateTargetOrbit) self.connect(self.repeatbox, SIGNAL("valueChanged(int)"), self.progress.setMaximum) self.connect(self.table, SIGNAL("cellChanged (int, int)"), self.updateBump) #self.updateTargetOrbit(self.base_orbit_box.currentText()) def _update_current_orbit(self): pvx = [bpm.pv(field="x", handle="readback")[0] for bpm in self.bpms] pvy = [bpm.pv(field="y", handle="readback")[0] for bpm in self.bpms] self.x0 = [float(v) if v.ok else np.nan for v in catools.caget(pvx)] self.y0 = [float(v) if v.ok else np.nan for v in catools.caget(pvy)] def resetBumps(self): jx0, jy0 = 5, 6 for i in range(self.table.rowCount()): self.table.item(i, jx0).setData(Qt.DisplayRole, str(0.0)) self.table.item(i, jy0).setData(Qt.DisplayRole, str(0.0)) #self.updateTargetOrbit(self.base_orbit_box.currentText()) def call_apply(self): #print "apply the orbit" obt = [] jx, jy = 7, 8 for i in range(self.table.rowCount()): x1,err = self.table.item(i, jx).data(Qt.DisplayRole).toFloat() y1,err = self.table.item(i, jy).data(Qt.DisplayRole).toFloat() obt.append([x1, y1]) self.correctOrbitBtn.setEnabled(False) nrepeat = self.repeatbox.value() kw = { "scale": float(self.scalebox.text()), "rcond": float(self.rcondbox.text()) } self.progress.setValue(0) QApplication.processEvents() for i in range(nrepeat): err, msg = setLocalBump(self.bpms, self.cors, obt, **kw) self.progress.setValue(i+1) QApplication.processEvents() if err != 0: QtGui.QMessageBox.critical( self, "Local Orbit Bump", "ERROR: {0}\nAbort.".format(msg), QtGui.QMessageBox.Ok) #self.progress.setValue(0) break self.correctOrbitBtn.setEnabled(True) def getTargetOrbit(self): x = [self.table.item(i,7).data(Qt.DisplayRole).toFloat()[0] for i in range(self.table.rowCount())] y = [self.table.item(i,8).data(Qt.DisplayRole).toFloat()[0] for i in range(self.table.rowCount())] return (self.sb, x), (self.sb, y) def updateTargetOrbit(self, baseobt): if baseobt == "All Zeros": jx0, jx1 = 5, 7 jy0, jy1 = 6, 8 for i in range(self.table.rowCount()): it0 = self.table.item(i, jx0) it1 = self.table.item(i, jx1) it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole)) it0 = self.table.item(i, jy0) it1 = self.table.item(i, jy1) it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole)) elif baseobt == "Current Orbit": self._update_current_orbit() jx0, jx1 = 5, 7 jy0, jy1 = 6, 8 for i in range(self.table.rowCount()): dx0,err = self.table.item(i, jx0).data(Qt.DisplayRole).toFloat() it = self.table.item(i, jx1) it.setData(Qt.DisplayRole, self.x0[i] + dx0) dy0,err = self.table.item(i, jy0).data(Qt.DisplayRole).toFloat() it = self.table.item(i, jy1) it.setData(Qt.DisplayRole, self.y0[i] + dy0) #self._update_orbit_plot() x, y = self.getTargetOrbit() self.emit(SIGNAL("targetOrbitChanged(PyQt_PyObject, PyQt_PyObject)"), x, y) def updateBump(self, row, col): #print "updating ", row, col if col == 5 or col == 6: self.updateTargetOrbit(self.base_orbit_box.currentText())
class typicalWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(typicalWindow, self).__init__(parent) # QtGui.QMainWindow.__init__(self) #window self.setWindowTitle(winTitle) self.central_widget=QWidget(self) self.setCentralWidget(self.central_widget) self.masterLayout=QGridLayout(self.central_widget) self.masterLayout.setAlignment(QtCore.Qt.AlignTop) #mainlayout self.vertical_order_layout=QtGui.QBoxLayout(2) self.vertical_order_layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignVCenter) self.masterLayout.addLayout(self.vertical_order_layout, 0,0,1,1) self.topDivideLayout=QGridLayout() self.botDivideLayout=QGridLayout() self.upper_layout=QGridLayout() self.topDivideLayout.addLayout(self.upper_layout, 0,0,1,1) self.lower_layout=QGridLayout() self.lower_layout.setAlignment(QtCore.Qt.AlignTop) self.botDivideLayout.addLayout(self.lower_layout, 0,0,1,1) self.midLayout=QGridLayout() self.midLayout.setAlignment(QtCore.Qt.AlignTop) self.base_layout=QGridLayout() self.base_layout.setAlignment(QtCore.Qt.AlignTop) self.botDivideLayout.addLayout(self.base_layout, 4,0,1,1) #sshFile=open(os.path.join(__location__, styleSheetFile+".stylesheet"), 'r') #self.styleData=sshFile.read() #sshFile.close #self.setStyleSheet(self.styleData) self.top=QtGui.QFrame(self) self.top.setFrameShape(QtGui.QFrame.StyledPanel) self.top.setLayout(self.topDivideLayout) self.bottom=QtGui.QFrame(self) self.bottom.setFrameShape(QtGui.QFrame.StyledPanel) self.bottom.setLayout(self.botDivideLayout) self.splitPlane=QtGui.QSplitter(QtCore.Qt.Vertical) self.splitPlane.addWidget(self.top) self.splitPlane.addWidget(self.bottom) self.splitPlane.setSizes([650, 650]) self.vertical_order_layout.addWidget(self.splitPlane) #layouts self.window_layer_00=QGridLayout() self.upper_layout.addLayout(self.window_layer_00, 0,0,1,1) self.window_layer_01=QGridLayout() self.upper_layout.addLayout(self.window_layer_01,1,0,1,1) self.window_layer_02=QGridLayout() self.upper_layout.addLayout(self.window_layer_02, 2,0,1,1) self.window_layer_03=QGridLayout() self.upper_layout.addLayout(self.window_layer_03,3,0,1,1) self.window_layer_04=QGridLayout() self.upper_layout.addLayout(self.window_layer_04, 4,0,1,1) self.window_layer_05=QGridLayout() self.upper_layout.addLayout(self.window_layer_05,5,0,1,1) self.window_layer_06=QGridLayout() self.midLayout.addLayout(self.window_layer_06, 6,0,1,1) self.frame_layout=QGridLayout() self.frame_layout.setAlignment(QtCore.Qt.AlignTop) self.lower_layout.addLayout(self.frame_layout, 0,0,1,1) self.frameWidget=QtGui.QGridLayout() self.frameWidget.setContentsMargins(5,10,5,10) self.frameOverride=QtGui.QFrame() self.frameOverride.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") self.frameOverride.setFixedHeight(100) self.frame_layout.addLayout(self.frameWidget, 0,0,1,1) self.frame_layout.addWidget(self.frameOverride, 0,0,1,1) self.frame_title_layout=QGridLayout() self.frameWidget.addLayout(self.frame_title_layout, 0,0,1,1) self.frame_radio_layout=QGridLayout() self.frameWidget.addLayout(self.frame_radio_layout, 1,0,1,1) self.frame_btn_layout=QGridLayout() self.frameWidget.addLayout(self.frame_btn_layout, 2,0,1,1) self.btm_btn_layout=QtGui.QGridLayout() self.btm_btn_layout.setAlignment(QtCore.Qt.AlignTop) self.btm_btn_layout.setContentsMargins(5,10,5,10) self.wbFrame=QtGui.QFrame() self.wbFrame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") self.btm_over_layout=QtGui.QGridLayout() self.btm_over_layout.setAlignment(QtCore.Qt.AlignTop) self.btm_over_layout.addLayout(self.btm_btn_layout, 0,0,1,1) self.btm_over_layout.addWidget(self.wbFrame, 0,0,1,1) self.pkt_layout= QGridLayout() self.pkt_layout.setAlignment(QtCore.Qt.AlignTop) self.pkt_widget=QGridLayout() self.pkt_widget.setContentsMargins(5,5,5,5) self.pkt_frame=QFrame() self.pkt_frame.setMinimumWidth(650) self.pkt_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") self.base_layout.addLayout(self.pkt_layout, 0,0,1,1) self.wndw_layer_pkt=QtGui.QGridLayout() self.wndw_layer_pkt.setAlignment(QtCore.Qt.AlignTop) self.pkt_widget.addLayout(self.wndw_layer_pkt, 0,0,1,1) self.park_btn_pkt=QtGui.QBoxLayout(2) self.park_btn_pkt.setAlignment(QtCore.Qt.AlignTop) self.park_btn_pkt.setContentsMargins(5,2,5,8) self.wndw_layer_pkt.addLayout(self.park_btn_pkt, 0,0,1,1) self.park_frame=QtGui.QFrame() self.park_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") #widgets self.drop_lbl_01=QLabel() self.drop_lbl_01.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) self.drop_lbl_01.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.window_layer_01.addWidget(self.drop_lbl_01, 0,0,1,1) self.drop_01=QComboBox() self.window_layer_01.addWidget(self.drop_01, 0,1,1,1) self.drop_01.addItems(prjFileName) self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.drop_01.customContextMenuRequested.connect(self.onRightClick) # self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.drop_lbl_02=QLabel() self.drop_lbl_02.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) self.drop_lbl_02.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.window_layer_01.addWidget(self.drop_lbl_02, 0,2,1,1) self.drop_02=QComboBox() self.window_layer_01.addWidget(self.drop_02, 0,3,1,1) # QtCore.QObject.connect(self.drop_02, SIGNAL("currentIndexChanged(QString)"), # self.on_drop_01_changed) self.drop_02.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) QtCore.QObject.connect(self.drop_01, SIGNAL("currentIndexChanged(QString)"), self.on_drop_01_changed) self.button_01=QPushButton("Set") self.button_01.setToolTip("set") self.connect(self.button_01, SIGNAL('clicked()'), self.listCreate) self.window_layer_01.addWidget(self.button_01, 0,4,1,1) self.button_02=QPushButton("Set2") self.button_02.setToolTip("set2") self.connect(self.button_02, SIGNAL('clicked()'), self.connectButton01) self.window_layer_01.addWidget(self.button_02, 0,5,1,1) self.drop_lbl_03=QLabel() self.drop_lbl_03.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) self.drop_lbl_03.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.window_layer_02.addWidget(self.drop_lbl_03, 0,0,1,1) self.drop_03=QComboBox() self.window_layer_02.addWidget(self.drop_03, 0,1,1,1) # QtCore.QObject.connect(self.drop_03, SIGNAL("currentIndexChanged(QString)"), # self.on_drop_01_changed) self.drop_03.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_03, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.button_03=QPushButton("button_03") self.button_03.setToolTip("button_03") self.connect(self.button_03, SIGNAL('clicked()'), self.connectButton01) self.window_layer_02.addWidget(self.button_03, 0,2,1,1) self.button_04=QPushButton("button_04") self.button_04.setToolTip("button_04") self.connect(self.button_04, SIGNAL('clicked()'), self.connectButton01) self.window_layer_02.addWidget(self.button_04, 0,3,1,1) self.button_05=QPushButton("button_05") self.button_05.setToolTip("button_05") self.connect(self.button_05, SIGNAL('clicked()'), self.connectButton01) self.window_layer_02.addWidget(self.button_05, 0,4,1,1) self.drop_04=QComboBox() self.window_layer_04.addWidget(self.drop_04, 0,2,1,1) # QtCore.QObject.connect(self.drop_04, SIGNAL("currentIndexChanged(QString)"), # self.on_drop_01_changed) self.drop_04.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_04, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.list_frame=QFrame() self.list_frame.setStyleSheet("color: rgb"+str(buttonColoursDict.get("red"))) self.list_layout=QHBoxLayout() self.list_frame.setLayout(self.list_layout) self.drop_list_builder_05=QComboBox() self.drop_list_builder_05.addItems(get_a_play_list) QtCore.QObject.connect(self.drop_list_builder_05, SIGNAL("currentIndexChanged(QString)"), self.build) self.drop_list_builder_05.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_list_builder_05, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.list_layout.addWidget(self.drop_list_builder_05) self.window_layer_04.addWidget(self.list_frame, 0,3,1,1) self.drop_list_06=QComboBox() # QtCore.QObject.connect(self.drop_list_06, SIGNAL("currentIndexChanged(QString)"),self.load) self.drop_list_06.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_list_06, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) #if len(pres)<1: #self.drop_list_06.setEnabled(0) #else: #self.drop_list_06.setEnabled(1) self.drop_list_06.addItems(alist2) self.list_layout.addWidget(self.drop_list_06) self.type_list_drop=QComboBox() self.type_list_drop.addItems(typesOfStuffInList) QtCore.QObject.connect(self.type_list_drop, SIGNAL("currentIndexChanged(QString)"), self.on_drop_01_changed) self.window_layer_04.addWidget(self.type_list_drop, 0,5,1,1) self.button_06=QPushButton("button_06") self.button_06.setToolTip("button_06") self.connect(self.button_06, SIGNAL('clicked()'), self.connectButton01) self.window_layer_04.addWidget(self.button_06, 0,6,0,1) headers = ('Name', 'Date', 'Path') self.listWidg = QTableWidget(1, 3) # self.listWidg.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) # self.listWidg.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) # self.listWidg.cellPressed.connect(self.clicked) # self.listWidg=QTableWidget(0, 3) self.listWidg.setHorizontalHeaderLabels(headers) # tableWidget=self.listWidg self.listWidg.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked) col1, col2, col3= 240, 160, 500 self.listWidg.setColumnWidth(0, col1) self.listWidg.setColumnWidth(1, col2) self.listWidg.setColumnWidth(2, col3) self.listWidg.setSelectionBehavior(QAbstractItemView.SelectRows) self.listWidg.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.listWidg.customContextMenuRequested.connect(self.RightClick) # self.listWidg.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) self.connect(self.listWidg, SIGNAL("itemClicked(QTableWidgetItem *)"), self.clicked) self.connect(self.listWidg, SIGNAL("itemDoubleClicked(QTableWidgetItem *)"), self.dclicked) self.window_layer_05.addWidget(self.listWidg, 0,2,1,1) self.status_lbl=QLabel() self.status_lbl.setStyleSheet('background-color:transparent') self.status_lbl.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) self.frame_title_layout.addWidget(self.status_lbl, 0,2,1,1) self.spaceHold=QLabel() self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) self.frame_title_layout.addWidget(self.spaceHold, 0,0,1,1) self.checkbox=QCheckBox("add") self.checkbox.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") # self.checkbox.setContentsMargins(5,0,0,0) self.checkbox.setChecked(1) self.frame_title_layout.addWidget(self.checkbox, 0,1,1,1) self.radiobox=QGridLayout() self.radio=QRadioButton("radio") self.radio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radio.setChecked(1) self.radiobox.addWidget(self.radio, 0,0,1,1) self.newradio=QRadioButton("newradio") self.newradio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.newradio, 0,2,1,1) self.frame_len_layout=QGridLayout() self.frame_len_layout.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) #self.frame_title_layout.addWidget(self.frame_len_layout, 1,3,1,1) self.spaceHold=QLabel() self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) self.frame_title_layout.addWidget(self.spaceHold, 0,3,1,1) self.over=QRadioButton("over") self.over.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.over, 1,1,1,1) self.head_lbl=QLabel("from") self.head_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.head_lbl, 1, 4,1,1) self.head_field=QTextEdit("") self.head_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.head_field, 1, 5,1,1) self.toe_lbl=QLabel("til") self.toe_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.toe_lbl, 1, 6,1,1) self.toe_field=QTextEdit("") self.toe_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.toe_field, 1, 7,1,1) self.fieldBox=QLineEdit() self.fieldBox.setVisible(0) self.fieldBox.setText(defaultText) self.play_in_rv_button=QPushButton("play in RV") self.connect(self.play_in_rv_button, SIGNAL('clicked()'), self.play_in_rv) self.frame_btn_layout.addWidget(self.play_in_rv_button, 0,0,0,1) self.look_btn=QPushButton("compare") self.connect(self.look_btn, SIGNAL('clicked()'), self.compare_in_rv) self.frame_btn_layout.addWidget(self.look_btn, 0,1, 0,1) # self.link_btn=QPushButton("link") # self.connect(self.link_btn, SIGNAL('clicked()'), self.play_in_rv) # self.frame_btn_layout.addWidget(self.link_btn, 0,2,1,1) self.create_btn=QPushButton("Publish") self.connect(self.create_btn, SIGNAL('clicked()'), self.pub_to_shotgun) self.frame_btn_layout.addWidget(self.create_btn, 0,3, 1,1) self.pocketTitle=QPushButton("title") self.pocketTitle.setObjectName('label') #self.pocketTitle.setStyleSheet("QPushButton#label{font-weight:500; color: rgb"str(buttonColorDict).get("yello"))+"; button-color: rgba(255,255,255,0); font-size: 10pt; border-width: 0px; font-style: bold;}") self.connect(self.pocketTitle, SIGNAL('clicked()'), self.send) self.connect(self.pocketTitle, SIGNAL('customContextMenuRequested(QPoint)'), lambda: self.send()) self.park_btn_pkt.addWidget(self.pocketTitle) self.a_btn=QPushButton("a_btn") #self.a_btn.setStyleSheet("background-color: rgb"str(buttonColorDict).get("yello"))) self.connect(self.a_btn, SIGNAL('clicked()'), self.play_in_rv) self.park_btn_pkt.addWidget(self.a_btn) self.card_menu=QMenu("card") self.card_menuBar=self.menuBar() self.card_menuBar.addMenu(self.card_menu) self.park_btn_pkt.addWidget(self.card_menuBar) buttonGrp.append(self.card_menuBar) self.card_btn=QToolButton() self.card_btn.setPopupMode(QToolButton.MenuButtonPopup) self.card_btn.setMenu(self.card_menu) self.card_special_btn=QPushButton("card special") self.connect(self.card_special_btn, SIGNAL('clicked()'), self.card_special_callup) action=QtGui.QWidgetAction(self.card_btn) action.setDefaultWidget(self.card_special_btn) self.card_btn.menu().addAction(action) self.B_card_btn=QToolButton() self.B_card_btn.setPopupMode(QToolButton.MenuButtonPopup) self.B_card_btn.setMenu(self.card_menu) self.B_card_special_btn=QPushButton("card special") self.connect(self.B_card_special_btn, SIGNAL('clicked()'),self.B_card_special_callup) action=QtGui.QWidgetAction(self.B_card_btn) action.setDefaultWidget(self.B_card_special_btn) self.B_card_btn.menu().addAction(action) self.start_window() def start_window(self): # self.connectButton01 print PROJECT print SCENE print SHOT index = self.drop_01.findText(SCENE, QtCore.Qt.MatchFixedString) self.drop_01.setCurrentIndex(index) self.get_scene() index2 = self.drop_02.findText(SHOT, QtCore.Qt.MatchFixedString) self.drop_02.setCurrentIndex(index2) self.listCreate() def buttonToggle(self): get_a_layout=self.park_btn_pkt get_size=get_a_layout.getContentsMargine() if get_size==(0,0,0,0): self.setvisible() else: self.setinvisible() def setinvisible(self): for each in buttonGrp: each.setVisible(0) self.park_btn_pkt.setContentsMargine(0,0,0,0) def setvisible(self): for each in buttonGrp: each.setVisible(1) self.park_btn_pkt.setContentsMargine(5,8,5,8) def get_scene(self): scene=self.drop_01 scene=scene.currentText() getPath='/jobs/'+PROJECT+'/'+scene get_items=os.listdir(getPath) get_items=sorted(get_items) # get_items=set(get_items) # get_items=sorted(get_items) self.get_shot(get_items) def get_shot(self, get_items): getDropScene=self.drop_02 getDropScene.clear() getDropScene.addItems(get_items) def onRightClick(self): scene=self.drop_01 scene=scene.currentText() path='/jobs/'+PROJECT+'/'+scene+"/" self.launch_folder(path) def launch_folder(self, path): # command="xdg-open '%s'"%path command="dolphin '%s'"%path subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def on_drop_01_changed(self): self.get_scene() newcol1=self.listWidg.columnWidth(0) newcol2=self.listWidg.columnWidth(1) newcol3=self.listWidg.columnWidth(2) if newcol1==0: col1, col2, col3= 240, 160, 500 else: col1, col2, col3= newcol1, newcol2, newcol3 # findproject=self.drop_01 self.listWidg.clear() self.status_lbl.clear() # self.listCreate() # self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype) # self.drop_03.addItems(get_items) # model, countdata, listArray =self.get_listStuff() # if self.on_drop_01=="item1": # buildListPath=pathList.get("listpathtype").replace(getUser, newUser) # self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype) # elif self.on_drop_01=="item2": # buildListPath=pathList.get("listpathtype2").replace(getUser, newUser) # self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype) def clicked(self): print "hi" def dclicked(self): print "hello" def get_listStuff(self): listArray=self.listWidg countdata=listArray.rowCount() model=listArray.model() return model, countdata, listArray def getListWidgetData(self): model, countdata, listArray =self.get_listStuff() dataInListWidget=[] for row in range(model.rowCount()): dataInListWidget.append([]) for column in range(model.columnCount()): index = model.index(row, column) dataInListWidget[row].append(str(model.data(index).toString())) return dataInListWidget, countdata def grab_folder_items(self): directory=rvFolder getstuff=os.listdir(directory) getUser=M_USER (dataInListWidget, countdata)=self.getListWidgetData() # self.listWidg.setRowCount(0) # self.listWidg.setColumnCount(0) try: getFiles=[os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))] pass except: print "nothing found" return getFile=[(each) for each in getFiles if getpwuid(stat(each).st_uid).pw_name==getUser] getFiles.sort(key=lambda x: os.path.getmtime(x)) fileDict=[] for each in getFiles: statbuf=os.stat(each) timeFormat=time.strftime('%m/%d/%Y', time.gmtime(os.path.getctime(each))) getAccTime=time.ctime(os.path.getmtime(each)) if " " in str(getAccTime): getAccTime=getAccTime.split(" ") getAccTime=getAccTime[1].split(" ")[1] else: getAccTime=getAccTime.split(" ")[3] timeFormat=timeFormat+" "+getAccTime makeDict=(each, timeFormat) fileDict.append(makeDict) count=len(fileDict) fileDict=reversed(fileDict) dictItems=fileDict return fileDict, count def listCreate(self): self.listWidg.setColumnCount(3) fileDict, count=self.grab_folder_items() self.listWidg.setRowCount(count) for row, item in enumerate(fileDict): key=item[0].split('/')[-1] path=item[0] value=item[1] self.listWidg.setItem(row, 0, QTableWidgetItem(key)) self.listWidg.setItem(row, 1, QTableWidgetItem(value)) self.listWidg.setItem(row, 2, QTableWidgetItem(path)) def is_listWid_item_selected(self): listW=self.listWidg (dataInListWidget, countdata)=self.getListWidgetData() get_string_id=[] for index in xrange(countdata): get=listW.item(index, 0).isSelected() if get==True: getObj=listW.item(index, 2).text() getObj=str(getObj) get_string_id.append(getObj) else: get=listW.item(index, 1).isSelected() if get==True: getObj=listW.item(index, 2).text() getObj=str(getObj) get_string_id.append(getObj) else: get=listW.item(index, 2).isSelected() if get==True: getObj=listW.item(index, 2).text() getObj=str(getObj) get_string_id.append(getObj) return get_string_id def build(self): list_build=self.drop_list_builder_05 list_build_function=list_build.currentText() selected_in_list=self.is_listWid_item_selected() allthePaths=('//', '//') allthePathsDic={"firstPath":'//', "secondPath":'//'} #drop_list_builder_05 getlisttype=self.type_list_drop listtype=getlisttype.currentText() if selected_in_list>1: getItems=[(each) for each in selected_in_list] nameToSave=' '.join(getItems) if listtype=="firstPath": suffixAppend="first" path=allthePathsDic.get("firstPath") if listtype=="secondPath": suffixAppend="second" path=allthePathsDic.get("secondPath") compareBucket=[] getitems=[(suffixAppend+":"+each.split("/")[-1]) for each in selected_in_list] name_to_save=' '.join(getitems) if list_build_function==get_a_play_list[1]: prompt="name of list:" getcomment=self.makeBody(prompt) if getComment==None: print "needs name" return else: pass getComment=getComment.replace(' ', '_') #shotList=suffixAppend+"_"+getComment+"storedText.txt" fileBuild=path+shotList copyfilemessage="creating in "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message' ,copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: if os.path.isfile(fileBuild)==True: cmessage="create over "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return else: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return elif list_build_function==get_a_play_list[2]: fileDict, list=self.getAllLists(allthePaths) def getAllLists(self, stuff): fileDict={} for each in stuff: getList, getnamesdic=self.obtain_presets(each) getnames=getnamesdic.keys() for eachp in eachn in map(None, getList, getnames): dictlist={eachn:eachp} fileDict.update(dictlist) return fileDict, getList def obtain_presets(self, morestuff): preset=False format=".txt" getpreset=[os.path.join(dirpath, name) for dirpath, dirnames, files in os.walk(morestuff) for name in files if name.lower().endswith(format)] preset=[(each) for each in getpreset if "storedText" in each] getlistnames={} for each in preset: getName=each.split("/")[-1] nam=getName.split("_") getpletename='_'.join(nam[:-1]) diction={getpletename:nam[0]} getlistnames.update(diction) return preset, getlistnames def makeBody(self, prompt): text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt) if ok: project=(str(text)) else: return return project def makeBodyFilled(self, prompt, message): text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt, QtGui.QLineEdit.Normal, message) if ok and text: project=(str(text)) else: return return project def load(self): list_load=self.drop_list_06 list_load_function=list_load.currentText() allthePaths=('//', '//') allthePathsDic={"firstPath":'//', "secondPath":'//'} if list_load_function==presetlist[0]: prompt="name of list:" getcomment=self.makeBody(prompt) if getComment==None: print "needs name" return else: pass getComment=getComment.replace(' ', '_') shotList=suffixAppend+"_"+getComment+"storedText.txt" fileBuild=path+shotList copyfilemessage="creating in "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message', copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: if os.path.isfile(fileBuild)==True: cmessage="create over "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return else: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return elif list_build_function==list_build[2]: fileDict, list=self.getAllLists(allthePaths) def reset_callup(self): allthePaths=('//', '//') allthePathsDic={"firstPath":'//', "secondPath":'//'} getlisttype=self.type_list_drop listtype=getlisttype.currentText() if listtype=="firstPath": directory=allthePathsDic.get("firstPath") getUser=getUser self.directory_for_taking(getUser, directory) def directory_for_taking(self, getUser, directory): model, countdata, listArray =self.get_listStuff() # self.status_lbl def connectButton01(self): print "hi" self.listCreate() def RightClick(self): selected_in_list=self.is_listWid_item_selected() path=str(selected_in_list[0])+"/" # command="xdg-open '%s'"%path self.launch_folder(path) def play_in_rv(self): selected_in_list=self.is_listWid_item_selected() command="rv "+str(selected_in_list[0])+"/*" print "you are running command: "+command subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def compare_in_rv(self): selected_in_list=self.is_listWid_item_selected() if len(selected_in_list)<2: print "must select more than one object in list" else: command="rv -wipe "+str(selected_in_list[0])+"/* "+str(selected_in_list[1])+"/*" print "you are running command: "+command subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def pub_to_shotgun(self): selected_in_list=self.is_listWid_item_selected() getPath=selected_in_list[0]+'/'+foldertypeplay+"/" get_items=os.listdir(getPath) getFileName=get_items[0].split(".")[0] print getFileName # getFileName=str(getFileName)+"-"+str(typeplay) # print getFileName format="_jpg" # command='msubmitCmd -p "'+str(selected_in_list[0])+getFileName+'.%04d'+formatEXT+'"'+' -s '+str(startFR)+' -e '+str(endFR)+' -t review -n='+comment+' --task techanim -audio '+audioFile+' -audioOffset 0' command='msubmitCmd -p "'+str(selected_in_list[0])+'/'+typeplay+format+'/'+getFileName+'.%04d'+formatEXT+'"'+' -s '+str(startFR)+' -e '+str(endFR)+' -t review -n="'+comment+'" --task '+DEPT # command="rv "+str(selected_in_list[0])+"/*" print "you are running command: "+command subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def send(self): print "end" def card_special_callup(self): print "card_special_callup" def Bcard_special_callup(self): print "B_card_special_callup" def B_card_special_callup(self): print "B_card_special_callup"
class OrbitCorrGeneral(QtGui.QWidget): """ A general orbit correction or local bump panel. """ def __init__(self, bpms, cors, parent = None): super(OrbitCorrGeneral, self).__init__(parent) self.bpms, self.cors = bpms, cors self.sb = [bpm.sb for bpm in self.bpms] self.x0, self.y0 = None, None self._update_current_orbit() self.table = QTableWidget(len(self.bpms), 9) self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) hdview = QHeaderView(Qt.Horizontal) self.table.setHorizontalHeaderLabels( ['BPM Name', 's', "Beta X", "Beta Y", "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"]) self._twiss = getTwiss([b.name for b in self.bpms], ["s", "betax", "betay", "etax"]) for i,bpm in enumerate(self.bpms): it = QTableWidgetItem(bpm.name) it.setFlags(it.flags() & (~Qt.ItemIsEditable)) self.table.setItem(i, 0, it) it = QTableWidgetItem(str(bpm.sb)) it.setFlags(it.flags() & (~Qt.ItemIsEditable)) #it.setMinimumWidth(80) self.table.setItem(i, 1, it) self.table.setItem(i, 2, QTableWidgetItem("%.4f" % self._twiss[i,1])) self.table.setItem(i, 3, QTableWidgetItem("%.4f" % self._twiss[i,2])) self.table.setItem(i, 4, QTableWidgetItem("%.4f" % self._twiss[i,3])) for j in range(5, 9): it = QTableWidgetItem(str(0.0)) it.setData(Qt.DisplayRole, str(0.0)) it.setFlags(it.flags() | Qt.ItemIsEditable) self.table.setItem(i, j, it) # use the current orbit #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i])) #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i])) #self.connect(self.table, SIGNAL("cellClicked(int, int)"), # self._cell_clicked) self.table.resizeColumnsToContents() #self.table.horizontalHeader().setStretchLastSection(True) #for i in range(4): # print "width", i, self.table.columnWidth(i) #self.table.setColumnWidth(0, 300) self.table.setColumnWidth(1, 80) vbox1 = QtGui.QVBoxLayout() frmbox = QFormLayout() self.base_orbit_box = QtGui.QComboBox() #self.base_orbit_box.addItems([ # "Current Orbit", "All Zeros"]) self.base_orbit_box.addItems(["All Zeros", "Current Orbit"]) frmbox.addRow("Orbit Base", self.base_orbit_box) grp = QtGui.QGroupBox("Local Bump") grp.setLayout(frmbox) vbox1.addWidget(grp) frmbox = QFormLayout() hln1 = QtGui.QFrame() hln1.setLineWidth(3) hln1.setFrameStyle(QtGui.QFrame.Sunken) hln1.setFrameShape(QtGui.QFrame.HLine) frmbox.addRow(hln1) self.repeatbox = QSpinBox() self.repeatbox.setRange(1, 20) self.repeatbox.setValue(3) # or connect the returnPressed() signal frmbox.addRow("&Repeat correction", self.repeatbox) self.rcondbox = QLineEdit() self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self)) self.rcondbox.setText("1e-2") frmbox.addRow("r&cond for SVD", self.rcondbox) self.scalebox = QDoubleSpinBox() self.scalebox.setRange(0.01, 5.00) self.scalebox.setSingleStep(0.01) self.scalebox.setValue(0.68) frmbox.addRow("&Scale correctors", self.scalebox) #hln2 = QtGui.QFrame() #hln2.setLineWidth(3) #hln2.setFrameStyle(QtGui.QFrame.Sunken) #hln2.setFrameShape(QtGui.QFrame.HLine) #frmbox.addRow(hln2) self.progress = QProgressBar() self.progress.setMaximum(self.repeatbox.value()) self.progress.setMaximumHeight(15) frmbox.addRow("Progress", self.progress) grp = QtGui.QGroupBox("Correction") grp.setLayout(frmbox) vbox1.addWidget(grp) #vbox.addStretch(1.0) #self.qdb = QDialogButtonBox(self) #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole) #self.qdb.addButton("R", QDialogButtonBox.ResetRole) #btn.setDefault(True) #self.qdb.addButton(QDialogButtonBox.Cancel) #self.qdb.addButton(QDialogButtonBox.Help) gbox = QtGui.QGridLayout() btn = QPushButton("Clear") self.connect(btn, SIGNAL("clicked()"), self.resetBumps) gbox.addWidget(btn, 0, 1) self.correctOrbitBtn = QPushButton("Apply") #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }"); self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply) self.correctOrbitBtn.setDefault(True) gbox.addWidget(self.correctOrbitBtn, 1, 1) gbox.setColumnStretch(0, 1) vbox1.addStretch() vbox1.addLayout(gbox) hbox1 = QtGui.QHBoxLayout() hbox1.addWidget(self.table, 2) hbox1.addLayout(vbox1, 0) self.setLayout(hbox1) self.connect(self.base_orbit_box, SIGNAL("currentIndexChanged(QString)"), self.updateTargetOrbit) self.connect(self.repeatbox, SIGNAL("valueChanged(int)"), self.progress.setMaximum) self.connect(self.table, SIGNAL("cellChanged (int, int)"), self.updateBump) #self.updateTargetOrbit(self.base_orbit_box.currentText()) def _update_current_orbit(self): pvx = [bpm.pv(field="x", handle="readback")[0] for bpm in self.bpms] pvy = [bpm.pv(field="y", handle="readback")[0] for bpm in self.bpms] self.x0 = [float(v) if v.ok else np.nan for v in catools.caget(pvx)] self.y0 = [float(v) if v.ok else np.nan for v in catools.caget(pvy)] def resetBumps(self): jx0, jy0 = 5, 6 for i in range(self.table.rowCount()): self.table.item(i, jx0).setData(Qt.DisplayRole, str(0.0)) self.table.item(i, jy0).setData(Qt.DisplayRole, str(0.0)) #self.updateTargetOrbit(self.base_orbit_box.currentText()) def call_apply(self): #print "apply the orbit" obt = [] jx, jy = 7, 8 for i in range(self.table.rowCount()): x1,err = self.table.item(i, jx).data(Qt.DisplayRole).toFloat() y1,err = self.table.item(i, jy).data(Qt.DisplayRole).toFloat() obt.append([x1, y1]) self.correctOrbitBtn.setEnabled(False) nrepeat = self.repeatbox.value() kw = { "scale": float(self.scalebox.text()), "rcond": float(self.rcondbox.text()) } self.progress.setValue(0) QApplication.processEvents() for i in range(nrepeat): err, msg = setLocalBump(self.bpms, self.cors, obt, **kw) self.progress.setValue(i+1) QApplication.processEvents() if err != 0: QtGui.QMessageBox.critical( self, "Local Orbit Bump", "ERROR: {0}\nAbort.".format(msg), QtGui.QMessageBox.Ok) #self.progress.setValue(0) break self.correctOrbitBtn.setEnabled(True) def getTargetOrbit(self): x = [self.table.item(i,7).data(Qt.DisplayRole).toFloat()[0] for i in range(self.table.rowCount())] y = [self.table.item(i,8).data(Qt.DisplayRole).toFloat()[0] for i in range(self.table.rowCount())] return (self.sb, x), (self.sb, y) def updateTargetOrbit(self, baseobt): if baseobt == "All Zeros": jx0, jx1 = 5, 7 jy0, jy1 = 6, 8 for i in range(self.table.rowCount()): it0 = self.table.item(i, jx0) it1 = self.table.item(i, jx1) it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole)) it0 = self.table.item(i, jy0) it1 = self.table.item(i, jy1) it1.setData(Qt.DisplayRole, it0.data(Qt.DisplayRole)) elif baseobt == "Current Orbit": self._update_current_orbit() jx0, jx1 = 5, 7 jy0, jy1 = 6, 8 for i in range(self.table.rowCount()): dx0,err = self.table.item(i, jx0).data(Qt.DisplayRole).toFloat() it = self.table.item(i, jx1) it.setData(Qt.DisplayRole, self.x0[i] + dx0) dy0,err = self.table.item(i, jy0).data(Qt.DisplayRole).toFloat() it = self.table.item(i, jy1) it.setData(Qt.DisplayRole, self.y0[i] + dy0) #self._update_orbit_plot() x, y = self.getTargetOrbit() self.emit(SIGNAL("targetOrbitChanged(PyQt_PyObject, PyQt_PyObject)"), x, y) def updateBump(self, row, col): #print "updating ", row, col if col == 5 or col == 6: self.updateTargetOrbit(self.base_orbit_box.currentText())
class AvailableWidget(QWidget): def __init__(self, parent, available): QWidget.__init__(self, parent) self._parent = parent self._available = available vbox = QVBoxLayout(self) self._table = QTableWidget(1, 5) self._table.removeRow(0) vbox.addWidget(self._table) self._headers = ('Name', 'Version', 'Description', "Authors", "Web") ui_tools.load_table(self._table, self._headers, _format_for_table(available)) self._table.setColumnWidth(0, 200) hbox = QHBoxLayout() btnInstall = QPushButton('Install') btnInstall.setMaximumWidth(100) hbox.addWidget(btnInstall) hbox.addWidget(QLabel(self.tr("NINJA needs to be restarted for " \ "changes to take effect."))) vbox.addLayout(hbox) # hbox = QHBoxLayout() # hbox.addWidget(QLabel( # self.tr("Add an external Plugin. URL Zip File:"))) # self._link = QLineEdit() # hbox.addWidget(self._link) # btnAdd = QPushButton(self.tr("Add")) # hbox.addWidget(btnAdd) # vbox.addLayout(hbox) # lblExternalPlugin = QLabel( # self.tr("(Write the URL of the Plugin and press 'Add')")) # lblExternalPlugin.setAlignment(Qt.AlignRight) # vbox.addWidget(lblExternalPlugin) self.connect(btnInstall, SIGNAL("clicked()"), self._install_plugins) # self.connect(btnAdd, SIGNAL("clicked()"), self._install_external) def _install_plugins(self): data = _format_for_table(self._available) plugins = ui_tools.remove_get_selected_items(self._table, data) #get the download link of each plugin for p_row in plugins: #search the plugin for p_dict in self._available: if unicode(p_dict["name"]) == unicode(p_row[0]): p_data = p_dict break #append the downlod link p_row.append(p_data["download"]) #download self._parent.download_plugins(plugins) def remove_item(self, plugin_name): plugin = _get_plugin(plugin_name, self._available) self._available.remove(plugin) def _install_external(self): if self._link.text().isEmpty(): QMessageBox.information(self, self.tr("External Plugins"), self.tr("URL from Plugin missing...")) return plug = [ file_manager.get_module_name(str(self._link.text())), 'External Plugin', '1.0', str(self._link.text()) ] self.parent().download_plugins(plug) self._link.setText('') def add_table_items(self, plugs): self._available += plugs data = _format_for_table(self._available) ui_tools.load_table(self._table, self._headers, data)
class ScanRecordTable(QGroupBox): """ GUI component. Displays a list of previous scan results. Selecting a scan causes details of the scan to appear in other GUI components (list of barcodes in the barcode table and image of the puck in the image frame). """ COLUMNS = ['Date', 'Time', 'Plate Type', 'Valid', 'Invalid', 'Empty'] def __init__(self, barcode_table, image_frame, options): super(ScanRecordTable, self).__init__() # Read the store from file self._store = Store(options.store_directory.value(), options) self._options = options self._barcodeTable = barcode_table self._imageFrame = image_frame self.setTitle("Scan Records") self._init_ui() self._load_store_records() def _init_ui(self): # Create record table - lists all the records in the store self._table = QTableWidget() self._table.setFixedWidth(440) self._table.setFixedHeight(600) self._table.setColumnCount(len(self.COLUMNS)) self._table.setHorizontalHeaderLabels(self.COLUMNS) self._table.setColumnWidth(0, 70) self._table.setColumnWidth(1, 55) self._table.setColumnWidth(2, 85) self._table.setColumnWidth(3, 60) self._table.setColumnWidth(4, 60) self._table.setColumnWidth(5, 60) self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self._table.cellPressed.connect(self._record_selected) # Delete button - deletes selected records btn_delete = QtGui.QPushButton('Delete') btn_delete.setToolTip('Delete selected scan/s') btn_delete.resize(btn_delete.sizeHint()) btn_delete.clicked.connect(self._delete_selected_records) hbox = QHBoxLayout() hbox.setSpacing(10) hbox.addWidget(btn_delete) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self._table) vbox.addLayout(hbox) self.setLayout(vbox) def add_record(self, plate, image): """ Add a new scan record to the store and display it. """ self._store.add_record(plate, image) self._load_store_records() def add_record_frame(self, plate, image): """ Add a new scan frame - creates a new record if its a new puck, else merges with previous record""" self._store.merge_record(plate, image) self._load_store_records() if self._options.scan_clipboard.value(): self._barcodeTable.copy_selected_to_clipboard() def _load_store_records(self): """ Populate the record table with all of the records in the store. """ self._table.clearContents() self._table.setRowCount(self._store.size()) for n, record in enumerate(self._store.records): items = [record.date, record.time, record.plate_type, record.num_valid_barcodes, record.num_unread_slots, record.num_empty_slots] if (record.num_valid_barcodes + record.num_empty_slots) == record.num_slots: color = self._options.col_ok() else: color = self._options.col_bad() color.a = 192 for m, item in enumerate(items): new_item = QtGui.QTableWidgetItem(str(item)) new_item.setBackgroundColor(color.to_qt()) new_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._table.setItem(n, m, new_item) # Display the first (most recent) record self._table.setCurrentCell(0, 0) self._record_selected() def _record_selected(self): """ Called when a row is selected, causes details of the selected record to be displayed (list of barcodes in the barcode table and image of the scan in the image frame). """ try: row = self._table.selectionModel().selectedRows()[0].row() record = self._store.get_record(row) self._barcodeTable.populate(record.barcodes) marked_image = record.marked_image(self._options) self._imageFrame.display_puck_image(marked_image) except IndexError: pass self._barcodeTable.populate([]) self._imageFrame.clear_frame() def _delete_selected_records(self): """ Called when the 'Delete' button is pressed. Deletes all of the selected records (and the associated images) from the store and from disk. Asks for user confirmation. """ # Display a confirmation dialog to check that user wants to proceed with deletion quit_msg = "This operation cannot be undone.\nAre you sure you want to delete these record/s?" reply = QtGui.QMessageBox.warning(self, 'Confirm Delete', quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) # If yes, find the appropriate records and delete them if reply == QtGui.QMessageBox.Yes: rows = self._table.selectionModel().selectedRows() records_to_delete = [] for row in rows: index = row.row() record = self._store.get_record(index) records_to_delete.append(record) self._store.delete_records(records_to_delete) self._load_store_records()
class OWxsh_waviness(widget.OWWidget): name = "xsh_waviness" id = "orange.widgets.preprocessor.xsh_waviness" description = "xoppy application to compute..." icon = "icons/waviness.png" author = "Luca Rebuffi" maintainer_email = "[email protected]; [email protected]" priority = 10 category = "" keywords = ["xoppy", "xsh_waviness"] outputs = [{"name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data"}] want_main_area = 1 want_control_area = 1 WIDGET_WIDTH = 1100 WIDGET_HEIGHT = 650 xx = None yy = None zz = None number_of_points_x = Setting(10) number_of_points_y = Setting(100) dimension_x = Setting(20.1) dimension_y = Setting(113.1) estimated_slope_error = Setting(0.9) montecarlo_seed = Setting(2387427) waviness_file_name = Setting('waviness.dat') harmonic_maximum_index = Setting(60) data = Setting({'c': ['0.3', '0.1', '0.1', '0.0', '0.0', '0.0', '0.3', '0.0', '0.0', '0.3', '0.0', '0.0', '0.5', '0.0', '0.0', '0.2', '0.2', '0.2', '0.9', '0.0', '0.0', '0.0', '0.0', '0.0', '0.4', '0.0', '0.0', '0.4', '0.0', '0.0', '0.0', '0.6', '0.6', '0.0', '0.4', '0.4', '0.0', '0.4', '0.4', '0.1', '0.4', '0.4', '0.1', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.3', '0.3', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0'], 'y': ['0.0', '-0.1', '-0.1', '0.0', '0.0', '0.0', '0.03', '0.0', '0.0', '0.2', '0.0', '0.0', '0.2', '0.0', '0.0', '0.1', '0.1', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.0', '0.01', '0.0', '0.0', '0.03', '0.0', '0.0', '0.0', '0.02', '0.02', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.3', '0.3', '0.0', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.0', '0.0', '0.0'], 'g': ['0.0', '0.3', '0.3', '0.0', '0.0', '0.0', '0.05', '0.0', '0.0', '0.05', '0.0', '0.0', '0.1', '0.0', '0.0', '0.05', '0.05', '0.05', '0.2', '0.0', '0.0', '0.0', '0.0', '0.0', '0.1', '0.0', '0.0', '0.1', '0.0', '0.0', '0.0', '0.2', '0.2', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.1', '0.1', '0.0', '0.2', '0.2', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0']}) def __init__(self): super().__init__() geom = QApplication.desktop().availableGeometry() self.setGeometry(QRect(round(geom.width() * 0.05), round(geom.height() * 0.05), round(min(geom.width() * 0.98, self.WIDGET_WIDTH)), round(min(geom.height() * 0.95, self.WIDGET_HEIGHT)))) gen_box = ShadowGui.widgetBox(self.controlArea, "Waviness Parameters", addSpace=True, orientation="horizontal", width=500) tabs_setting = gui.tabWidget(gen_box) tab_input = ShadowGui.createTabPage(tabs_setting, "Input Parameter") tab_harmonics = ShadowGui.createTabPage(tabs_setting, "Harmonics") tab_out = ShadowGui.createTabPage(tabs_setting, "Output") self.input_box = ShadowGui.widgetBox(tab_input, "Inputs", addSpace=True, orientation="vertical", width=470) gui.button(self.input_box, self, "Load xsh_waviness input file ...", callback=self.load_inp_file) gui.separator(self.input_box) ShadowGui.lineEdit(self.input_box, self, "number_of_points_x", "Number of Points (<201) X (width)", labelWidth=300, valueType=int, orientation="horizontal") ShadowGui.lineEdit(self.input_box, self, "number_of_points_y", " Y (length)", labelWidth=300, valueType=int, orientation="horizontal") gui.separator(self.input_box) ShadowGui.lineEdit(self.input_box, self, "dimension_x", "Dimensions [cm] X (width)", labelWidth=300, valueType=float, orientation="horizontal") ShadowGui.lineEdit(self.input_box, self, "dimension_y", " Y (length)", labelWidth=300, valueType=float, orientation="horizontal") gui.separator(self.input_box) ShadowGui.lineEdit(self.input_box, self, "estimated_slope_error", "Estimated slope error [arcsec]", labelWidth=300, valueType=float, orientation="horizontal") ShadowGui.lineEdit(self.input_box, self, "montecarlo_seed", "Monte Carlo initial seed", labelWidth=300, valueType=int, orientation="horizontal") self.output_box = ShadowGui.widgetBox(tab_input, "Outputs", addSpace=True, orientation="vertical", width=470) self.select_file_box = ShadowGui.widgetBox(self.output_box, "", addSpace=True, orientation="horizontal") gui.separator(self.output_box) gui.button(self.output_box, self, "Write xsh_waviness input file (optional) ...", callback=self.write_inp_file) ShadowGui.lineEdit(self.select_file_box, self, "waviness_file_name", "Output File Name", labelWidth=120, valueType=str, orientation="horizontal") self.harmonics_box = ShadowGui.widgetBox(tab_harmonics, "Harmonics", addSpace=True, orientation="vertical", width=470, height=690) ShadowGui.lineEdit(self.harmonics_box, self, "harmonic_maximum_index", "Harmonic Maximum Index", labelWidth=300, valueType=int, orientation="horizontal", callback=self.set_harmonics) gui.separator(self.harmonics_box) self.scrollarea = QScrollArea() self.scrollarea.setMaximumWidth(400) self.harmonics_box.layout().addWidget(self.scrollarea, alignment=Qt.AlignHCenter) self.shadow_output = QTextEdit() self.shadow_output.setReadOnly(True) out_box = ShadowGui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=600) out_box.layout().addWidget(self.shadow_output) button_box = ShadowGui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Calculate Waviness", callback=self.calculate_waviness) button.setFixedHeight(45) button.setFixedWidth(170) button = gui.button(button_box, self, "Generate Waviness File", callback=self.generate_waviness_file) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(200) button = gui.button(button_box, self, "Reset Fields", callback=self.call_reset_settings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(120) gui.rubber(self.controlArea) self.figure = Figure(figsize=(600, 600)) self.figure.patch.set_facecolor('white') self.axis = self.figure.add_subplot(111, projection='3d') self.axis.set_xlabel("X (cm)") self.axis.set_ylabel("Y (cm)") self.axis.set_zlabel("Z (µm)") self.figure_canvas = FigureCanvasQTAgg(self.figure) self.mainArea.layout().addWidget(self.figure_canvas) gui.rubber(self.mainArea) def restoreWidgetPosition(self): super().restoreWidgetPosition() self.table = QTableWidget(self.harmonic_maximum_index + 1, 3) self.table.setAlternatingRowColors(True) self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed) for i in range(0, 3): self.table.setColumnWidth(i, 70) horHeaders = [] verHeaders = [] for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): table_item = QTableWidgetItem(str(item)) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(m, n, table_item) verHeaders.append(str(m)) self.table.setHorizontalHeaderLabels(horHeaders) self.table.setVerticalHeaderLabels(verHeaders) self.table.resizeRowsToContents() self.table.itemChanged.connect(self.table_item_changed) self.scrollarea.setWidget(self.table) self.scrollarea.setWidgetResizable(1) gui.rubber(self.controlArea) def reload_harmonics_table(self): horHeaders = [] verHeaders = [] self.table.itemChanged.disconnect(self.table_item_changed) self.table.clear() row_count = self.table.rowCount() for n in range(0, row_count): self.table.removeRow(0) for index in range(0, self.harmonic_maximum_index + 1): self.table.insertRow(0) for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): table_item = QTableWidgetItem(str(item)) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(m, n, table_item) verHeaders.append(str(m)) self.table.setHorizontalHeaderLabels(horHeaders) self.table.setVerticalHeaderLabels(verHeaders) self.table.resizeRowsToContents() for i in range(0, 3): self.table.setColumnWidth(i, 70) self.table.itemChanged.connect(self.table_item_changed) def table_item_changed(self): dict = {} message = "" error_row_index = -1 error_column_index = -1 previous_value = "" try: row_count = self.harmonic_maximum_index + 1 for column_index in range(0, self.table.columnCount()): column_name = self.table.horizontalHeaderItem(column_index).data(0) row_content = [] for row_index in range(0, row_count): if not self.table.item(row_index, column_index) is None: message = "Value at row " + str( row_index) + " and column \'" + column_name + "\' is not numeric" error_row_index = row_index error_column_index = column_index previous_value = self.data[column_name][row_index] value = float(self.table.item(row_index, column_index).data(0)) # to raise exception row_content.append(str(value)) dict[column_name] = row_content self.data = dict except ValueError: QMessageBox.critical(self, "QMessageBox.critical()", message + "\nValue is reset to previous value", QMessageBox.Ok) table_item = QTableWidgetItem(previous_value) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(error_row_index, error_column_index, table_item) self.table.setCurrentCell(error_row_index, error_column_index) except Exception as exception: QMessageBox.critical(self, "QMessageBox.critical()", exception.args[0], QMessageBox.Ok) def set_harmonics(self): if self.harmonic_maximum_index < 0: QMessageBox.critical(self, "QMessageBox.critical()", "Harmonic Maximum Index should be a positive integer number", QMessageBox.Ok) else: row_count = len(self.data["c"]) if self.harmonic_maximum_index + 1 > row_count: for n, key in enumerate(sorted(self.data.keys())): for m in range(row_count, self.harmonic_maximum_index + 1): self.data[key].append('0.0') else: for n, key in enumerate(sorted(self.data.keys())): self.data[key] = copy.deepcopy(self.data[key][0: self.harmonic_maximum_index + 1]) self.reload_harmonics_table() def load_inp_file(self): file_name = QFileDialog.getOpenFileName(self, "Select a input file for XSH_WAVINESS", ".", "*.inp") if not file_name is None: sys.stdout = EmittingStream(textWritten=self.writeStdOut) if not file_name.strip() == "": dict = ST.waviness_read(file=file_name) self.number_of_points_x = dict["npointx"] self.number_of_points_y = dict["npointy"] self.dimension_y = dict["xlength"] self.dimension_x = dict["width"] self.estimated_slope_error = dict["slp"] self.montecarlo_seed = dict["iseed"] self.waviness_file_name = dict["file"].strip('\n\r').strip() self.harmonic_maximum_index = dict["nharmonics"] self.data["c"] = self.to_str_array(dict["c"]) self.data["y"] = self.to_str_array(dict["y"]) self.data["g"] = self.to_str_array(dict["g"]) self.reload_harmonics_table() def write_inp_file(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() file_name = self.waviness_file_name.strip().split(sep=".dat")[0] + ".inp" dict = {} dict["npointx"] = self.number_of_points_x dict["npointy"] = self.number_of_points_y dict["xlength"] = self.dimension_y dict["width"] = self.dimension_x dict["slp"] = self.estimated_slope_error dict["iseed"] = self.montecarlo_seed dict["file"] = self.waviness_file_name.strip('\n\r') dict["nharmonics"] = self.harmonic_maximum_index dict["c"] = self.to_float_array(self.data["c"]) dict["y"] = self.to_float_array(self.data["y"]) dict["g"] = self.to_float_array(self.data["g"]) ST.waviness_write(dict, file=file_name) QMessageBox.information(self, "QMessageBox.information()", "File \'" + file_name + "\' written to disk", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "QMessageBox.critical()", exception.args[0], QMessageBox.Ok) def calculate_waviness(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() xx, yy, zz = ST.waviness_calc(npointx=self.number_of_points_x, npointy=self.number_of_points_y, width=self.dimension_x, xlength=self.dimension_y, slp=self.estimated_slope_error, nharmonics=self.harmonic_maximum_index, iseed=self.montecarlo_seed, c=self.to_float_array(self.data["c"]), y=self.to_float_array(self.data["y"]), g=self.to_float_array(self.data["g"])) self.xx = xx self.yy = yy self.zz = zz self.axis.clear() x_to_plot, y_to_plot = numpy.meshgrid(xx, yy) z_to_plot = [] for y_index in range(0, len(yy)): z_array = [] for x_index in range(0, len(xx)): z_array.append(1e4 * float(zz[x_index][y_index])) # to micron z_to_plot.append(z_array) z_to_plot = numpy.array(z_to_plot) self.axis.plot_surface(x_to_plot, y_to_plot, z_to_plot, rstride=1, cstride=1, cmap=cm.autumn, linewidth=0.5, antialiased=True) slope, sloperms = ST.slopes(zz, xx, yy) title = ' Slope error rms in X direction: %f arcsec' % (sloperms[0]) + '\n' + \ ' : %f urad' % (sloperms[2]) + '\n' + \ ' Slope error rms in Y direction: %f arcsec' % (sloperms[1]) + '\n' + \ ' : %f urad' % (sloperms[3]) self.axis.set_xlabel("X (cm)") self.axis.set_ylabel("Y (cm)") self.axis.set_zlabel("Z (µm)") self.axis.set_title(title) self.axis.mouse_init() self.figure_canvas.draw() QMessageBox.information(self, "QMessageBox.information()", "Waviness calculated: if the result is satisfactory,\nclick \'Generate Waviness File\' to complete the operation ", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "QMessageBox.critical()", exception.args[0], QMessageBox.Ok) def generate_waviness_file(self): if not self.zz is None and not self.yy is None and not self.xx is None: if not self.waviness_file_name is None: self.waviness_file_name = self.waviness_file_name.strip() if self.waviness_file_name == "": raise Exception("Output File Name missing") else: raise Exception("Output File Name missing") sys.stdout = EmittingStream(textWritten=self.writeStdOut) ST.write_shadow_surface(self.zz.T, self.xx, self.yy, outFile=self.waviness_file_name) QMessageBox.information(self, "QMessageBox.information()", "Waviness file " + self.waviness_file_name + " written on disk", QMessageBox.Ok) self.send("PreProcessor_Data", ShadowPreProcessorData(waviness_data_file=self.waviness_file_name)) def call_reset_settings(self): if ConfirmDialog.confirmed(parent=self, message="Confirm Reset of the Fields?"): try: self.resetSettings() self.reload_harmonics_table() except: pass def check_fields(self): self.number_of_points_x = ShadowGui.checkStrictlyPositiveNumber(self.number_of_points_x, "Number of Points X") self.number_of_points_y = ShadowGui.checkStrictlyPositiveNumber(self.number_of_points_y, "Number of Points Y") self.dimension_x = ShadowGui.checkStrictlyPositiveNumber(self.dimension_x, "Dimension X") self.dimension_y = ShadowGui.checkStrictlyPositiveNumber(self.dimension_y, "Dimension Y") self.estimated_slope_error = ShadowGui.checkPositiveNumber(self.estimated_slope_error, "Estimated slope error") self.montecarlo_seed = ShadowGui.checkPositiveNumber(self.montecarlo_seed, "Monte Carlo initial seed") self.harmonic_maximum_index = ShadowGui.checkPositiveNumber(self.harmonic_maximum_index, "Harmonic Maximum Index") if not self.waviness_file_name is None: self.waviness_file_name = self.waviness_file_name.strip() if self.waviness_file_name == "": raise Exception("Output File Name missing") else: raise Exception("Output File Name missing") def to_float_array(self, string_array): float_array = [] for index in range(len(string_array)): float_array.append(float(string_array[index])) return float_array def to_str_array(self, float_array): string_array = [] for index in range(len(float_array)): string_array.append(str(float_array[index])) return string_array def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible()
class ScanRecordTable(QGroupBox): """ GUI component. Displays a list of previous scan results. Selecting a scan causes details of the scan to appear in other GUI components (list of barcodes in the barcode table and image of the puck in the image frame). """ COLUMNS = [ 'Date', 'Time', 'Plate Barcode', 'Plate Type', 'Valid', 'Invalid', 'Empty' ] def __init__(self, barcode_table, image_frame, options, to_run_on_table_clicked): super(ScanRecordTable, self).__init__() # Read the store from file self._store = Store(options.store_directory.value(), options.store_capacity, FileManager()) self._options = options self._barcodeTable = barcode_table self._imageFrame = image_frame self.setTitle("Scan Records") self._init_ui(to_run_on_table_clicked) self._load_store_records() def _init_ui(self, to_run_on_table_clicked): # Create record table - lists all the records in the store self._table = QTableWidget() self._table.setFixedWidth(440) self._table.setFixedHeight(600) self._table.setColumnCount(len(self.COLUMNS)) self._table.setHorizontalHeaderLabels(self.COLUMNS) self._table.setColumnWidth(0, 70) self._table.setColumnWidth(1, 55) self._table.setColumnWidth(2, 85) self._table.setColumnWidth(3, 70) self._table.setColumnWidth(4, 45) self._table.setColumnWidth(5, 50) self._table.setColumnWidth(6, 45) self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self._table.cellPressed.connect(to_run_on_table_clicked) self._table.cellPressed.connect(self._record_selected) # Delete button - deletes selected records btn_delete = QtGui.QPushButton('Delete') btn_delete.setToolTip('Delete selected scan/s') btn_delete.resize(btn_delete.sizeHint()) btn_delete.clicked.connect(self._delete_selected_records) hbox = QHBoxLayout() hbox.setSpacing(10) hbox.addWidget(btn_delete) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self._table) vbox.addLayout(hbox) self.setLayout(vbox) def add_record_frame(self, holder_barcode, plate, holder_img, pins_img): """ Add a new scan frame - creates a new record if its a new puck, else merges with previous record""" self._store.merge_record(holder_barcode, plate, holder_img, pins_img) self._load_store_records() if self._options.scan_clipboard.value(): self._barcodeTable.copy_to_clipboard() def _load_store_records(self): """ Populate the record table with all of the records in the store. """ self._table.clearContents() self._table.setRowCount(self._store.size()) for n, record in enumerate(self._store.records): items = [ record.date, record.time, record.holder_barcode, record.plate_type, record.num_valid_barcodes, record.num_unread_slots, record.num_empty_slots ] if (record.num_valid_barcodes + record.num_empty_slots) == record.num_slots: color = self._options.col_ok() else: color = self._options.col_bad() color.a = 192 for m, item in enumerate(items): new_item = QtGui.QTableWidgetItem(str(item)) new_item.setBackgroundColor(color.to_qt()) new_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._table.setItem(n, m, new_item) # Display the first (most recent) record self._table.setCurrentCell(0, 0) self._record_selected() def _record_selected(self): """ Called when a row is selected, causes details of the selected record to be displayed (list of barcodes in the barcode table and image of the scan in the image frame). """ try: row = self._table.selectionModel().selectedRows()[0].row() record = self._store.get_record(row) self._barcodeTable.populate(record.holder_barcode, record.barcodes) marked_image = record.marked_image(self._options) self._imageFrame.display_puck_image(marked_image) except IndexError: self._barcodeTable.clear() self._imageFrame.clear_frame( "Record table empty\nNothing to display") def _delete_selected_records(self): """ Called when the 'Delete' button is pressed. Deletes all of the selected records (and the associated images) from the store and from disk. Asks for user confirmation. """ # Display a confirmation dialog to check that user wants to proceed with deletion quit_msg = "This operation cannot be undone.\nAre you sure you want to delete these record/s?" reply = QtGui.QMessageBox.warning(self, 'Confirm Delete', quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) # If yes, find the appropriate records and delete them if reply == QtGui.QMessageBox.Yes: rows = self._table.selectionModel().selectedRows() records_to_delete = [] for row in rows: index = row.row() record = self._store.get_record(index) records_to_delete.append(record) self._store.delete_records(records_to_delete) self._load_store_records() def is_latest_holder_barcode(self, holder_barcode): return self._store.is_latest_holder_barcode(holder_barcode)
class ElemCompDialog(QtGui.QDialog): def __init__(self,mz, mass,xp,parent=None): QtGui.QDialog.__init__(self, parent) settings = QSettings() size = settings.value("MainWindow/Size",QVariant(QSize(1024,650))).toSize() self.resize(size) self.setWindowTitle('Elenmental Composition') self.xp=xp self.mass=mass self.mz=mz print mz self.initControls() # self.initPlots() def initControls(self): self.plot1 = Qwt.QwtPlot(self) self.plot1.setCanvasBackground(Qt.white) self.plot2 = Qwt.QwtPlot(self) self.plot2.setCanvasBackground(Qt.white) self.list = QTreeWidget() self.list.setColumnCount(11) self.list.setColumnWidth(0,80) self.list.setColumnWidth(1,80) self.list.setColumnWidth(2,60) self.list.setColumnWidth(3,60) self.list.setColumnWidth(4,60) self.list.setColumnWidth(5,150) self.list.setColumnWidth(7,30) self.list.setColumnWidth(8,30) self.list.setColumnWidth(9,30) self.list.setColumnWidth(10,30) self.list.setHeaderLabels(['Mass','Calc.Mass','mDa','PPM','DBE','Formula','Fit Conf %','C','H','N','O']) self.list.setSortingEnabled(True) self.table = QTableWidget(1,11) self.table.setColumnWidth(0,80) self.table.setColumnWidth(1,80) self.table.setColumnWidth(2,60) self.table.setColumnWidth(3,60) self.table.setColumnWidth(4,60) self.table.setColumnWidth(5,150) self.table.setColumnWidth(7,30) self.table.setColumnWidth(8,30) self.table.setColumnWidth(9,30) self.table.setColumnWidth(10,30) self.table.setHorizontalHeaderLabels(['Mass','Calc.Mass','mDa','PPM','DBE','Formula','Fit Conf %','C','H','N','O']) self.table.setEditTriggers(QTableWidget.NoEditTriggers) self.table.setSelectionBehavior(QTableWidget.SelectRows) self.table.setSelectionMode(QTableWidget.SingleSelection) self.table.setAlternatingRowColors(True) print self.connect(self.table, SIGNAL("itemActivated(QTableWidgetItem*)"), self.tableClicked) # self.connect(self.library_list, SIGNAL("itemSelectionChanged()"), self.libraryListClicked) up_hbox=QVBoxLayout() up_hbox.addWidget(self.table) down_hbox = QVBoxLayout() down_hbox.addWidget(self.plot1) down_hbox.addWidget(self.plot2) hbox = QVBoxLayout() hbox.addLayout(up_hbox, 3.5) hbox.addLayout(down_hbox, 3.5) self.setLayout(hbox) self.cal_mass() def tableClicked(self,item): self.C=self.table.item(item.row(),7).text() self.H=self.table.item(item.row(),8).text() self.N=self.table.item(item.row(),9).text() self.O=self.table.item(item.row(),10).text() self.cal_isotopic() self.initPlots() def initPlots(self): self.plot1.clear() # self.plot1.setTitle("Observed Isotope Distribution") # self.plot1.setAxisTitle(Qwt.QwtPlot.xBottom, 'Raman shift (cm-1)') # self.plot1.setAxisTitle(Qwt.QwtPlot.yLeft, 'Intensity') # grid = Qwt.QwtPlotGrid() pen = QPen(Qt.DotLine) pen.setColor(Qt.black) pen.setWidth(0) # grid.setPen(pen) # grid.attach(self.plot1) self.mass1=self.mass/self.massy*100 self.plot1.setAxisScale(self.plot1.xBottom,self.x_min,self.x_max) self.plot1.setAxisScale(self.plot1.yLeft,0,1.1*100) color = QColor('black') curve = Qwt.QwtPlotCurve("test1") pen = QPen(color) pen.setWidth(1) curve.setPen(pen) curve.setData(self.mass_x,self.mass_y) curve.setStyle(Qwt.QwtPlotCurve.Sticks) curve.attach(self.plot1) self.plot1.replot() self.plot2.clear() # self.plot2.setTitle("Theoretical Isotope Distribution") # self.plot2.setAxisTitle(Qwt.QwtPlot.xBottom, 'Raman shift (cm-1)') # self.plot2.setAxisTitle(Qwt.QwtPlot.yLeft, 'Intensity') # grid = Qwt.QwtPlotGrid() pen = QPen(Qt.DotLine) pen.setColor(Qt.blue) self.plot2.setAxisScale(self.plot1.xBottom,self.x_min,self.x_max) self.plot2.setAxisScale(self.plot1.yLeft,0,1.1*100) color = QColor('blue') curve = Qwt.QwtPlotCurve("test1") pen = QPen(color) pen.setWidth(1) curve.setPen(pen) # self.axis= np.arange(len(self.mass)) curve.setData(self.x,self.y) curve.setStyle(Qwt.QwtPlotCurve.Sticks) curve.attach(self.plot2) pen.setWidth(0) # grid.setPen(pen) # grid.attach(self.plot2) self.plot2.replot() def cal_mass(self): # charge=0.0 tol = 10.0 # electron=0.000549 measured_mass=np.round(self.xp) limit_lo = measured_mass - (tol/1000.0) limit_hi = measured_mass + (tol/1000.0) mass=[] mass.append((12.000000000,2.0,"C")) #mass.append((78.9183376,-1.0,"Br")) #mass.append((34.96885271,-1.0,"Cl")) #mass.append((31.97207069,0.0,"S")) #mass.append((30.97376151,1.0,"P")) #mass.append((27.9769265327,2.0,"Si")) #mass.append((22.98976967,-1.0,"Na")) #mass.append((18.99840320,-1.0,"F")) mass.append((15.9949146221,0.0,"O")) mass.append((14.0030740052,1.0,"N")) mass.append((1.0078250321,-1.0,"H")) print range(1,10) print mass[0][0] print mass[1][0] print mass[2][0] calc_mass=[] for i in range(1,int(floor(measured_mass/mass[0][0]))+1): for j in range(0,int(floor((measured_mass-mass[0][0]*i)/mass[1][0]))+1): for k in range(0,int(floor((measured_mass-mass[0][0]*i-mass[1][0]*j)/mass[2][0]))+1): # rr=(measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0] # rrr=round((measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0]) # rrrr=int(round((measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0])) # print "rr:%s"%rr+" rrr:%s"%rrr+" rrrr:%s"%rrrr r=int(round((measured_mass-mass[0][0]*i-mass[1][0]*j-mass[2][0]*k)/mass[3][0])) calmass=mass[0][0]*i+mass[1][0]*j+mass[2][0]*k+mass[3][0]*r if (mass[0][1]*i+mass[2][1]*k+mass[3][1]*r)>=-1 and calmass>limit_lo and calmass<limit_hi: calc_mass.append((calmass,i,j,k,r)) print len(calc_mass) for ii in range(0,len(calc_mass)): mda=(measured_mass-calc_mass[ii][0])*1000 ppm=(measured_mass-calc_mass[ii][0])/measured_mass*1000000 DBE=(calc_mass[ii][1]*2+calc_mass[ii][3]-calc_mass[ii][4]+2)/2.0 self.calmass="%.4f"%calc_mass[ii][0] self.mda="%.1f"%mda self.ppm="%.1f"%ppm self.DBE="%.1f"%DBE self.C="%s"%calc_mass[ii][1] self.H="%s"%calc_mass[ii][4] self.N="%s"%calc_mass[ii][3] self.O="%s"%calc_mass[ii][2] self.Formula="C%2s"%self.C+" H%2s"%self.H+" N%2s"%self.N+" O%2s"%self.O mass=str(self.xp) # if not(ii==0): # mass="" self.cal_isotopic() self.initPlots() self.conf="%.1f"%self.mass_diff self.table.insertRow(ii) self.table.setRowHeight(ii,20) self.table.setItem(ii, 0,QTableWidgetItem(mass)) self.table.setItem(ii, 1,QTableWidgetItem(self.calmass)) self.table.setItem(ii, 2,QTableWidgetItem(self.mda)) self.table.setItem(ii, 3,QTableWidgetItem(self.ppm)) self.table.setItem(ii, 4,QTableWidgetItem(self.DBE)) self.table.setItem(ii, 5,QTableWidgetItem(self.Formula)) self.table.setItem(ii, 6,QTableWidgetItem(self.conf)) self.table.setItem(ii, 7,QTableWidgetItem(self.C)) self.table.setItem(ii, 8,QTableWidgetItem(self.H)) self.table.setItem(ii, 9,QTableWidgetItem(self.N)) self.table.setItem(ii, 10,QTableWidgetItem(self.O)) item=QTreeWidgetItem([mass,str(self.calmass),str(self.mda),str(self.ppm),str(self.DBE),self.Formula,str(self.conf),str(self.C),str(self.H),str(self.N),str(self.O)]) self.list.addTopLevelItem(item) self.table.removeRow(len(calc_mass)) self.table.setSortingEnabled(True) # self.table.sortByColumn(1,Qt.DescendingOrder) def next2pow(self): return 2**int(np.ceil(np.log(float(self.xx))/np.log(2.0))) def cal_isotopic(self): MAX_ELEMENTS=5+1 # add 1 due to mass correction 'element' MAX_ISOTOPES=4 # maxiumum # of isotopes for one element CUTOFF=1e-4 # relative intensity cutoff for plotting WINDOW_SIZE = 500 #WINDOW_SIZE=input('Window size (in Da) ---> '); #RESOLUTION=input('Resolution (in Da) ----> '); % mass unit used in vectors RESOLUTION = 1 if RESOLUTION < 0.00001:# % minimal mass step allowed RESOLUTION = 0.00001 elif RESOLUTION > 0.5: # maximal mass step allowed RESOLUTION = 0.5 R=0.00001/RESOLUTION# % R is used to scale nuclide masses (see below) WINDOW_SIZE=WINDOW_SIZE/RESOLUTION; self.xx=WINDOW_SIZE # convert window size to new mass units WINDOW_SIZE=self.next2pow(); # fast radix-2 fast-Fourier transform algorithm if WINDOW_SIZE < np.round(496708*R)+1: WINDOW_SIZE = self.next2pow(np.round(496708*R)+1) # just to make sure window is big enough #H378 C254 N65 O75 S6 M=np.array([int(self.H),int(self.C),int(self.N),int(self.O),0,0]) #% empiric formula, e.g. bovine insulin # isotopic abundances stored in matrix A (one row for each element) A=np.zeros((MAX_ELEMENTS,MAX_ISOTOPES,2)); A[0][0,:] = [100783,0.9998443]# % 1H A[0][1,:] = [201410,0.0001557]# % 2H A[1][0,:] = [100000,0.98889]# % 12C A[1][1,:] = [200336,0.01111]# % 13C A[2][0,:] = [100307,0.99634]# % 14N A[2][1,:] = [200011,0.00366]# % 15N A[3][0,:] = [99492,0.997628]# % 16O A[3][1,:] = [199913,0.000372]# % 17O A[3][2,:] = [299916,0.002000]# % 18O A[4][0,:] = [97207,0.95018]# % 32S A[4][1,:] = [197146,0.00750]# % 33S A[4][2,:] = [296787,0.04215]# % 34S A[4][3,:] = [496708,0.00017]# % 36S A[5][0,:] = [100000,1.00000]# % for shifting mass so that Mmi is # % near left limit of window Mmi=np.array([np.round(100783*R), np.round(100000*R),\ np.round(100307*R),np.round(99492*R), np.round(97207*R), 0])*M# % (Virtual) monoisotopic mass in new units Mmi = Mmi.sum() #% mass shift so Mmi is in left limit of window: FOLDED=np.floor(Mmi/(WINDOW_SIZE-1))+1# % folded FOLDED times (always one folding due to shift below) #% shift distribution to 1 Da from lower window limit: M[MAX_ELEMENTS-1]=np.ceil(((WINDOW_SIZE-1)-np.mod(Mmi,WINDOW_SIZE-1)+np.round(100000*R))*RESOLUTION) MASS_REMOVED=np.array([0,11,13,15,31,-1])*M#% correction for 'virtual' elements and mass shift begin=WINDOW_SIZE*RESOLUTION+MASS_REMOVED.sum() end=2*(WINDOW_SIZE-1)*RESOLUTION+MASS_REMOVED.sum() ptA=np.ones(WINDOW_SIZE); t_fft=0 t_mult=0 for i in xrange(MAX_ELEMENTS): tA=np.zeros(WINDOW_SIZE) for j in xrange(MAX_ISOTOPES): if A[i][j,0] != 0: #removed +1 after R)+1 --we're using python tA[np.round(A[i][j,0]*R)]=A[i][j,1]#; % put isotopic distribution in tA t0 = time.clock() tA=F.fft(tA) # FFT along elements isotopic distribution O(nlogn) t_fft = time.clock()-t0 t0 = time.clock() tA=tA**M[i]# % O(n) ################# ptA = ptA*tA# % O(n)#this is where it is messing UP ################# t1 = time.clock() t_mult=t1-t0 t0=time.clock() ptA=F.ifft(ptA).real#; % O(nlogn) t0=time.clock() MA=np.linspace(begin,end,WINDOW_SIZE-1) ind=np.where(ptA>CUTOFF)[0] self.x = MA[ind] self.y = ptA[ind] self.x_min=int(np.min(self.x)-(np.max(self.x)-np.min(self.x))) self.x_max=int(np.min(self.x)+(np.max(self.x)-np.min(self.x))) self.mass_y=np.ones(len(self.x)) mass_diff=np.ones(len(self.x)) mzInd= np.logical_and((self.mz>=self.x_min),(self.mz<=self.x_max)) self.mass_y=self.mass[mzInd] self.mass_x=self.mz[mzInd] # for i in range(len(self.x)): # self.mass_y[i]=self.mass[int(self.x[i])] self.massy=np.max(self.mass_y) print self.massy self.mass_y=self.mass_y/max(self.mass_y)*100 self.y=self.y/max(self.y)*100 # k=(self.mass_y*self.y).sum()/(self.mass_y*self.mass_y).sum() # self.fit=((k*self.mass_y-self.y)*(k*self.mass_y-self.y)).sum()/(self.y*self.y).sum() for i in range(len(self.y)): mass_diff[i]=np.abs(self.mass_y[i]-self.y[i])/(self.mass_y[i]+self.y[i]) self.mass_diff=(1-mass_diff.sum()/len(mass_diff))*100
class FilesUIManager(QWidget): def __init__(self, winged, pref): QWidget.__init__(self) self.winged = winged self.pref = pref self._vbox = QVBoxLayout(self) self._hbox = QHBoxLayout() self._table = QTableWidget(1, 3) self._table.setHorizontalHeaderLabels(['Access', 'File Name', 'Size']) self._table.setSelectionBehavior(QAbstractItemView.SelectRows) self._table.verticalHeader().hide() self._table.removeRow(0) self._table.setColumnWidth(0, 80) self._table.setColumnWidth(1, 480) self._hbox.addWidget(self._table) self._btnDownload = QPushButton(QIcon(config.images['download']), '') self._btnDownload.setToolTip('Download') self._btnFacebook = QPushButton(QIcon(config.images['facebook']), '') self._btnFacebook.setToolTip('Share on Facebook') self._btnTwitter = QPushButton(QIcon(config.images['twitter']), '') self._btnTwitter.setToolTip('Share on Twitter') self._btnLink = QPushButton(QIcon(config.images['link']), '') self._btnLink.setToolTip('Copy Link') self.connect(self._btnDownload, SIGNAL("clicked()"), self._save) self.connect(self._btnFacebook, SIGNAL("clicked()"), self._facebook) self.connect(self._btnTwitter, SIGNAL("clicked()"), self._twitter) self.connect(self._btnLink, SIGNAL("clicked()"), self._copy_link) def _save(self): file_ = self._files[self._table.currentRow()] if file_['accesibility'] == '2': if self.pref.get('ask', True): folderName = str(QFileDialog.getExistingDirectory(self, 'Save File in...')) else: folderName = self.pref.get('folder', '') if folderName != '': self.winged.save_file(file_, folderName) else: QMessageBox.information(self, 'Download Fail', 'You can only download public files\nwith WingedBox-Client.') def _facebook(self): file_ = self._files[self._table.currentRow()] self.winged.thread.api.facebook(file_) def _twitter(self): file_ = self._files[self._table.currentRow()] self.winged.thread.api.twitter(file_) def _copy_link(self): clipboard = QApplication.clipboard() file = self._files[self._table.currentRow()] clipboard.setText('http://wingedbox.com/downloads/' + file['id'] + "-" + file['file-name']) def find(self, text): items = self._table.findItems(text, Qt.MatchContains) rows = [i.row() for i in items] rowsCount = range(self._table.rowCount()) rowsCount.reverse() for i in rowsCount: if i not in rows: self._table.removeRow(i) def load_table(self, files): self._files = files r = 0 for file in files: self._table.insertRow(r) if len(file['name']) > 0: item = QTableWidgetItem(file['name']) else: item = QTableWidgetItem(file['file-name']) item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled ) self._table.setItem(r, 1, item) item = QTableWidgetItem(str(file['file-size'] / 1024) + ' kb') item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled ) self._table.setItem(r, 2, item) imageFile = config.type.get(file['type'], config.typeBlank) access = config.access[file['accesibility']] item = QTableWidgetItem(QIcon(imageFile), access[3]) item.setBackgroundColor(QColor(access[0], access[1], access[2])) item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled ) self._table.setItem(r, 0, item) r += 1 self._table.resizeRowsToContents() self._table.resizeColumnsToContents() self._table.horizontalHeader().setStretchLastSection(True)
class BarcodeTable(QGroupBox): """ GUI component. Displays a list of barcodes for the currently selected puck. """ def __init__(self, options): super(BarcodeTable, self).__init__() self._barcodes = [] self._options = options self.setTitle("Barcodes") self._init_ui() def _init_ui(self): # Create record table - lists all the records in the store self._table = QTableWidget() # Create barcode table - lists all the barcodes in a record self._table = QtGui.QTableWidget() self._table.setFixedWidth(110) self._table.setFixedHeight(600) self._table.setColumnCount(1) self._table.setRowCount(10) self._table.setHorizontalHeaderLabels(['Barcode']) self._table.setColumnWidth(0, 100) # Clipboard button - copy the selected barcodes to the clipboard self._btn_clipboard = QtGui.QPushButton('Copy To Clipboard') self._btn_clipboard.setToolTip('Copy barcodes for the selected record to the clipboard') self._btn_clipboard.resize(self._btn_clipboard.sizeHint()) self._btn_clipboard.clicked.connect(self.copy_selected_to_clipboard) self._btn_clipboard.setEnabled(False) hbox = QHBoxLayout() hbox.setSpacing(10) hbox.addWidget(self._btn_clipboard) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self._table) vbox.addLayout(hbox) self.setLayout(vbox) def populate(self, barcodes): """ Called when a new row is selected on the record table. Displays all of the barcodes from the selected record in the barcode table. By default, valid barcodes are highlighted green, invalid barcodes are highlighted red, and empty slots are grey. """ num_slots = len(barcodes) self._table.clearContents() self._table.setRowCount(num_slots) for index, barcode in enumerate(barcodes): # Select appropriate background color if barcode == NOT_FOUND_SLOT_SYMBOL: color = self._options.col_bad() elif barcode == EMPTY_SLOT_SYMBOL: color = self._options.col_empty() else: color = self._options.col_ok() color.a = 192 # Set table item barcode = QtGui.QTableWidgetItem(barcode) barcode.setBackgroundColor(color.to_qt()) barcode.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._table.setItem(index, 0, barcode) self._barcodes = barcodes[:] for i, barcode in enumerate(self._barcodes): if barcode in [NOT_FOUND_SLOT_SYMBOL, EMPTY_SLOT_SYMBOL]: self._barcodes[i] = "" self._update_button_state() def _update_button_state(self): if self._barcodes is None or len(self._barcodes) == 0: self._btn_clipboard.setEnabled(False) else: self._btn_clipboard.setEnabled(True) def copy_selected_to_clipboard(self): """ Called when the copy to clipboard button is pressed. Copies the list/s of barcodes for the currently selected records to the clipboard so that the user can paste it elsewhere. """ sep = os.linesep if self._barcodes: pyperclip.copy(sep.join(self._barcodes))
class OWdabam_height_profile(OWWidget): name = "DABAM Height Profile" id = "dabam_height_profile" description = "Calculation of mirror surface error profile" icon = "icons/dabam.png" author = "Luca Rebuffi" maintainer_email = "[email protected]; [email protected]" priority = 6 category = "" keywords = ["dabam_height_profile"] outputs = [{"name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data"}] want_main_area = 1 want_control_area = 1 MAX_WIDTH = 1320 MAX_HEIGHT = 700 IMAGE_WIDTH = 860 IMAGE_HEIGHT = 645 CONTROL_AREA_WIDTH = 405 TABS_AREA_HEIGHT = 618 xx = None yy = None zz = None entry_number = Setting(1) shape=Setting(0) slope_error_from = Setting(0.0) slope_error_to = Setting(1.5) dimension_y_from = Setting(0.0) dimension_y_to = Setting(200.0) use_undetrended = Setting(0) step_x = Setting(1.0) dimension_x = Setting(10.0) center_y = Setting(1) modify_y = Setting(0) new_length = Setting(200.0) filler_value = Setting(0.0) scale_factor_y = Setting(1.0) renormalize_y = Setting(1) error_type_y = Setting(0) rms_y = Setting(0.9) dabam_profile_index = Setting(1) heigth_profile_file_name = Setting('mirror.dat') tab=[] def __init__(self): super().__init__() self.runaction = widget.OWAction("Calculate Height Profile", self) self.runaction.triggered.connect(self.calculate_heigth_profile_ni) self.addAction(self.runaction) self.runaction = widget.OWAction("Generate Height Profile File", self) self.runaction.triggered.connect(self.generate_heigth_profile_file_ni) self.addAction(self.runaction) geom = QApplication.desktop().availableGeometry() self.setGeometry(QRect(round(geom.width() * 0.05), round(geom.height() * 0.05), round(min(geom.width() * 0.98, self.MAX_WIDTH)), round(min(geom.height() * 0.95, self.MAX_HEIGHT)))) self.setMaximumHeight(self.geometry().height()) self.setMaximumWidth(self.geometry().width()) # DABAM INITIALIZATION self.server = dabam.dabam() self.server.set_input_silent(True) gui.separator(self.controlArea) button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Calculate Height\nProfile", callback=self.calculate_heigth_profile) button.setFixedHeight(45) button = gui.button(button_box, self, "Generate Height\nProfile File", callback=self.generate_heigth_profile_file) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(150) button = gui.button(button_box, self, "Reset Fields", callback=self.call_reset_settings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) gui.separator(self.controlArea) tabs_setting = gui.tabWidget(self.controlArea) tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT) tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH-5) tab_input = oasysgui.createTabPage(tabs_setting, "DABAM Search Setting") tab_gener = oasysgui.createTabPage(tabs_setting, "DABAM Generation Setting") tab_out = oasysgui.createTabPage(tabs_setting, "Output") manual_box = oasysgui.widgetBox(tab_input, "Manual Entry", addSpace=True, orientation="vertical") oasysgui.lineEdit(manual_box, self, "entry_number", "Entry Number", labelWidth=300, valueType=int, orientation="horizontal") gui.separator(manual_box) button = gui.button(manual_box, self, "Retrieve Profile", callback=self.retrieve_profile) button.setFixedHeight(35) button.setFixedWidth(self.CONTROL_AREA_WIDTH-35) input_box = oasysgui.widgetBox(tab_input, "Search Parameters", addSpace=True, orientation="vertical") gui.comboBox(input_box, self, "shape", label="Mirror Shape", labelWidth=300, items=["All", "Plane", "Cylindrical", "Elliptical", "Toroidal", "Spherical"], sendSelectedValue=False, orientation="horizontal") gui.separator(input_box) input_box_1 = oasysgui.widgetBox(input_box, "", addSpace=True, orientation="horizontal") oasysgui.lineEdit(input_box_1, self, "slope_error_from", "Slope Error From (" + u"\u03BC" + "rad)", labelWidth=150, valueType=float, orientation="horizontal") oasysgui.lineEdit(input_box_1, self, "slope_error_to", "To (" + u"\u03BC" + "rad)", labelWidth=60, valueType=float, orientation="horizontal") input_box_2 = oasysgui.widgetBox(input_box, "", addSpace=True, orientation="horizontal") self.le_dimension_y_from = oasysgui.lineEdit(input_box_2, self, "dimension_y_from", "Mirror Length From", labelWidth=150, valueType=float, orientation="horizontal") self.le_dimension_y_to = oasysgui.lineEdit(input_box_2, self, "dimension_y_to", "To", labelWidth=60, valueType=float, orientation="horizontal") table_box = oasysgui.widgetBox(tab_input, "Search Results", addSpace=True, orientation="vertical", height=290) self.overlay_search = Overlay(table_box, self.search_profiles) self.overlay_search.hide() button = gui.button(input_box, self, "Search", callback=self.overlay_search.show) button.setFixedHeight(35) button.setFixedWidth(self.CONTROL_AREA_WIDTH-35) gui.comboBox(table_box, self, "use_undetrended", label="Use Undetrended Profile", labelWidth=300, items=["No", "Yes"], callback=self.table_item_clicked, sendSelectedValue=False, orientation="horizontal") gui.separator(table_box) self.scrollarea = QScrollArea() self.scrollarea.setMinimumWidth(self.CONTROL_AREA_WIDTH-35) table_box.layout().addWidget(self.scrollarea, alignment=Qt.AlignHCenter) self.table = QTableWidget(1, 5) self.table.setAlternatingRowColors(True) self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed) self.table.verticalHeader().setVisible(False) self.table.setColumnWidth(0, 40) self.table.setColumnWidth(1, 70) self.table.setColumnWidth(2, 70) self.table.setColumnWidth(3, 85) self.table.setColumnWidth(4, 80) self.table.resizeRowsToContents() self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.itemClicked.connect(self.table_item_clicked) self.scrollarea.setWidget(self.table) self.scrollarea.setWidgetResizable(1) output_profile_box = oasysgui.widgetBox(tab_gener, "Surface Generation Parameters", addSpace=True, orientation="vertical", height=270) self.le_dimension_x = oasysgui.lineEdit(output_profile_box, self, "dimension_x", "Width", labelWidth=300, valueType=float, orientation="horizontal") self.le_step_x = oasysgui.lineEdit(output_profile_box, self, "step_x", "Step Width", labelWidth=300, valueType=float, orientation="horizontal") gui.comboBox(output_profile_box, self, "center_y", label="Center Profile in the middle of O.E.", labelWidth=300, items=["No", "Yes"], sendSelectedValue=False, orientation="horizontal") gui.comboBox(output_profile_box, self, "modify_y", label="Modify Length?", labelWidth=240, items=["No", "Rescale to new length", "Fit to new length (fill or cut)"], callback=self.set_ModifyY, sendSelectedValue=False, orientation="horizontal") self.modify_box_1 = oasysgui.widgetBox(output_profile_box, "", addSpace=False, orientation="vertical", height=50) self.modify_box_2 = oasysgui.widgetBox(output_profile_box, "", addSpace=False, orientation="vertical", height=50) oasysgui.lineEdit(self.modify_box_2, self, "scale_factor_y", "Scale Factor", labelWidth=300, valueType=float, orientation="horizontal") self.modify_box_3 = oasysgui.widgetBox(output_profile_box, "", addSpace=False, orientation="vertical", height=50) self.le_new_length = oasysgui.lineEdit(self.modify_box_3, self, "new_length", "New Length", labelWidth=300, valueType=float, orientation="horizontal") oasysgui.lineEdit(self.modify_box_3, self, "filler_value", "Filler Value (if new length > profile length) [nm]", labelWidth=300, valueType=float, orientation="horizontal") self.set_ModifyY() gui.comboBox(output_profile_box, self, "renormalize_y", label="Renormalize Length Profile to different RMS", labelWidth=300, items=["No", "Yes"], callback=self.set_RenormalizeY, sendSelectedValue=False, orientation="horizontal") self.output_profile_box_1 = oasysgui.widgetBox(output_profile_box, "", addSpace=True, orientation="vertical") gui.comboBox(self.output_profile_box_1, self, "error_type_y", label="Normalization to", labelWidth=270, items=["Figure Error (nm)", "Slope Error (" + u"\u03BC" + "rad)"], sendSelectedValue=False, orientation="horizontal") oasysgui.lineEdit(self.output_profile_box_1, self, "rms_y", "Rms Value", labelWidth=300, valueType=float, orientation="horizontal") self.set_RenormalizeY() output_box = oasysgui.widgetBox(tab_gener, "Outputs", addSpace=True, orientation="vertical") select_file_box = oasysgui.widgetBox(output_box, "", addSpace=True, orientation="horizontal") self.le_heigth_profile_file_name = oasysgui.lineEdit(select_file_box, self, "heigth_profile_file_name", "Output File Name", labelWidth=120, valueType=str, orientation="horizontal") gui.button(select_file_box, self, "...", callback=self.selectFile) self.shadow_output = QTextEdit() self.shadow_output.setReadOnly(True) out_box = oasysgui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=500) out_box.layout().addWidget(self.shadow_output) gui.rubber(self.controlArea) self.initializeTabs() gui.rubber(self.mainArea) self.overlay_search.raise_() def resizeEvent(self, event): self.overlay_search.resize(self.CONTROL_AREA_WIDTH - 15, 290) event.accept() def after_change_workspace_units(self): self.si_to_user_units = 1e2 / self.workspace_units_to_cm self.horHeaders = ["Entry", "Shape", "Length\n[" + self.workspace_units_label + "]", "Heights St.Dev.\n[nm]", "Slopes St.Dev.\n[" + u"\u03BC" + "rad]"] self.table.setHorizontalHeaderLabels(self.horHeaders) self.plot_canvas[0].setGraphXLabel("Y [" + self.workspace_units_label + "]") self.plot_canvas[1].setGraphXLabel("Y [" + self.workspace_units_label + "]") self.axis.set_xlabel("X [" + self.workspace_units_label + "]") self.axis.set_ylabel("Y [" + self.workspace_units_label + "]") label = self.le_dimension_y_from.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_dimension_y_to.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_dimension_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_step_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") def initializeTabs(self): self.tabs = gui.tabWidget(self.mainArea) self.tab = [gui.createTabPage(self.tabs, "Info"), gui.createTabPage(self.tabs, "Heights Profile"), gui.createTabPage(self.tabs, "Slopes Profile"), gui.createTabPage(self.tabs, "PSD Heights"), gui.createTabPage(self.tabs, "CSD Heights"), gui.createTabPage(self.tabs, "ACF"), gui.createTabPage(self.tabs, "Generated 2D Profile"), ] for tab in self.tab: tab.setFixedHeight(self.IMAGE_HEIGHT) tab.setFixedWidth(self.IMAGE_WIDTH) self.plot_canvas = [None, None, None, None, None, None] self.plot_canvas[0] = PlotWindow(roi=False, control=False, position=True, plugins=False) self.plot_canvas[0].setDefaultPlotLines(True) self.plot_canvas[0].setActiveCurveColor(color='darkblue') self.plot_canvas[0].setGraphYLabel("Z [nm]") self.plot_canvas[0].setGraphTitle("Heights Profile") self.plot_canvas[0].setDrawModeEnabled(True, 'rectangle') self.plot_canvas[0].setZoomModeEnabled(True) self.plot_canvas[1] = PlotWindow(roi=False, control=False, position=True, plugins=False) self.plot_canvas[1].setDefaultPlotLines(True) self.plot_canvas[1].setActiveCurveColor(color='darkblue') self.plot_canvas[1].setGraphYLabel("Zp [$\mu$rad]") self.plot_canvas[1].setGraphTitle("Slopes Profile") self.plot_canvas[1].setDrawModeEnabled(True, 'rectangle') self.plot_canvas[1].setZoomModeEnabled(True) self.plot_canvas[2] = PlotWindow(roi=False, control=False, position=True, plugins=False) self.plot_canvas[2].setDefaultPlotLines(True) self.plot_canvas[2].setActiveCurveColor(color='darkblue') self.plot_canvas[2].setGraphXLabel("f [m^-1]") self.plot_canvas[2].setGraphYLabel("PSD [m^3]") self.plot_canvas[2].setGraphTitle("Power Spectral Density of Heights Profile") self.plot_canvas[2].setDrawModeEnabled(True, 'rectangle') self.plot_canvas[2].setZoomModeEnabled(True) self.plot_canvas[2].setXAxisLogarithmic(True) self.plot_canvas[2].setYAxisLogarithmic(True) self.plot_canvas[3] = PlotWindow(roi=False, control=False, position=True, plugins=False) self.plot_canvas[3].setDefaultPlotLines(True) self.plot_canvas[3].setActiveCurveColor(color='darkblue') self.plot_canvas[3].setGraphXLabel("f [m^-1]") self.plot_canvas[3].setGraphYLabel("CSD [m^3]") self.plot_canvas[3].setGraphTitle("Cumulative Spectral Density of Heights Profile") self.plot_canvas[3].setDrawModeEnabled(True, 'rectangle') self.plot_canvas[3].setZoomModeEnabled(True) self.plot_canvas[3].setXAxisLogarithmic(True) self.plot_canvas[4] = PlotWindow(roi=False, control=False, position=True, plugins=False) self.plot_canvas[4].setDefaultPlotLines(True) self.plot_canvas[4].setActiveCurveColor(color='darkblue') self.plot_canvas[4].setGraphXLabel("Length [m]") self.plot_canvas[4].setGraphYLabel("ACF") self.plot_canvas[4].setGraphTitle("Autocovariance Function of Heights Profile") self.plot_canvas[4].setDrawModeEnabled(True, 'rectangle') self.plot_canvas[4].setZoomModeEnabled(True) self.figure = Figure(figsize=(self.IMAGE_HEIGHT, self.IMAGE_HEIGHT)) # QUADRATA! self.figure.patch.set_facecolor('white') self.axis = self.figure.add_subplot(111, projection='3d') self.axis.set_zlabel("Z [nm]") self.plot_canvas[5] = FigureCanvasQTAgg(self.figure) self.profileInfo = QTextEdit() self.profileInfo.setReadOnly(True) self.profileInfo.setMinimumHeight(self.IMAGE_HEIGHT-5) self.profileInfo.setMaximumHeight(self.IMAGE_HEIGHT-5) self.profileInfo.setMinimumWidth(310) self.profileInfo.setMaximumWidth(310) profile_box = oasysgui.widgetBox(self.tab[0], "", addSpace=True, orientation="horizontal", height = self.IMAGE_HEIGHT, width=320) profile_box.layout().addWidget(self.profileInfo) for index in range(0, 6): self.tab[index+1].layout().addWidget(self.plot_canvas[index]) self.tabs.setCurrentIndex(1) def plot_dabam_graph(self, plot_canvas_index, curve_name, x_values, y_values, xtitle, ytitle, color='blue', replace=True): self.plot_canvas[plot_canvas_index].addCurve(x_values, y_values, curve_name, symbol='', color=color, replace=replace) #'+', '^', ',' self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle) self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle) self.plot_canvas[plot_canvas_index].replot() def set_ModifyY(self): self.modify_box_1.setVisible(self.modify_y == 0) self.modify_box_2.setVisible(self.modify_y == 1) self.modify_box_3.setVisible(self.modify_y == 2) def set_RenormalizeY(self): self.output_profile_box_1.setVisible(self.renormalize_y==1) def table_item_clicked(self): if self.table.selectionModel().hasSelection(): if not self.table.rowCount() == 0: if not self.table.item(0, 0) is None: row = self.table.selectionModel().selectedRows()[0].row() self.entry_number = int(self.table.item(row, 0).text()) self.retrieve_profile() def retrieve_profile(self): try: if self.entry_number is None or self.entry_number <= 0: raise Exception("Entry number should be a strictly positive integer number") self.server.load(self.entry_number) self.profileInfo.setText(self.server.info_profiles()) self.plot_canvas[0].setGraphTitle( "Heights Profile. St.Dev.=%.3f nm" % (self.server.stdev_profile_heights() * 1e9)) self.plot_canvas[1].setGraphTitle( "Slopes Profile. St.Dev.=%.3f $\mu$rad" % (self.server.stdev_profile_slopes() * 1e6)) if self.use_undetrended == 0: self.plot_dabam_graph(0, "heights_profile", self.si_to_user_units * self.server.y, 1e9 * self.server.zHeights, "Y [" + self.workspace_units_label + "]", "Z [nm]") self.plot_dabam_graph(1, "slopes_profile", self.si_to_user_units * self.server.y, 1e6 * self.server.zSlopes, "Y [" + self.workspace_units_label + "]", "Zp [$\mu$rad]") else: self.plot_dabam_graph(0, "heights_profile", self.si_to_user_units * self.server.y, 1e9 * self.server.zHeightsUndetrended, "Y [" + self.workspace_units_label + "]", "Z [nm]") self.plot_dabam_graph(1, "slopes_profile", self.si_to_user_units * self.server.y, 1e6 * self.server.zSlopesUndetrended, "Y [" + self.workspace_units_label + "]", "Zp [$\mu$rad]") y = self.server.f ** (self.server.powerlaw["hgt_pendent"]) * 10 ** self.server.powerlaw["hgt_shift"] i0 = self.server.powerlaw["index_from"] i1 = self.server.powerlaw["index_to"] beta = -self.server.powerlaw["hgt_pendent"] self.plot_canvas[2].setGraphTitle( "Power Spectral Density of Heights Profile (beta=%.2f,Df=%.2f)" % (beta, (5 - beta) / 2)) self.plot_dabam_graph(2, "psd_heights_2", self.server.f, self.server.psdHeights, "f [m^-1]", "PSD [m^3]") self.plot_dabam_graph(2, "psd_heights_1", self.server.f, y, "f [m^-1]", "PSD [m^3]", color='green', replace=False) self.plot_dabam_graph(2, "psd_heights_3", self.server.f[i0:i1], y[i0:i1], "f [m^-1]", "PSD [m^3]", color='red', replace=False) self.plot_dabam_graph(3, "csd", self.server.f, self.server.csd_heights(), "f [m^-1]", "CSD [m^3]") c1, c2, c3 = dabam.autocorrelationfunction(self.server.y, self.server.zHeights) self.plot_canvas[4].setGraphTitle( "Autocovariance Function of Heights Profile.\nAutocorrelation Length (ACF=0.5)=%.3f m" % (c3)) self.plot_dabam_graph(4, "acf", c1[0:-1], c2, "Length [m]", "Heights Autocovariance") # surface error removal if not self.zz is None and not self.yy is None and not self.xx is None: self.xx = None self.yy = None self.zz = None self.axis.set_title("") self.axis.clear() self.plot_canvas[5].draw() if (self.tabs.currentIndex()==6): self.tabs.setCurrentIndex(1) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) #raise exception def search_profiles(self): try: self.table.itemClicked.disconnect(self.table_item_clicked) self.table.clear() row_count = self.table.rowCount() for n in range(0, row_count): self.table.removeRow(0) self.table.setHorizontalHeaderLabels(self.horHeaders) profiles = dabam.dabam_summary_dictionary(surface=self.get_dabam_shape(), slp_err_from=self.slope_error_from*1e-6, slp_err_to=self.slope_error_to*1e-6, length_from=self.dimension_y_from / self.si_to_user_units, length_to=self.dimension_y_to / self.si_to_user_units) for index in range(0, len(profiles)): self.table.insertRow(0) for index in range(0, len(profiles)): table_item = QTableWidgetItem(str(profiles[index]["entry"])) table_item.setTextAlignment(Qt.AlignCenter) self.table.setItem(index, 0, table_item) table_item = QTableWidgetItem(str(profiles[index]["surface"])) table_item.setTextAlignment(Qt.AlignLeft) self.table.setItem(index, 1, table_item) table_item = QTableWidgetItem(str(numpy.round(profiles[index]["length"]*self.si_to_user_units, 3))) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(index, 2, table_item) table_item = QTableWidgetItem(str(numpy.round(profiles[index]["hgt_err"]*1e9, 3))) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(index, 3, table_item) table_item = QTableWidgetItem(str(numpy.round(profiles[index]["slp_err"]*1e6, 3))) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(index, 4, table_item) self.table.setHorizontalHeaderLabels(self.horHeaders) self.table.resizeRowsToContents() self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.itemClicked.connect(self.table_item_clicked) self.overlay_search.hide() except Exception as exception: self.overlay_search.hide() QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) def get_dabam_shape(self): if self.shape == 0: return None elif self.shape == 1: return "plane" elif self.shape == 2: return "cylindrical" elif self.shape == 3: return "elliptical" elif self.shape == 4: return "toroidal" elif self.shape == 5: return "spherical" def calculate_heigth_profile_ni(self): self.calculate_heigth_profile(not_interactive_mode=True) def calculate_heigth_profile(self, not_interactive_mode=False): try: if self.server.y is None: raise Exception("No Profile Selected") sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() combination = "EF" if self.modify_y == 2: profile_1D_y_x_temp = self.si_to_user_units * self.server.y if self.use_undetrended == 0: profile_1D_y_y_temp = self.si_to_user_units * self.server.zHeights else: profile_1D_y_y_temp = self.si_to_user_units * self.server.zHeightsUndetrended first_coord = profile_1D_y_x_temp[0] second_coord = profile_1D_y_x_temp[1] last_coord = profile_1D_y_x_temp[-1] step = numpy.abs(second_coord - first_coord) length = numpy.abs(last_coord - first_coord) n_points_old = len(profile_1D_y_x_temp) if self.new_length > length: difference = self.new_length - length n_added_points = int(difference/step) if difference % step == 0: n_added_points += 1 if n_added_points % 2 != 0: n_added_points += 1 profile_1D_y_x = numpy.arange(n_added_points + n_points_old) * step profile_1D_y_y = numpy.ones(n_added_points + n_points_old) * self.filler_value * 1e-9 * self.si_to_user_units profile_1D_y_y[int(n_added_points/2) : n_points_old + int(n_added_points/2)] = profile_1D_y_y_temp elif self.new_length < length: difference = length - self.new_length n_removed_points = int(difference/step) if difference % step == 0: n_removed_points -= 1 if n_removed_points % 2 != 0: n_removed_points -= 1 if n_removed_points >= 2: profile_1D_y_x = profile_1D_y_x_temp[0 : (n_points_old - n_removed_points)] profile_1D_y_y = profile_1D_y_y_temp[(int(n_removed_points/2) - 1) : (n_points_old - int(n_removed_points/2) - 1)] else: profile_1D_y_x = profile_1D_y_x_temp profile_1D_y_y = profile_1D_y_y_temp else: profile_1D_y_x = profile_1D_y_x_temp profile_1D_y_y = profile_1D_y_y_temp else: if self.modify_y == 0: profile_1D_y_x = self.si_to_user_units * self.server.y elif self.modify_y == 1: profile_1D_y_x = self.si_to_user_units * self.server.y * self.scale_factor_y if self.use_undetrended == 0: profile_1D_y_y = self.si_to_user_units * self.server.zHeights else: profile_1D_y_y = self.si_to_user_units * self.server.zHeightsUndetrended if self.center_y: first_coord = profile_1D_y_x[0] last_coord = profile_1D_y_x[-1] length = numpy.abs(last_coord - first_coord) profile_1D_y_x_temp = numpy.linspace(-length/2, length/2, len(profile_1D_y_x)) profile_1D_y_x = profile_1D_y_x_temp if self.renormalize_y == 0: rms_y = None else: if self.error_type_y == profiles_simulation.FIGURE_ERROR: rms_y = self.si_to_user_units * self.rms_y * 1e-9 # from nm to user units else: rms_y = self.rms_y * 1e-6 # from urad to rad xx, yy, zz = profiles_simulation.simulate_profile_2D(combination = combination, error_type_l = self.error_type_y, rms_l = rms_y, x_l = profile_1D_y_x, y_l = profile_1D_y_y, mirror_width = self.dimension_x, step_w = self.step_x, rms_w = 0.0) self.xx = xx self.yy = yy self.zz = zz # in user units self.axis.clear() x_to_plot, y_to_plot = numpy.meshgrid(xx, yy) z_to_plot = zz * 1e9 / self.si_to_user_units #nm self.axis.plot_surface(x_to_plot, y_to_plot, z_to_plot, rstride=1, cstride=1, cmap=cm.autumn, linewidth=0.5, antialiased=True) sloperms = profiles_simulation.slopes(zz.T, xx, yy, return_only_rms=1) title = ' Slope error rms in X direction: %f $\mu$rad' % (sloperms[0]*1e6) + '\n' + \ ' Slope error rms in Y direction: %f $\mu$rad' % (sloperms[1]*1e6) self.axis.set_xlabel("X [" + self.workspace_units_label + "]") self.axis.set_ylabel("Y [" + self.workspace_units_label + "]") self.axis.set_zlabel("Z [nm]") self.axis.set_title(title) self.axis.mouse_init() if not not_interactive_mode: try: self.plot_canvas[5].draw() except: pass self.tabs.setCurrentIndex(6) QMessageBox.information(self, "QMessageBox.information()", "Height Profile calculated: if the result is satisfactory,\nclick \'Generate Height Profile File\' to complete the operation ", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) #raise exception def generate_heigth_profile_file_ni(self): self.generate_heigth_profile_file(not_interactive_mode=True) def generate_heigth_profile_file(self, not_interactive_mode=False): if not self.zz is None and not self.yy is None and not self.xx is None: try: congruence.checkDir(self.heigth_profile_file_name) sys.stdout = EmittingStream(textWritten=self.writeStdOut) ST.write_shadow_surface(self.zz, self.xx, self.yy, outFile=congruence.checkFileName(self.heigth_profile_file_name)) if not not_interactive_mode: QMessageBox.information(self, "QMessageBox.information()", "Height Profile file " + self.heigth_profile_file_name + " written on disk", QMessageBox.Ok) if self.modify_y == 0: dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0]) if self.modify_y == 1: dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0]) * self.scale_factor_y elif self.modify_y == 2: dimension_y = self.new_length self.send("PreProcessor_Data", ShadowPreProcessorData(error_profile_data_file=self.heigth_profile_file_name, error_profile_x_dim=self.dimension_x, error_profile_y_dim=dimension_y)) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) def call_reset_settings(self): if ConfirmDialog.confirmed(parent=self, message="Confirm Reset of the Fields?"): try: self.resetSettings() except: pass def check_fields(self): self.dimension_x = congruence.checkStrictlyPositiveNumber(self.dimension_x, "Dimension X") self.step_x = congruence.checkStrictlyPositiveNumber(self.step_x, "Step X") if self.step_x > self.dimension_x/2: raise Exception("Step Width should be smaller than or equal to Width/2") if self.modify_y == 1: self.scale_factor_y = congruence.checkStrictlyPositiveNumber(self.scale_factor_y, "Scale Factor") elif self.modify_y == 2: self.new_length = congruence.checkStrictlyPositiveNumber(self.new_length, "New Length") if self.renormalize_y == 1: self.rms_y = congruence.checkPositiveNumber(self.rms_y, "Rms Y") congruence.checkDir(self.heigth_profile_file_name) def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible() def selectFile(self): self.le_heigth_profile_file_name.setText(oasysgui.selectFileFromDialog(self, self.heigth_profile_file_name, "Select Output File", file_extension_filter="Data Files (*.dat)"))
class DataItemWidget(QWidget): __EXTRA_COLUMN_WIDTH = 20 def __init__(self, me_cls, data): QWidget.__init__(self) self.__me_cls = me_cls self.__setup_ui() self.__data = data self.__init_data() self.__connect_slot() def __setup_ui(self): v_layout = QVBoxLayout() self.__tool_widget = ToolWidget() self.__tool_widget.setMaximumHeight(40) self.__data_table_widget = QTableWidget() self.__data_table_widget.horizontalHeader().setStretchLastSection(True) self.__data_table_widget.horizontalHeader().setResizeMode( 0, QHeaderView.Fixed) v_layout.setSpacing(0) v_layout.setContentsMargins(0, 0, 0, 0) v_layout.addWidget(self.__tool_widget, 0) v_layout.addWidget(self.__data_table_widget, 1) self.setLayout(v_layout) def __connect_slot(self): pass #self.connect(self.__tool_widget,SIGNAL('refresh_btn_clicked()'), self ,SLOT('__on_refresh_signal()')) def __init_data(self): self.__data_table_widget.clearContents() # init header #self.__colume_names = yt_connection.get_table_colume_names(self.__table_name) self.__colume_names = [x.field.name for x in self.__me_cls.attributes] #self.__colume_names.insert(0,'entity_id') #print self.__colume_names self.__data_table_widget.setColumnCount(len(self.__colume_names)) head_list = QStringList() for colume in self.__colume_names: head_list << colume self.__data_table_widget.setHorizontalHeaderLabels(head_list) # default the header column both sides are coverd, these codes add __EXTRA_COLUMN_WIDTH to the header column width # and reise column width in function self.__adjust_table_colume() self.__data_table_widget.horizontalHeader().setResizeMode( QHeaderView.ResizeToContents) self.__record_colume_header_width() self.__data_table_widget.horizontalHeader().setResizeMode( QHeaderView.Interactive) self.__record_colume_header_width() show_data = [] for entity_id, value in self.__data.items(): item = value.obj_data.copy() item['managed_entity_id'] = entity_id show_data.append(item) self.__update_table(show_data) # init data # data = yt_connection.get_table_data(self.__table_name) # # self.__update_table(data) self.__adjust_table_colume() def __record_colume_header_width(self): count = self.__data_table_widget.columnCount() self.__column_widths = [] for i in range(count): self.__column_widths.append( self.__data_table_widget.columnWidth(i) + self.__EXTRA_COLUMN_WIDTH) ''' data like this [ {u'direction': 'to-lport', u'name': '[]', u'priority': '100', u'log': 'true', u'action': 'drop', u'external_ids': '{"neutron:lport"="5fb77332-2035-4f72-8e57-7415b02489c9"}', u'match': '"outport==\\"inside-vm2\\""', u'severity': '[]', 'uuid': '2890a832-1c83-4b8e-8b40-2928817012cc'} ] ''' def __update_table(self, data): self.__data_table_widget.clearContents() row_num = 0 for row in data: self.__data_table_widget.insertRow(row_num) colume_num = 0 for colume in self.__colume_names: if row.has_key(colume): item_str = str(row[colume]) else: item_str = 'None' table_wid_item = QTableWidgetItem(item_str) table_wid_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.__data_table_widget.setItem(row_num, colume_num, table_wid_item) colume_num += 1 row_num += 1 def __clear_table_data(self): row_count = self.__data_table_widget.rowCount() rev = [i for i in range(row_count)] rev.reverse() for i in rev: self.__data_table_widget.removeRow(i) def __adjust_table_colume(self): self.__data_table_widget.resizeColumnsToContents() count = self.__data_table_widget.columnCount() for i in range(count): col_wid = self.__data_table_widget.columnWidth(i) if col_wid < self.__column_widths[i]: self.__data_table_widget.setColumnWidth( i, self.__column_widths[i])