class ParametersTable(QWidget): def __init__(self, parent=None, name="parameter_table"): QWidget.__init__(self, parent, name) self.__dc_parameters = None self.add_dc_cb = None self.parameters_label = QLabel(self, "parameters_label") self.parameter_table = QTable(self, "parameter_table") self.parameter_table.setNumCols(3) self.parameter_table.horizontalHeader().\ setLabel(0, self.__tr("Name"), -1) self.parameter_table.horizontalHeader().\ setLabel(1, self.__tr("Value")) self.parameter_table.verticalHeader().hide() self.parameter_table.horizontalHeader().setClickEnabled(False, 0) self.parameter_table.horizontalHeader().setClickEnabled(False, 1) self.parameter_table.setColumnWidth(0, 200) self.parameter_table.setColumnWidth(1, 200) self.parameter_table.hideColumn(2) self.parameter_table.setColumnReadOnly(0, True) self.parameter_table.setLeftMargin(0) self.parameter_table.setNumRows(0) self.position_label = QLabel("Positions", self, "position_view") self.position_label.setAlignment(Qt.AlignTop) ## self.add_button = QPushButton(self, "add_button") #self.add_button.setDisabled(True) h_layout = QGridLayout(self, 1, 2) v_layout_position = QVBoxLayout(self) v_layout_position.addWidget(self.position_label) v_layout_table = QVBoxLayout(self) h_layout.addLayout(v_layout_table, 0, 0) h_layout.addLayout(v_layout_position, 0, 1) v_layout_table.addWidget(self.parameters_label) v_layout_table.addWidget(self.parameter_table) ## v_layout_table.addWidget(self.add_button) ## self.languageChange() ## QObject.connect(self.add_button, SIGNAL("clicked()"), ## self.__add_data_collection) QObject.connect(self.parameter_table, SIGNAL("valueChanged(int, int)"), self.__parameter_value_change) #self.populate_parameter_table(self.__dc_parameters) ## def languageChange(self): ## self.add_button.setText("Add") def __tr(self, s, c=None): return qApp.translate("parameter_table", s, c) def __add_data_collection(self): return self.add_dc_cb(self.__dc_parameters, self.collection_type) def populate_parameter_table(self, parameters): self.parameter_table.setNumRows(11) i = 0 for param_key, parameter in parameters.items(): if param_key != 'positions': self.parameter_table.setText(i, 0, parameter[0]) self.parameter_table.setText(i, 1, parameter[1]) self.parameter_table.setText(i, 2, param_key) i += 1 ## def add_positions(self, positions): ## self.__dc_parameters['positions'].extend(positions) def __parameter_value_change(self, row, col): self.__dc_parameters[str(self.parameter_table.item(row, 2).text())][1] = \ str(self.parameter_table.item(row, 1).text())
class BrowserBrick(BaseComponents.BlissWidget): def __init__(self, *args): BaseComponents.BlissWidget.__init__(self, *args) #map displayed string in the history list -> actual file path self.history_map = dict() self.layout = QVBoxLayout(self) self.defineSlot('load_file', ()) self.defineSlot('login_changed', ()) self.addProperty('mnemonic', 'string', '') self.addProperty('history', 'string', '', hidden=True) self.addProperty('sessions ttl (in days)', 'integer', '30') #make sure the history property is a pickled dict try: hist = pickle.loads(self.getProperty('history').getValue()) except: # EOFError if the string is empty but let's not count on it self.getProperty('history').setValue(pickle.dumps(dict())) # maybe defer that for later self.cleanup_history() self.main_layout = QSplitter(self) self.main_layout.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)) # left part of the splitter self.history_box = QVBox(self.main_layout) self.history_box.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.sort_order = True self.sort_col = None self.history = QTable(self.history_box) self.history.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)) self.history.setSelectionMode(QTable.SingleRow) self.history.setNumCols(3) self.history.verticalHeader().hide() self.history.setLeftMargin(0) self.history.setSorting(False) QObject.connect(self.history, SIGNAL('currentChanged(int,int)'), self.history_changed) #by default sorting only sorts the columns and not whole rows. #let's reimplement that QObject.connect(self.history.horizontalHeader(), SIGNAL('clicked(int)'), self.sort_column) header = self.history.horizontalHeader() header.setLabel(0, 'Time and date') header.setLabel(1, 'Prefix') header.setLabel(2, 'Run number') self.clear_history_button = QPushButton('Clear history', self.history_box) self.history_box.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) QObject.connect(self.clear_history_button, SIGNAL('clicked()'), self.clear_history) # Right part of the splitter self.browser_box = QWidget(self.main_layout) QVBoxLayout(self.browser_box) self.browser_box.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.top_layout = QHBoxLayout(self.browser_box) self.back_button = QToolButton(self.browser_box) self.back_button.setIconSet(QIconSet(Icons.load('Left2'))) self.back_button.setTextLabel('Back') self.back_button.setUsesTextLabel(True) self.back_button.setTextPosition(QToolButton.BelowIcon) self.back_button.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)) self.forward_button = QToolButton(self.browser_box) self.forward_button.setIconSet(QIconSet(Icons.load('Right2'))) self.forward_button.setTextLabel('Forward') self.forward_button.setUsesTextLabel(True) self.forward_button.setTextPosition(QToolButton.BelowIcon) self.forward_button.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)) self.top_layout.addWidget(self.back_button) self.top_layout.addWidget(self.forward_button) self.browser_box.layout().addLayout(self.top_layout) self.browser = QTextBrowser(self.browser_box) self.browser.setReadOnly(True) self.browser_box.layout().addWidget(self.browser) self.layout.addWidget(self.main_layout) #initially disabled self.forward_button.setEnabled(False) self.back_button.setEnabled(False) #connections QObject.connect(self.browser, SIGNAL('backwardAvailable(bool)'), self.back_button.setEnabled) QObject.connect(self.browser, SIGNAL('forwardAvailable(bool)'), self.forward_button.setEnabled) QObject.connect(self.back_button, SIGNAL('clicked()'), self.browser.backward) QObject.connect(self.forward_button, SIGNAL('clicked()'), self.browser.forward) self.edna = None # resize the splitter to something like 1/4-3/4 # width = self.main_layout.width() # left = width / 4.0 # right = width - left # logging.debug('setting splitter sizes to %d and %d', left, right) # self.main_layout.setSizes([left, right]) def sort_column(self, col_number): logging.debug('%s: sorting with column %d', self, col_number) if col_number == self.sort_column: # switch the sort order self.sort_order = self.sort_order ^ True else: self.sort_order = True #else, ascending self.sort_column = col_number self.history.sortColumn(col_number, self.sort_order, True) # put the right decoration on the header label if self.sort_order: direction = Qt.Ascending else: direction = Qt.Descending self.history.horizontalHeader().setSortIndicator(col_number, direction) def load_file(self, path): if self.browser.mimeSourceFactory().data(path) == None: self.browser.setText('<center>FILE NOT FOUND</center>') else: self.browser.setSource(abspath(path)) def history_changed(self, row, col): logging.debug('history elem selected: %d:%d', row, col) index = (str(self.history.text(row,0)), str(self.history.text(row,1)), str(self.history.text(row,2))) try: path = self.history_map[index] self.load_file(path) except KeyError as e: # can happen when qt sends us the signal with # null data and we get the key ("","","") pass def new_html(self, html_path, image_prefix, run_number): logging.getLogger().debug('got a new html page: %s, prefix: %r, run number: %s', html_path, image_prefix, run_number) # prepend the time and date to the path we just got so # the history is more readable time_string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) index = (time_string, str(image_prefix), str(run_number)) self.history_map[index] = html_path # synchronize the history prop if self.current_user is not None: whole_history = pickle.loads(self.getProperty('history').getValue()) whole_history[self.current_user] = self.history_map self.getProperty('history').setValue(pickle.dumps(whole_history)) self.history.insertRows(self.history.numRows()) logging.debug('numRows() is %d', self.history.numRows()) rows = self.history.numRows() - 1 self.history.setText(rows, 0, QString(time_string)) self.history.setText(rows, 1, QString(str(image_prefix))) self.history.setText(rows, 2, QString(str(run_number))) logging.debug('numRows() is %d', self.history.numRows()) self.load_file(html_path) def clear_history(self): self.history_map.clear() self.history.setNumRows(0) def propertyChanged(self, prop, oldval, newval): if prop == 'mnemonic': logging.getLogger().debug('BrowserBrick: using edna object %s', newval) if self.edna is not None: self.disconnect(self.edna, PYSIGNAL('newEDNAHTML'), self.new_html) self.edna = self.getHardwareObject(newval) logging.getLogger().debug('edna object is now: %s', self.edna) self.connect(self.edna, PYSIGNAL('newEDNAHTML'), self.new_html) def run(self): pass def login_changed(self, session_id,prop_code=None,prop_number=None,prop_id=None,expiration_time=0): logging.debug('BrowserBrick::login_changed: login changed to %r', session_id) if session_id is None: # user logged out logging.debug('user logged out') self.current_user = None else: self.current_user = (prop_code, prop_number) logging.debug('current user is now %r', self.current_user) self.clear_all() self.fill_history_for(self.current_user) def clear_all(self): self.clear_history() self.browser.setText('') def fill_history_for(self, user): if user is None: return logging.debug('loading history for user %s', user) whole_history = pickle.loads(self.getProperty('history').getValue()) try: self.history_map = whole_history[user] except KeyError: #user has no history yet self.history_map = dict() for k,v in self.history_map.items(): self.history.insertRows(self.history.numRows()) logging.debug('numRows() is %d', self.history.numRows()) rows = self.history.numRows() - 1 self.history.setText(rows, 0, k[0]) self.history.setText(rows, 1, k[1]) self.history.setText(rows, 2, k[2]) def cleanup_history(self): histories = pickle.loads(self.getProperty('history').getValue()) sessions_ttl = self.getProperty('sessions ttl (in days)').getValue() limit_date = datetime.now() - timedelta(sessions_ttl) #we're mutating the dict so do not use iteritems() just to be sure for user in list(histories.keys()): history = histories[user] #get the keys where the date is more recent than the limit date valid_keys = [x for x in list(history.keys()) if datetime.strptime(x[0], '%Y-%m-%d %H:%M:%S') > limit_date] #NB: old format was "%a, %d %b %Y %H:%M:%S" if len(valid_keys) != len(history): # some entries are too old, copy only the ones that are recent enough new_hist = dict((k,history[k]) for k in valid_keys) logging.debug('BrowserBrick: removed %d entries from saved history for user %s', len(history) - len(valid_keys), user) histories[user] = new_hist self.getProperty('history').setValue(pickle.dumps(histories))
class ParametersTable(QWidget): def __init__(self, parent = None, name = "parameter_table"): QWidget.__init__(self, parent, name) self.__dc_parameters = None self.add_dc_cb = None self.parameters_label = QLabel(self, "parameters_label") self.parameter_table = QTable(self, "parameter_table") self.parameter_table.setNumCols(3) self.parameter_table.horizontalHeader().\ setLabel(0, self.__tr("Name"), -1) self.parameter_table.horizontalHeader().\ setLabel(1, self.__tr("Value")) self.parameter_table.verticalHeader().hide() self.parameter_table.horizontalHeader().setClickEnabled(False, 0); self.parameter_table.horizontalHeader().setClickEnabled(False, 1); self.parameter_table.setColumnWidth(0, 200) self.parameter_table.setColumnWidth(1, 200) self.parameter_table.hideColumn(2) self.parameter_table.setColumnReadOnly(0, True) self.parameter_table.setLeftMargin(0) self.parameter_table.setNumRows(0) self.position_label = QLabel("Positions", self, "position_view") self.position_label.setAlignment(Qt.AlignTop) ## self.add_button = QPushButton(self, "add_button") #self.add_button.setDisabled(True) h_layout = QGridLayout(self, 1, 2) v_layout_position = QVBoxLayout(self) v_layout_position.addWidget(self.position_label) v_layout_table = QVBoxLayout(self) h_layout.addLayout(v_layout_table, 0, 0) h_layout.addLayout(v_layout_position, 0, 1) v_layout_table.addWidget(self.parameters_label) v_layout_table.addWidget(self.parameter_table) ## v_layout_table.addWidget(self.add_button) ## self.languageChange() ## QObject.connect(self.add_button, SIGNAL("clicked()"), ## self.__add_data_collection) QObject.connect(self.parameter_table, SIGNAL("valueChanged(int, int)"), self.__parameter_value_change) #self.populate_parameter_table(self.__dc_parameters) ## def languageChange(self): ## self.add_button.setText("Add") def __tr(self, s, c = None): return qApp.translate("parameter_table", s, c) def __add_data_collection(self): return self.add_dc_cb(self.__dc_parameters, self.collection_type) def populate_parameter_table(self, parameters): self.parameter_table.setNumRows(11) i = 0 for param_key, parameter in parameters.items(): if param_key != 'positions': self.parameter_table.setText(i, 0, parameter[0]) self.parameter_table.setText(i, 1, parameter[1]) self.parameter_table.setText(i, 2, param_key) i += 1 ## def add_positions(self, positions): ## self.__dc_parameters['positions'].extend(positions) def __parameter_value_change(self, row, col): self.__dc_parameters[str(self.parameter_table.item(row, 2).text())][1] = \ str(self.parameter_table.item(row, 1).text())
class BrowserBrick(BaseComponents.BlissWidget): def __init__(self, *args): BaseComponents.BlissWidget.__init__(self, *args) #map displayed string in the history list -> actual file path self.history_map = dict() self.layout = QVBoxLayout(self) self.defineSlot('load_file', ()) self.defineSlot('login_changed', ()) self.addProperty('mnemonic', 'string', '') self.addProperty('history', 'string', '', hidden=True) self.addProperty('sessions ttl (in days)', 'integer', '30') #make sure the history property is a pickled dict try: hist = pickle.loads(self.getProperty('history').getValue()) except: # EOFError if the string is empty but let's not count on it self.getProperty('history').setValue(pickle.dumps(dict())) # maybe defer that for later self.cleanup_history() self.main_layout = QSplitter(self) self.main_layout.setSizePolicy( QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)) # left part of the splitter self.history_box = QVBox(self.main_layout) self.history_box.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.sort_order = True self.sort_col = None self.history = QTable(self.history_box) self.history.setSizePolicy( QSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)) self.history.setSelectionMode(QTable.SingleRow) self.history.setNumCols(3) self.history.verticalHeader().hide() self.history.setLeftMargin(0) self.history.setSorting(False) QObject.connect(self.history, SIGNAL('currentChanged(int,int)'), self.history_changed) #by default sorting only sorts the columns and not whole rows. #let's reimplement that QObject.connect(self.history.horizontalHeader(), SIGNAL('clicked(int)'), self.sort_column) header = self.history.horizontalHeader() header.setLabel(0, 'Time and date') header.setLabel(1, 'Prefix') header.setLabel(2, 'Run number') self.clear_history_button = QPushButton('Clear history', self.history_box) self.history_box.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) QObject.connect(self.clear_history_button, SIGNAL('clicked()'), self.clear_history) # Right part of the splitter self.browser_box = QWidget(self.main_layout) QVBoxLayout(self.browser_box) self.browser_box.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.top_layout = QHBoxLayout(self.browser_box) self.back_button = QToolButton(self.browser_box) self.back_button.setIconSet(QIconSet(Icons.load('Left2'))) self.back_button.setTextLabel('Back') self.back_button.setUsesTextLabel(True) self.back_button.setTextPosition(QToolButton.BelowIcon) self.back_button.setSizePolicy( QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)) self.forward_button = QToolButton(self.browser_box) self.forward_button.setIconSet(QIconSet(Icons.load('Right2'))) self.forward_button.setTextLabel('Forward') self.forward_button.setUsesTextLabel(True) self.forward_button.setTextPosition(QToolButton.BelowIcon) self.forward_button.setSizePolicy( QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)) self.top_layout.addWidget(self.back_button) self.top_layout.addWidget(self.forward_button) self.browser_box.layout().addLayout(self.top_layout) self.browser = QTextBrowser(self.browser_box) self.browser.setReadOnly(True) self.browser_box.layout().addWidget(self.browser) self.layout.addWidget(self.main_layout) #initially disabled self.forward_button.setEnabled(False) self.back_button.setEnabled(False) #connections QObject.connect(self.browser, SIGNAL('backwardAvailable(bool)'), self.back_button.setEnabled) QObject.connect(self.browser, SIGNAL('forwardAvailable(bool)'), self.forward_button.setEnabled) QObject.connect(self.back_button, SIGNAL('clicked()'), self.browser.backward) QObject.connect(self.forward_button, SIGNAL('clicked()'), self.browser.forward) self.edna = None # resize the splitter to something like 1/4-3/4 # width = self.main_layout.width() # left = width / 4.0 # right = width - left # logging.debug('setting splitter sizes to %d and %d', left, right) # self.main_layout.setSizes([left, right]) def sort_column(self, col_number): logging.debug('%s: sorting with column %d', self, col_number) if col_number == self.sort_column: # switch the sort order self.sort_order = self.sort_order ^ True else: self.sort_order = True #else, ascending self.sort_column = col_number self.history.sortColumn(col_number, self.sort_order, True) # put the right decoration on the header label if self.sort_order: direction = Qt.Ascending else: direction = Qt.Descending self.history.horizontalHeader().setSortIndicator(col_number, direction) def load_file(self, path): if self.browser.mimeSourceFactory().data(path) == None: self.browser.setText('<center>FILE NOT FOUND</center>') else: self.browser.setSource(abspath(path)) def history_changed(self, row, col): logging.debug('history elem selected: %d:%d', row, col) index = (str(self.history.text(row, 0)), str(self.history.text(row, 1)), str(self.history.text(row, 2))) try: path = self.history_map[index] self.load_file(path) except KeyError as e: # can happen when qt sends us the signal with # null data and we get the key ("","","") pass def new_html(self, html_path, image_prefix, run_number): logging.getLogger().debug( 'got a new html page: %s, prefix: %r, run number: %s', html_path, image_prefix, run_number) # prepend the time and date to the path we just got so # the history is more readable time_string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) index = (time_string, str(image_prefix), str(run_number)) self.history_map[index] = html_path # synchronize the history prop if self.current_user is not None: whole_history = pickle.loads( self.getProperty('history').getValue()) whole_history[self.current_user] = self.history_map self.getProperty('history').setValue(pickle.dumps(whole_history)) self.history.insertRows(self.history.numRows()) logging.debug('numRows() is %d', self.history.numRows()) rows = self.history.numRows() - 1 self.history.setText(rows, 0, QString(time_string)) self.history.setText(rows, 1, QString(str(image_prefix))) self.history.setText(rows, 2, QString(str(run_number))) logging.debug('numRows() is %d', self.history.numRows()) self.load_file(html_path) def clear_history(self): self.history_map.clear() self.history.setNumRows(0) def propertyChanged(self, prop, oldval, newval): if prop == 'mnemonic': logging.getLogger().debug('BrowserBrick: using edna object %s', newval) if self.edna is not None: self.disconnect(self.edna, PYSIGNAL('newEDNAHTML'), self.new_html) self.edna = self.getHardwareObject(newval) logging.getLogger().debug('edna object is now: %s', self.edna) self.connect(self.edna, PYSIGNAL('newEDNAHTML'), self.new_html) def run(self): pass def login_changed(self, session_id, prop_code=None, prop_number=None, prop_id=None, expiration_time=0): logging.debug('BrowserBrick::login_changed: login changed to %r', session_id) if session_id is None: # user logged out logging.debug('user logged out') self.current_user = None else: self.current_user = (prop_code, prop_number) logging.debug('current user is now %r', self.current_user) self.clear_all() self.fill_history_for(self.current_user) def clear_all(self): self.clear_history() self.browser.setText('') def fill_history_for(self, user): if user is None: return logging.debug('loading history for user %s', user) whole_history = pickle.loads(self.getProperty('history').getValue()) try: self.history_map = whole_history[user] except KeyError: #user has no history yet self.history_map = dict() for k, v in self.history_map.items(): self.history.insertRows(self.history.numRows()) logging.debug('numRows() is %d', self.history.numRows()) rows = self.history.numRows() - 1 self.history.setText(rows, 0, k[0]) self.history.setText(rows, 1, k[1]) self.history.setText(rows, 2, k[2]) def cleanup_history(self): histories = pickle.loads(self.getProperty('history').getValue()) sessions_ttl = self.getProperty('sessions ttl (in days)').getValue() limit_date = datetime.now() - timedelta(sessions_ttl) #we're mutating the dict so do not use iteritems() just to be sure for user in list(histories.keys()): history = histories[user] #get the keys where the date is more recent than the limit date valid_keys = [ x for x in list(history.keys()) if datetime.strptime(x[0], '%Y-%m-%d %H:%M:%S') > limit_date ] #NB: old format was "%a, %d %b %Y %H:%M:%S" if len(valid_keys) != len(history): # some entries are too old, copy only the ones that are recent enough new_hist = dict((k, history[k]) for k in valid_keys) logging.debug( 'BrowserBrick: removed %d entries from saved history for user %s', len(history) - len(valid_keys), user) histories[user] = new_hist self.getProperty('history').setValue(pickle.dumps(histories))
class ChannelWidgetSettingsDialog(QDialog): value_display_widgets = { "LCD": QLCDNumber, "label": QLabel, "combo": QComboBox, "editable": QLineEdit } alignment_flags = { 'vleft': Qt.AlignLeft | Qt.AlignBottom, 'vright': Qt.AlignRight | Qt.AlignBottom, 'vcentre': Qt.AlignHCenter | Qt.AlignBottom, 'hleft': Qt.AlignLeft | Qt.AlignVCenter, 'hright': Qt.AlignRight | Qt.AlignVCenter, 'hcentre': Qt.AlignCenter } def __init__(self, *args): QDialog.__init__(self, *args) self.setCaption("%s - channel properties" % str(self.name())) self.innerbox = QSplitter(Qt.Horizontal, self) grid = QGrid(2, self.innerbox) grid.setSpacing(5) grid.setMargin(5) QLabel("Label", grid) self.txtLabel = QLineEdit(grid) QLabel("Label position", grid) labelpos_group = QVButtonGroup(grid) self.optLabelAbove = QRadioButton("above", labelpos_group) self.optLabelLeft = QRadioButton("on the left", labelpos_group) self.optLabelLeft.setChecked(True) QLabel("Label alignment", grid) labelalign_group = QHButtonGroup(grid) self.optLabelAlignLeft = QRadioButton("left", labelalign_group) self.optLabelAlignCenter = QRadioButton("centre", labelalign_group) self.optLabelAlignRight = QRadioButton("right", labelalign_group) self.optLabelAlignLeft.setChecked(True) QLabel("Value display format", grid) self.txtFormat = QLineEdit(grid) QLabel("Value display style", grid) self.lstChannelStyles = QComboBox(grid) self.lstChannelStyles.insertStrList( ["LCD", "label", "combo", "editable"]) QObject.connect(self.lstChannelStyles, SIGNAL('activated(int)'), self.lstChannelStylesChanged) self.combopanel = QHBox(self.innerbox) self.tblComboChoices = QTable(self.combopanel) self.tblComboChoices.setNumCols(2) self.tblComboChoices.setNumRows(10) for i in range(10): self.tblComboChoices.verticalHeader().setLabel( i, "%2.0f" % (i + 1)) self.tblComboChoices.setText(i, 0, "%2.0f" % (i + 1)) self.tblComboChoices.horizontalHeader().setLabel(0, "value") self.tblComboChoices.horizontalHeader().setLabel(1, "label") self.combopanel.hide() ok_cancel = QHBox(self) self.cmdOk = QPushButton("ok", ok_cancel) HorizontalSpacer(ok_cancel) self.cmdCancel = QPushButton("cancel", ok_cancel) QObject.connect(self.cmdOk, SIGNAL("clicked()"), self.accept) QObject.connect(self.cmdCancel, SIGNAL("clicked()"), self.reject) QVBoxLayout(self, 5, 10) self.layout().addWidget(self.innerbox) self.layout().addWidget(ok_cancel) def _showComboPanel(self, show=True): if show: self.resize(QSize(self.width() * 2, self.height())) self.combopanel.show() self.innerbox.setSizes([self.width() / 2, self.width() / 2]) else: self.resize(QSize(self.width() / 2, self.height())) self.combopanel.hide() def lstChannelStylesChanged(self, idx): if idx == 2: # combo self._showComboPanel() else: self._showComboPanel(False) def channelWidget(self, parent, running=False, config=None): if config is None: config = self.channelConfig() else: self.setChannelConfig(config) w = ControlPanelWidget(parent, config, running=running) if config["label_pos"] == "above": QVBoxLayout(w, 2, 0) alignment_prefix = "v" else: QHBoxLayout(w, 2, 0) alignment_prefix = "h" alignment_flag = ChannelWidgetSettingsDialog.alignment_flags[ alignment_prefix + config["label_align"]] w.layout().addWidget(QLabel(config["label"], w), 0, alignment_flag) w.value = ChannelWidgetSettingsDialog.value_display_widgets[ config["value_display_style"]](w) if "combo" in config: for value, label in config["combo"]: w.value.insertItem(label) w.layout().addWidget(w.value) return w def setChannelConfig(self, config): self.txtLabel.setText(config["label"]) self.optLabelAbove.setChecked(config["label_pos"] == "above") self.optLabelLeft.setChecked(config["label_pos"] == "left") self.optLabelAlignLeft.setChecked(config["label_align"] == "left") self.optLabelAlignRight.setChecked(config["label_align"] == "right") self.optLabelAlignCenter.setChecked(config["label_align"] == "centre") self.lstChannelStyles.setCurrentText(config["value_display_style"]) self.txtFormat.setText(config["value_display_format"]) if "combo" in config: i = 0 for value, label in config["combo"]: self.tblComboChoices.setText(i, 0, value) self.tblComboChoices.setText(i, 1, label) i += 1 self._showComboPanel() def channelConfig(self): config = { "type": "channel", "name": str(self.name()), "label": str(self.txtLabel.text()), "label_pos": self.optLabelAbove.isChecked() and "above" or "left", "value_display_style": str(self.lstChannelStyles.currentText()), "label_align": self.optLabelAlignLeft.isChecked() and "left" or self.optLabelAlignRight.isChecked() and "right" or "centre", "value_display_format": str(self.txtFormat.text()) } if config["value_display_style"] == "combo": combocfg = [] for i in range(10): value = self.tblComboChoices.text(i, 0) label = self.tblComboChoices.text(i, 1) combocfg.append((value, label)) config["combo"] = combocfg return config
class Form1(QMainWindow): def __init__(self,parent = None,name = None,fl = 0): QMainWindow.__init__(self,parent,name,fl) self.statusBar() self.image0 = QPixmap() self.image0.loadFromData(image0_data,"PNG") self.image1 = QPixmap() self.image1.loadFromData(image1_data,"PNG") self.image2 = QPixmap() self.image2.loadFromData(image2_data,"PNG") self.image3 = QPixmap() self.image3.loadFromData(image3_data,"PNG") if not name: self.setName("Form1") self.setCentralWidget(QWidget(self,"qt_central_widget")) self.addButton = QPushButton(self.centralWidget(),"addButton") self.addButton.setGeometry(QRect(620,20,111,31)) self.addButton.setAutoDefault(1) self.replaceButton = QPushButton(self.centralWidget(),"replaceButton") self.replaceButton.setGeometry(QRect(740,20,110,31)) self.replaceButton.setAutoDefault(1) self.deleteButton = QPushButton(self.centralWidget(),"deleteButton") self.deleteButton.setGeometry(QRect(860,20,111,31)) self.deleteButton.setAutoDefault(1) self.pushButton1 = QPushButton(self.centralWidget(),"pushButton1") self.pushButton1.setGeometry(QRect(290,430,121,41)) self.pushButton1.setAutoDefault(1) self.pushButton1_2 = QPushButton(self.centralWidget(),"pushButton1_2") self.pushButton1_2.setGeometry(QRect(420,430,121,41)) self.pushButton1_2.setAutoDefault(1) self.table1 = QTable(self.centralWidget(),"table1") self.table1.setGeometry(QRect(10,70,980,350)) self.table1.setNumRows(100) self.table1.setNumCols(100) self.table1.setReadOnly(1) self.table1.setSelectionMode(QTable.Single) self.lineEdit1 = QLineEdit(self.centralWidget(),"lineEdit1") self.lineEdit1.setGeometry(QRect(10,20,601,31)) self.fileNewAction = QAction(self,"fileNewAction") self.fileNewAction.setIconSet(QIconSet(self.image0)) self.fileOpenAction = QAction(self,"fileOpenAction") self.fileOpenAction.setIconSet(QIconSet(self.image1)) self.fileSaveAction = QAction(self,"fileSaveAction") self.fileSaveAction.setIconSet(QIconSet(self.image2)) self.fileSaveAsAction = QAction(self,"fileSaveAsAction") self.filePrintAction = QAction(self,"filePrintAction") self.filePrintAction.setIconSet(QIconSet(self.image3)) self.fileExitAction = QAction(self,"fileExitAction") self.helpContentsAction = QAction(self,"helpContentsAction") self.helpIndexAction = QAction(self,"helpIndexAction") self.helpAboutAction = QAction(self,"helpAboutAction") self.editSettingsAction = QAction(self,"editSettingsAction") self.menunew_itemAction = QAction(self,"menunew_itemAction") self.toolBar = QToolBar(QString(""),self,Qt.DockTop) self.fileNewAction.addTo(self.toolBar) self.fileOpenAction.addTo(self.toolBar) self.fileSaveAction.addTo(self.toolBar) self.fileSaveAsAction.addTo(self.toolBar) self.MenuBar = QMenuBar(self,"MenuBar") self.fileMenu = QPopupMenu(self) self.fileNewAction.addTo(self.fileMenu) self.fileOpenAction.addTo(self.fileMenu) self.fileSaveAction.addTo(self.fileMenu) self.fileSaveAsAction.addTo(self.fileMenu) self.fileMenu.insertSeparator() self.fileExitAction.addTo(self.fileMenu) self.MenuBar.insertItem(QString(""),self.fileMenu,1) self.Edit = QPopupMenu(self) self.editSettingsAction.addTo(self.Edit) self.MenuBar.insertItem(QString(""),self.Edit,2) self.helpMenu = QPopupMenu(self) self.helpAboutAction.addTo(self.helpMenu) self.MenuBar.insertItem(QString(""),self.helpMenu,3) self.languageChange() self.resize(QSize(1000,556).expandedTo(self.minimumSizeHint())) self.clearWState(Qt.WState_Polished) self.connect(self.fileExitAction,SIGNAL("activated()"),self.close) self.connect(self.pushButton1_2,SIGNAL("clicked()"),self.close) self.connect(self.table1,SIGNAL("pressed(int,int,int,const QPoint&)"),self.table_click) self.connect(self.addButton,SIGNAL("clicked()"),self.add_entry) self.connect(self.replaceButton,SIGNAL("clicked()"),self.replace_entry) self.connect(self.lineEdit1,SIGNAL("returnPressed()"),self.add_entry) self.connect(self.deleteButton,SIGNAL("clicked()"),self.delete_entry) self.connect(self.addButton,SIGNAL("clicked()"),self.lineEdit1.clear) self.connect(self.lineEdit1,SIGNAL("returnPressed()"),self.lineEdit1.clear) self.connect(self.replaceButton,SIGNAL("clicked()"),self.lineEdit1.clear) self.connect(self.deleteButton,SIGNAL("clicked()"),self.lineEdit1.clear) self.connect(self.pushButton1,SIGNAL("clicked()"),self.run_programs) self.connect(self.fileNewAction,SIGNAL("activated()"),self.new_graph) self.connect(self.editSettingsAction,SIGNAL("activated()"),self.display_config) self.connect(self.fileOpenAction,SIGNAL("activated()"),self.open_command) self.connect(self.fileSaveAction,SIGNAL("activated()"),self.save_command) self.connect(self.fileSaveAsAction,SIGNAL("activated()"),self.saveas_command) self.connect(self.helpAboutAction,SIGNAL("activated()"),self.show_about) self.setTabOrder(self.lineEdit1,self.addButton) self.setTabOrder(self.addButton,self.replaceButton) self.setTabOrder(self.replaceButton,self.deleteButton) self.setTabOrder(self.deleteButton,self.pushButton1) self.setTabOrder(self.pushButton1,self.pushButton1_2) self.setTabOrder(self.pushButton1_2,self.table1) def languageChange(self): self.setCaption(self.__tr("QTPlumb")) self.addButton.setText(self.__tr("Add")) self.replaceButton.setText(self.__tr("Replace")) self.deleteButton.setText(self.__tr("Delete")) self.pushButton1.setText(self.__tr("Run Programs")) self.pushButton1_2.setText(self.__tr("Close")) QToolTip.add(self.table1,self.__tr("Click on the spreadsheet to create connections")) QToolTip.add(self.lineEdit1,self.__tr("Enter your programs here")) self.fileNewAction.setText(self.__tr("New")) self.fileNewAction.setMenuText(self.__tr("&New")) self.fileNewAction.setAccel(self.__tr("Ctrl+N")) self.fileOpenAction.setText(self.__tr("Open")) self.fileOpenAction.setMenuText(self.__tr("&Open...")) self.fileOpenAction.setAccel(self.__tr("Ctrl+O")) self.fileSaveAction.setText(self.__tr("Save")) self.fileSaveAction.setMenuText(self.__tr("&Save")) self.fileSaveAction.setAccel(self.__tr("Ctrl+S")) self.fileSaveAsAction.setText(self.__tr("Save As")) self.fileSaveAsAction.setMenuText(self.__tr("Save &As...")) self.fileSaveAsAction.setAccel(QString.null) self.filePrintAction.setText(self.__tr("Print")) self.filePrintAction.setMenuText(self.__tr("&Print...")) self.filePrintAction.setAccel(self.__tr("Ctrl+P")) self.fileExitAction.setText(self.__tr("E&xit")) self.fileExitAction.setMenuText(self.__tr("E&xit")) self.fileExitAction.setAccel(QString.null) self.helpContentsAction.setText(self.__tr("Contents")) self.helpContentsAction.setMenuText(self.__tr("&Contents...")) self.helpContentsAction.setAccel(QString.null) self.helpIndexAction.setText(self.__tr("Index")) self.helpIndexAction.setMenuText(self.__tr("&Index...")) self.helpIndexAction.setAccel(QString.null) self.helpAboutAction.setText(self.__tr("About")) self.helpAboutAction.setMenuText(self.__tr("&About")) self.helpAboutAction.setAccel(QString.null) self.editSettingsAction.setText(self.__tr("Options")) self.editSettingsAction.setMenuText(self.__tr("Options")) self.menunew_itemAction.setText(self.__tr("new item")) self.menunew_itemAction.setMenuText(self.__tr("new item")) self.toolBar.setLabel(self.__tr("Tools")) if self.MenuBar.findItem(1): self.MenuBar.findItem(1).setText(self.__tr("&File")) if self.MenuBar.findItem(2): self.MenuBar.findItem(2).setText(self.__tr("Edit")) if self.MenuBar.findItem(3): self.MenuBar.findItem(3).setText(self.__tr("&Help")) def run_programs(self): import glob from commands import getoutput from thread import start_new_thread if len(glob.glob(getoutput("echo ~") + "/.qtplumb")) > 0: file = open(getoutput("echo ~") + "/.qtplumb", "r") command = file.readline() xterm_loc = file.readline() for i in range(0, 5): if xterm_loc != "\n": break xterm_loc = file.readline() file.close() command = command[0:(len(command) - 1)] command = xterm_loc + " -hold -e " + command else: command = "../testadj " for i in range(0, len(self.programs)): command += " \"%d:" % (i + 1) + self.programs[i] + "\" " command += " -e " for i in range(1, len(self.programs) + 2): for j in range(1, len(self.programs) + 2): if self.table1.text(i, j).ascii() == "X": command += " %d," % (i - 1) + "%d " % (j - 1) def command_runner(x): getoutput(command) start_new_thread(command_runner, (0, )) def table_click(self,row,col,button,point): if (row == 0) or (row > len(self.programs) + 1) or (col > (len(self.programs) + 1)) or ((row == 1) and (col == 0)): self.disable_ed() return if col == 0: self.selectedEntry = [row,col] self.replaceButton.setEnabled(1) self.deleteButton.setEnabled(1) self.lineEdit1.setText(self.table1.text(row,col)) return if self.table1.text(row, col).ascii() != "X": self.table1.setText(row, col, QString("X")) else: self.table1.setText(row, col, QString("")) self.disable_ed() def add_entry(self): s = self.lineEdit1.text().ascii() self.programs.append(s) self.table1.setText(len(self.programs) + 1, 0, s) self.table1.setText(0, len(self.programs) + 1, s) def replace_entry(self): s = self.lineEdit1.text().ascii() self.programs[self.selectedEntry[0] - 1] = s self.table1.setText(self.selectedEntry[0], 0, s) self.table1.setText(0, self.selectedEntry[0], s) def init_two(self): self.programs = [] self.table1.setText(0, 1, QString("Console")) self.table1.setText(1, 0, QString("Console")) self.disable_ed() self.filename = "" def delete_entry(self): self.table1.removeRow(self.selectedEntry[0]) self.table1.removeColumn(self.selectedEntry[0]) self.programs.pop(self.selectedEntry[0] - 2) self.disable_ed() def disable_ed(self): self.selectedEntry = [0,0] self.deleteButton.setEnabled(0) self.replaceButton.setEnabled(0) def new_graph(self): for i in range(0, len(self.programs) + 2): for j in range(0, len(self.programs) + 2): self.table1.clearCell(i, j) self.init_two() def open_command(self): from commands import getoutput if self.filename == "": temp = QFileDialog.getOpenFileName(getoutput("echo ~"), "Commands (*.cmd);;All Files (*.*)", self, "Save as", "Choose a file").ascii() else: temp = QFileDialog.getOpenFileName(self.filename, "Commands (*.cmd);;All Files (*.*)", self, "Save as", "Choose a file").ascii() if temp == None: return self.filename = temp file = open(self.filename, "r") command = file.read() file.close() def add_to_graph(s): self.lineEdit1.setText(s) self.add_entry() tempstring = "" mode = 1 for i in range(0, len(command)): if command[i] == '-' and mode == 1: if command[i + 1] == 'e': i += 2 mode = 2 if command[i] == ":" and mode == 1: i += 1 tempstring = "" while command[i] != '"' and command[i - 1] != '\\': tempstring += command[i] i += 1 add_to_graph(tempstring) if command[i] == ',' and mode == 2: tempstring = "" frm = 0 dest = 0 while command[i] != ' ': i -= 1 i += 1 while command[i] != ',': tempstring += command[i] i += 1 i += 1 frm = int(tempstring) tempstring = "" while command[i] != " " and command[i] != "\n": tempstring += command[i] i += 1 dest = int(tempstring) self.table1.setText(frm + 1, dest + 1, "X") def save_command(self): if self.filename == "": self.saveas_command() return command = "../testadj " for i in range(0, len(self.programs)): command += " \"%d:" % (i + 1) + self.programs[i] + "\" " command += "-e " for i in range(1, len(self.programs) + 1): for j in range(1, len(self.programs) + 2): if self.table1.text(i, j).ascii() == "X": command += " %d," % i + "%d " % (j - 1) file = open(self.filename, "w") file.write(command) file.write("\n") file.close() def saveas_command(self): from commands import getoutput if self.filename == "": temp = QFileDialog.getSaveFileName(getoutput("echo ~"), "Commands (*.cmd);;All Files (*.*)", self, "Save as", "Choose a file").ascii() else: temp = QFileDialog.getSaveFileName(self.filename, "Commands (*.cmd);;All Files (*.*)", self, "Save as", "Choose a file").ascii() if temp != None: self.filename = temp self.save_command() def show_about(self): from aboutbox import aboutBox box = aboutBox(self, "About", 0, 0) box.show() box.exec_loop() def display_config(self): from configbox import configBox box = configBox(self, "QTPlumb Config", 0, 0) box.init_two() box.show() box.exec_loop() def __tr(self,s,c = None): return qApp.translate("Form1",s,c)
class Form2(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) if not name: self.setName("Form2") self.pushButton2 = QPushButton(self,"pushButton2") self.pushButton2.setGeometry(QRect(620,330,141,31)) self.pushButton3 = QPushButton(self,"pushButton3") self.pushButton3.setGeometry(QRect(620,370,141,31)) self.pushButton5 = QPushButton(self,"pushButton5") self.pushButton5.setGeometry(QRect(260,340,111,31)) self.table1 = QTable(self,"table1") self.table1.setGeometry(QRect(30,20,800,310)) self.table1.setLineWidth(1) self.table1.setNumRows(101) self.table1.setNumCols(15) self.textLabel1 = QLabel(self,"textLabel1") self.textLabel1.setGeometry(QRect(140,340,70,31)) self.textLabel1.setPaletteBackgroundColor(QColor(0,255,255)) pal = QPalette() cg = QColorGroup() cg.setColor(QColorGroup.Foreground,Qt.black) cg.setColor(QColorGroup.Button,QColor(192,192,192)) cg.setColor(QColorGroup.Light,Qt.white) cg.setColor(QColorGroup.Midlight,QColor(223,223,223)) cg.setColor(QColorGroup.Dark,QColor(96,96,96)) cg.setColor(QColorGroup.Mid,QColor(128,128,128)) cg.setColor(QColorGroup.Text,Qt.black) cg.setColor(QColorGroup.BrightText,Qt.white) cg.setColor(QColorGroup.ButtonText,Qt.black) cg.setColor(QColorGroup.Base,Qt.white) cg.setColor(QColorGroup.Background,QColor(0,255,255)) cg.setColor(QColorGroup.Shadow,Qt.black) cg.setColor(QColorGroup.Highlight,QColor(0,0,128)) cg.setColor(QColorGroup.HighlightedText,Qt.white) cg.setColor(QColorGroup.Link,Qt.black) cg.setColor(QColorGroup.LinkVisited,Qt.black) pal.setActive(cg) cg.setColor(QColorGroup.Foreground,Qt.black) cg.setColor(QColorGroup.Button,QColor(192,192,192)) cg.setColor(QColorGroup.Light,Qt.white) cg.setColor(QColorGroup.Midlight,QColor(220,220,220)) cg.setColor(QColorGroup.Dark,QColor(96,96,96)) cg.setColor(QColorGroup.Mid,QColor(128,128,128)) cg.setColor(QColorGroup.Text,Qt.black) cg.setColor(QColorGroup.BrightText,Qt.white) cg.setColor(QColorGroup.ButtonText,Qt.black) cg.setColor(QColorGroup.Base,Qt.white) cg.setColor(QColorGroup.Background,QColor(0,255,255)) cg.setColor(QColorGroup.Shadow,Qt.black) cg.setColor(QColorGroup.Highlight,QColor(0,0,128)) cg.setColor(QColorGroup.HighlightedText,Qt.white) cg.setColor(QColorGroup.Link,QColor(0,0,255)) cg.setColor(QColorGroup.LinkVisited,QColor(255,0,255)) pal.setInactive(cg) cg.setColor(QColorGroup.Foreground,QColor(128,128,128)) cg.setColor(QColorGroup.Button,QColor(192,192,192)) cg.setColor(QColorGroup.Light,Qt.white) cg.setColor(QColorGroup.Midlight,QColor(220,220,220)) cg.setColor(QColorGroup.Dark,QColor(96,96,96)) cg.setColor(QColorGroup.Mid,QColor(128,128,128)) cg.setColor(QColorGroup.Text,QColor(128,128,128)) cg.setColor(QColorGroup.BrightText,Qt.white) cg.setColor(QColorGroup.ButtonText,QColor(128,128,128)) cg.setColor(QColorGroup.Base,Qt.white) cg.setColor(QColorGroup.Background,QColor(0,255,255)) cg.setColor(QColorGroup.Shadow,Qt.black) cg.setColor(QColorGroup.Highlight,QColor(0,0,128)) cg.setColor(QColorGroup.HighlightedText,Qt.white) cg.setColor(QColorGroup.Link,QColor(0,0,255)) cg.setColor(QColorGroup.LinkVisited,QColor(255,0,255)) pal.setDisabled(cg) self.textLabel1.setPalette(pal) self.lineEdit2 = QLineEdit(self,"lineEdit2") self.lineEdit2.setGeometry(QRect(40,420,310,21)) self.languageChange() self.resize(QSize(866,656).expandedTo(self.minimumSizeHint())) self.clearWState(Qt.WState_Polished) self.connect(self.pushButton2,SIGNAL("clicked()"),self.addMatrix) self.connect(self.pushButton3,SIGNAL("clicked()"),self.addMem) self.connect(self.pushButton5,SIGNAL("clicked()"),self.percent) self.connect(self.lineEdit2,SIGNAL("returnPressed()"),self.intvec) def languageChange(self): self.setCaption(self.__tr("Form2")) self.pushButton2.setText(self.__tr("Generar BD")) self.pushButton3.setText(self.__tr("Memoria")) self.pushButton5.setText(self.__tr("Porcentaje")) self.textLabel1.setText(QString.null) def addMatrix(self): filas = self.table1.numRows() col = self.table1.numCols() for i in range(0, filas): for j in range(0, col): val = str(dbanimales[i][j]) self.table1.setText(i,j,val) def addMem(self): filas = self.table1.numRows() col = self.table1.numCols() for i in range(0, filas): for j in range(0, col): self.table1.clearCell(i,j) for i in range(0, 7): for j in range(0, 15): v = str(memoria[i][j]) self.table1.setText(i,j,v) def percent(self): suma = cony1 + cony2 + cony3 + cony4 + cony5 + cony6 + cony7 por = str((suma * 100)/101) self.textLabel1.setText(por) def intvec(self): x = self.lineEdit2.text().ascii() x = list(x) x = map(int, x) x = np.array([x]) x = x.transpose() clase = np.dot(memoria,x) aux= clase.max() for i in xrange(0, 7): if clase[i][0] == aux: clase [i][0] = 1 elif clase[i][0] < aux: clase [i][0] = 0 clase = clase.transpose() if np.all(clase == y7) == True: cad = 'Clase 7' self.textLabel1.setText(cad) elif np.all(clase == y6) == True: cad = 'Clase 6' self.textLabel1.setText(cad) elif np.all(clase == y5) == True: cad = 'Clase 5' self.textLabel1.setText(cad) elif np.all(clase == y4) == True: cad = 'Clase 4' self.textLabel1.setText(cad) elif np.all(clase == y3) == True: cad = 'Clase 3' self.textLabel1.setText(cad) elif np.all(clase == y2) == True: cad = 'Clase 2' self.textLabel1.setText(cad) elif np.all(clase == y1) == True: cad = 'Clase 1' self.textLabel1.setText(cad) def __tr(self,s,c = None): return qApp.translate("Form2",s,c)
class Form2(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) if not name: self.setName("Form2") self.lineEdit2 = QLineEdit(self,"lineEdit2") self.lineEdit2.setGeometry(QRect(40,420,310,21)) self.textLabel1 = QLabel(self,"textLabel1") self.textLabel1.setGeometry(QRect(30,340,181,31)) self.textLabel1.setPaletteBackgroundColor(QColor(0,255,255)) pal = QPalette() cg = QColorGroup() cg.setColor(QColorGroup.Foreground,Qt.black) cg.setColor(QColorGroup.Button,QColor(192,192,192)) cg.setColor(QColorGroup.Light,Qt.white) cg.setColor(QColorGroup.Midlight,QColor(223,223,223)) cg.setColor(QColorGroup.Dark,QColor(96,96,96)) cg.setColor(QColorGroup.Mid,QColor(128,128,128)) cg.setColor(QColorGroup.Text,Qt.black) cg.setColor(QColorGroup.BrightText,Qt.white) cg.setColor(QColorGroup.ButtonText,Qt.black) cg.setColor(QColorGroup.Base,Qt.white) cg.setColor(QColorGroup.Background,QColor(0,255,255)) cg.setColor(QColorGroup.Shadow,Qt.black) cg.setColor(QColorGroup.Highlight,QColor(0,0,128)) cg.setColor(QColorGroup.HighlightedText,Qt.white) cg.setColor(QColorGroup.Link,Qt.black) cg.setColor(QColorGroup.LinkVisited,Qt.black) pal.setActive(cg) cg.setColor(QColorGroup.Foreground,Qt.black) cg.setColor(QColorGroup.Button,QColor(192,192,192)) cg.setColor(QColorGroup.Light,Qt.white) cg.setColor(QColorGroup.Midlight,QColor(220,220,220)) cg.setColor(QColorGroup.Dark,QColor(96,96,96)) cg.setColor(QColorGroup.Mid,QColor(128,128,128)) cg.setColor(QColorGroup.Text,Qt.black) cg.setColor(QColorGroup.BrightText,Qt.white) cg.setColor(QColorGroup.ButtonText,Qt.black) cg.setColor(QColorGroup.Base,Qt.white) cg.setColor(QColorGroup.Background,QColor(0,255,255)) cg.setColor(QColorGroup.Shadow,Qt.black) cg.setColor(QColorGroup.Highlight,QColor(0,0,128)) cg.setColor(QColorGroup.HighlightedText,Qt.white) cg.setColor(QColorGroup.Link,QColor(0,0,255)) cg.setColor(QColorGroup.LinkVisited,QColor(255,0,255)) pal.setInactive(cg) cg.setColor(QColorGroup.Foreground,QColor(128,128,128)) cg.setColor(QColorGroup.Button,QColor(192,192,192)) cg.setColor(QColorGroup.Light,Qt.white) cg.setColor(QColorGroup.Midlight,QColor(220,220,220)) cg.setColor(QColorGroup.Dark,QColor(96,96,96)) cg.setColor(QColorGroup.Mid,QColor(128,128,128)) cg.setColor(QColorGroup.Text,QColor(128,128,128)) cg.setColor(QColorGroup.BrightText,Qt.white) cg.setColor(QColorGroup.ButtonText,QColor(128,128,128)) cg.setColor(QColorGroup.Base,Qt.white) cg.setColor(QColorGroup.Background,QColor(0,255,255)) cg.setColor(QColorGroup.Shadow,Qt.black) cg.setColor(QColorGroup.Highlight,QColor(0,0,128)) cg.setColor(QColorGroup.HighlightedText,Qt.white) cg.setColor(QColorGroup.Link,QColor(0,0,255)) cg.setColor(QColorGroup.LinkVisited,QColor(255,0,255)) pal.setDisabled(cg) self.textLabel1.setPalette(pal) self.pushButton2 = QPushButton(self,"pushButton2") self.pushButton2.setGeometry(QRect(620,330,141,31)) self.pushButton3 = QPushButton(self,"pushButton3") self.pushButton3.setGeometry(QRect(620,370,141,31)) self.table1 = QTable(self,"table1") self.table1.setGeometry(QRect(30,20,800,310)) self.table1.setLineWidth(1) self.table1.setNumRows(101) self.table1.setNumCols(15) self.languageChange() self.resize(QSize(866,656).expandedTo(self.minimumSizeHint())) self.clearWState(Qt.WState_Polished) self.connect(self.pushButton2,SIGNAL("clicked()"),self.addMatrix) self.connect(self.pushButton3,SIGNAL("clicked()"),self.addMem) def languageChange(self): self.setCaption(self.__tr("Form2")) self.textLabel1.setText(QString.null) self.pushButton2.setText(self.__tr("Generar BD")) self.pushButton3.setText(self.__tr("Memoria")) def addMatrix(self): filas = self.table1.numRows() col = self.table1.numCols() for i in range(0, filas): for j in range(0, col): val = str(dbanimales[i][j]) self.table1.setText(i,j,val) def addMem(self): filas = self.table1.numRows() col = self.table1.numCols() for i in range(0, filas): for j in range(0, col): self.table1.clearCell(i,j) for i in range(0, 7): for j in range(0, 15): v = str(memoria[i][j]) self.table1.setText(i,j,v) def __tr(self,s,c = None): return qApp.translate("Form2",s,c)
class ChannelWidgetSettingsDialog(QDialog): value_display_widgets = { "LCD": QLCDNumber, "label": QLabel, "combo": QComboBox, "editable": QLineEdit } alignment_flags = { 'vleft': Qt.AlignLeft | Qt.AlignBottom, 'vright': Qt.AlignRight | Qt.AlignBottom, 'vcentre': Qt.AlignHCenter | Qt.AlignBottom, 'hleft': Qt.AlignLeft | Qt.AlignVCenter, 'hright': Qt.AlignRight | Qt.AlignVCenter, 'hcentre': Qt.AlignCenter } def __init__(self, *args): QDialog.__init__(self, *args) self.setCaption("%s - channel properties" % str(self.name())) self.innerbox = QSplitter(Qt.Horizontal, self) grid = QGrid(2, self.innerbox) grid.setSpacing(5) grid.setMargin(5) QLabel("Label", grid) self.txtLabel = QLineEdit(grid) QLabel("Label position", grid) labelpos_group = QVButtonGroup(grid) self.optLabelAbove = QRadioButton("above", labelpos_group) self.optLabelLeft = QRadioButton("on the left", labelpos_group) self.optLabelLeft.setChecked(True) QLabel("Label alignment", grid) labelalign_group = QHButtonGroup(grid) self.optLabelAlignLeft = QRadioButton("left", labelalign_group) self.optLabelAlignCenter = QRadioButton("centre", labelalign_group) self.optLabelAlignRight = QRadioButton("right", labelalign_group) self.optLabelAlignLeft.setChecked(True) QLabel("Value display format", grid) self.txtFormat = QLineEdit(grid) QLabel("Value display style", grid) self.lstChannelStyles = QComboBox(grid) self.lstChannelStyles.insertStrList(["LCD", "label", "combo", "editable"]) QObject.connect(self.lstChannelStyles, SIGNAL('activated(int)'), self.lstChannelStylesChanged) self.combopanel = QHBox(self.innerbox) self.tblComboChoices = QTable(self.combopanel) self.tblComboChoices.setNumCols(2) self.tblComboChoices.setNumRows(10) for i in range(10): self.tblComboChoices.verticalHeader().setLabel(i, "%2.0f" % (i+1)) self.tblComboChoices.setText(i, 0, "%2.0f" % (i+1)) self.tblComboChoices.horizontalHeader().setLabel(0, "value") self.tblComboChoices.horizontalHeader().setLabel(1, "label") self.combopanel.hide() ok_cancel = QHBox(self) self.cmdOk = QPushButton("ok", ok_cancel) HorizontalSpacer(ok_cancel) self.cmdCancel = QPushButton("cancel", ok_cancel) QObject.connect(self.cmdOk, SIGNAL("clicked()"), self.accept) QObject.connect(self.cmdCancel, SIGNAL("clicked()"), self.reject) QVBoxLayout(self, 5, 10) self.layout().addWidget(self.innerbox) self.layout().addWidget(ok_cancel) def _showComboPanel(self, show=True): if show: self.resize(QSize(self.width()*2, self.height())) self.combopanel.show() self.innerbox.setSizes([self.width()/2,self.width()/2]) else: self.resize(QSize(self.width()/2, self.height())) self.combopanel.hide() def lstChannelStylesChanged(self, idx): if idx == 2: # combo self._showComboPanel() else: self._showComboPanel(False) def channelWidget(self, parent, running=False, config=None): if config is None: config = self.channelConfig() else: self.setChannelConfig(config) w = ControlPanelWidget(parent, config, running=running) if config["label_pos"] == "above": QVBoxLayout(w, 2, 0) alignment_prefix = "v" else: QHBoxLayout(w, 2, 0) alignment_prefix = "h" alignment_flag = ChannelWidgetSettingsDialog.alignment_flags[alignment_prefix + config["label_align"]] w.layout().addWidget(QLabel(config["label"], w), 0, alignment_flag) w.value = ChannelWidgetSettingsDialog.value_display_widgets[config["value_display_style"]](w) if "combo" in config: for value, label in config["combo"]: w.value.insertItem(label) w.layout().addWidget(w.value) return w def setChannelConfig(self, config): self.txtLabel.setText(config["label"]) self.optLabelAbove.setChecked(config["label_pos"]=="above") self.optLabelLeft.setChecked(config["label_pos"]=="left") self.optLabelAlignLeft.setChecked(config["label_align"]=="left") self.optLabelAlignRight.setChecked(config["label_align"]=="right") self.optLabelAlignCenter.setChecked(config["label_align"]=="centre") self.lstChannelStyles.setCurrentText(config["value_display_style"]) self.txtFormat.setText(config["value_display_format"]) if "combo" in config: i = 0 for value, label in config["combo"]: self.tblComboChoices.setText(i, 0, value) self.tblComboChoices.setText(i, 1, label) i += 1 self._showComboPanel() def channelConfig(self): config = { "type": "channel", "name": str(self.name()), "label": str(self.txtLabel.text()), "label_pos": self.optLabelAbove.isChecked() and "above" or "left", "value_display_style": str(self.lstChannelStyles.currentText()), "label_align": self.optLabelAlignLeft.isChecked() and "left" or self.optLabelAlignRight.isChecked() and "right" or "centre", "value_display_format": str(self.txtFormat.text()) } if config["value_display_style"] == "combo": combocfg = [] for i in range(10): value = self.tblComboChoices.text(i, 0) label = self.tblComboChoices.text(i, 1) combocfg.append((value, label)) config["combo"] = combocfg return config
class Grid(QTabWidget): """La tabla que manejara los registros y las variables""" #Funciones de inicializacion def __init__(self, padre, interfazdatos, porterodatos): from Driza.datos.conversion import AgenteConversion self.__portero = porterodatos QTabWidget.__init__(self, padre, "Grid") self.setTabPosition(QTabWidget.Bottom) self.tab = QWidget(self, "tab") tabLayout = QVBoxLayout(self.tab, 11, 6, "tabLayout") self.table1 = QTable(self.tab, "table1") tabLayout.addWidget(self.table1) self.insertTab(self.tab, QString.fromLatin1("&Registros")) self.tab_2 = QWidget(self, "tab_2") tabLayout_2 = QVBoxLayout(self.tab_2, 11, 6, "tabLayout_2") self.table2 = QTable(self.tab_2, "table2") tabLayout_2.addWidget(self.table2) self.insertTab(self.tab_2, QString.fromLatin1("&Variables")) from Driza.iuqt3.vprincipal.dcasos import DCasos self.dcasos = DCasos(self.table1, interfazdatos) self.modoetiqueta = False # Variable que guarda si estamos en modo etiqueta o normal self.__nreg = 10 self.__nvar = 10 self.__idu = interfazdatos self.__init_t_reg() self.__init_t_var() self.__conexiones() self.__agenteconversion = AgenteConversion(self.__idu) def __init_t_reg(self): """Inicializa la tabla de datos""" self.table1.setNumCols(16) self.table1.setNumRows(64) for i in range(self.table1.horizontalHeader().count()): self.table1.horizontalHeader().setLabel(i+1, '') def __init_t_var(self): """Inicializa la tabla de variables""" self.table2.setSelectionMode(QTable.MultiRow) self.table2.setNumRows(self.__nvar) self.table2.setNumCols(5) titulos = self.table2.horizontalHeader() titulos.setLabel (0, "Nombre") titulos.setLabel (1, "Tipo") titulos.setLabel (2, "Valor por defecto") titulos.setLabel (3, u"Etiqueta") titulos.setLabel (4, u"Etiquetas de valor") def __conexiones(self): """Conexiones""" self.connect(self.table1, SIGNAL("valueChanged(int, int)"), self.__modificacion_t_reg) self.connect(self.table2, SIGNAL("valueChanged(int, int)"), self.__modificacion_t_var) def myUpdate(self): """Actualizacion de contenido""" LOG.debug("Actualizando contenido del grid") self.__mostrar_t_reg() self.__mostrar_t_var() def showEvent(self, event): """Redefinición del show de la clase base""" self.myUpdate() QTabWidget.showEvent(self, event) def borrar_seleccion(self, borrardatos=False): """Esta funcion borra la seleccion de la tabla. El parametro opcional determina si se ha deborrar tambien los datos""" tablaactual = self.currentPageIndex() if tablaactual == 0: tabla = self.table1 else: tabla = self.table2 if borrardatos: lista = [] for seleccion in range(tabla.numSelections()): for fila in range(tabla.selection(seleccion).topRow(), tabla.selection(seleccion).bottomRow()+1): lista.append(fila) lista.sort() lista.reverse() for fila in lista: if tablaactual == 0: if fila < self.__idu.n_reg(): del self.__idu[fila] else: if fila < self.__idu.n_var(): self.__idu.delVar(fila) for seleccion in range(tabla.numSelections()): tabla.removeSelection(seleccion) def lista_seleccion(self, tabla=0): """Devuelve una lista con los registros que han sido seleccionados""" tabla = self.table1 listasalida = [] if tabla.numSelections(): toprow = tabla.numRows() bottomrow = 0 leftcol = tabla.numCols() rightcol = 0 for seleccion in range(tabla.numSelections()): misel = tabla.selection(seleccion) if misel.topRow() < toprow: toprow = misel.topRow() if misel.bottomRow()> bottomrow: bottomrow = misel.bottomRow() if misel.leftCol()< leftcol: leftcol = misel.leftCol() if misel.rightCol()> rightcol: rightcol = misel.rightCol() LOG.debug("Limites totales de seleccion:("+str(toprow)+","+str(leftcol)+")") LOG.debug("Limites totales de seleccion:("+str(bottomrow)+","+str(rightcol)+")") if bottomrow >= self.__idu.n_reg(): bottomrow = self.__idu.n_reg() - 1 if rightcol >= self.__idu.n_var(): rightcol = self.__idu.n_var() - 1 for fila in range(toprow, bottomrow+1): nuevafila = [] for columna in range(leftcol, rightcol+1): if self.__idu[fila][columna].valido() and tabla.isSelected(fila, columna): nuevafila.append(repr(self.__idu[fila][columna])) else: nuevafila.append(None) LOG.debug("Fila añadida a la seleccion de copiado: "+str(nuevafila)) listasalida.append(nuevafila) return listasalida def insertar_reg(self): """Inserta un registro en la posicion actual""" assert(self.currentPageIndex() == 0) #Estamos en la tabla de registros tabla = self.table1 pos = tabla.currentRow() self.__idu.ins_reg(pos) self.myUpdate() #TODO: Optimizar redibujado def verificar_seleccion_registros(self): """Verifica que la seleccion solamente consta de registros.""" tabla = self.table1 for indiceseleccion in range(tabla.numSelections()): seleccion = tabla.selection(indiceseleccion) if seleccion.leftCol()!=0 or seleccion.rightCol() < self.__idu.n_var()-1: LOG.debug("Seleccionincorrecta:"+str(seleccion.leftCol())+","+str(seleccion.rightCol())) from Driza.excepciones import SeleccionIncorrectaException raise SeleccionIncorrectaException def mostrar_t_reg(self): """Muestra el tab de casos""" self.showPage(self.tab) def mostrar_t_var(self): """Muestra el tab de variables""" self.showPage(self.tab_2) #Metodos privados def __mostrar_t_var(self): """ Representa la variable pos en la tabla de variables. Las propiedades de la variable las lee de los datos. Si no se indica posicion, se entiende que se quiere rellenar toda la tabla """ LOG.debug("Actualizando tabla de variables completa") if self.__nvar > (self.table2.numRows()-self.__idu.n_var()): self.table2.setNumRows(self.__idu.n_var()+self.__nvar) for fila in range(self.__idu.n_var(), self.table2.numRows()): for columna in range(self.table2.numCols()): self.table2.clearCell(fila, columna) for indicevar in range(self.__idu.n_var()): self.__mostrar_var(indicevar) self.__mostrar_titulo_t_reg() def __mostrar_var(self, pos): """Muestra una unica variable (fila) en la tabla segun el listado de variables""" variable = self.__idu.var(pos) self.table2.setText(pos, 0, str(variable.name())) self.table2.setItem(pos, 1, self.__combotableitem()) self.table2.item(pos, 1).setCurrentItem(variable.tipo) self.table2.setText(pos, 3, str(variable.descripcion)) self.table2.setText(pos, 2, str(variable.valorpordefecto)) self.table2.setItem(pos, 4, self.__botontableitem()) def __mostrar_t_reg(self): """ Rellena la tabla de datos con los registros actuales """ if self.__nreg > (self.table1.numRows() - self.__idu.n_reg()): self.table1.setNumRows(self.__idu.n_reg() + self.__nreg) for i in range(self.__idu.n_reg()): self.__mostrar_reg(i) self.__mostrar_titulo_t_reg() for i in range(self.__idu.n_reg(), self.table1.numRows()): for j in range(self.table1.numCols()): self.table1.clearCell(i, j) for i in range(self.table1.numRows()): for j in range(self.__idu.n_var(), self.table1.numCols()): self.table1.clearCell(i, j) self.__mostrar_lateral_t_reg() def __mostrar_reg(self, pos): """Muestra un solo dato""" if self.modoetiqueta: for i in range(self.__idu.n_var()): if hasattr(self.__idu[pos][i], "etiqueta"): self.table1.setText(pos, i, self.__idu[pos][i].etiqueta()) else: self.table1.setText(pos, i, str(self.__idu[pos][i])) else: for i in range(self.__idu.n_var()): self.table1.setText(pos, i, str(self.__idu[pos][i])) def __mostrar_columna_t_reg(self, pos): """Muestra una columna de la tabla de registros""" for i in range(self.__idu.n_reg()): self.table1.setText(i, pos, str(self.__idu[i][pos])) def __mostrar_titulo_t_reg(self, pos=None): """Actualiza los titulos de la tabla de datos segun las variables""" titulos = self.table1.horizontalHeader() if pos: titulos.setLabel(pos, self.__idu.var(pos).name()) else: i = 0 for _ in range(self.__idu.n_var()): self.table1.horizontalHeader().setLabel(i, self.__idu.var(i).name()) i += 1 for _ in range(self.__idu.n_var(), self.table1.horizontalHeader().count()): self.table1.horizontalHeader().setLabel(i, '') i += 1 def __mostrar_lateral_t_reg(self): """Muestra los numeros laterales. Sirve para el filtrado""" lateral = self.table1.verticalHeader() #lista=self.__idu.getCol(self.__gestorfiltro.variable,filtrado=False) for i in range(self.__idu.n_reg()): # if self.__gestorfiltro.variable and not lista[i]: # lateral.setLabel(i,"--"+str(i)) # else: lateral.setLabel(i, str(i+1)) def __combotableitem(self): """Devuelve un nuevo objeto tipo combotableitem con la lista de tipos""" lista = QStringList() from Driza.listas import SL for tipo in SL.nombrevariables: lista.append(tipo) return QComboTableItem(self.table2, lista) def __botontableitem(self): """Devuelve un nuevo objeto tipo combotableitem con la lista de tipos""" return ButtonTableItem(self.table2, self.dcasos) def __modificacion_t_var(self, fila, columna): """Funcion a que conecta con la introduccion de nuevos datos en la tabla de variables""" if columna == 1 and (self.table2.text(fila, columna).latin1() == self.__idu.var(fila).tipo): return # Se ha solicitado un cambio de tipo al propio tipo self.__portero.guardar_estado() if fila >= self.__idu.n_var(): #Es una nueva variable #Variables intermedias (creadas con los valores por defecto) for valorintermedio in range (self.__idu.n_var(), fila): self.__insertar_variable() self.__mostrar_var(valorintermedio) self.__insertar_variable() #Variable modificada variable = self.__idu.var(fila) if columna == 1: # El usuario quiere cambiar el tipo textoencuestion = self.table2.text(fila, columna).latin1() #preguntar el tipo de conversion metododeseado = self.__preguntar_conversion(variable, textoencuestion) if metododeseado: variable, columna = self.__agenteconversion(variable, textoencuestion, metododeseado) #Pareja variable-list self.__idu.establecer_var(fila, variable, columna) self.__mostrar_t_reg() else: #Restos de campos (Texto) from Driza.excepciones import VariableExisteException try: self.__idu.modificar_var(variable, columna, str(self.table2.text(fila, columna).latin1())) except VariableExisteException: QMessageBox.warning(self, u'Atención', u'El nombre de variable ya existe') except NameError: QMessageBox.warning(self, u'Atención', u'Nombre de variable Erróneo') self.__mostrar_var(fila) #En todos los casos, actualizamos el titulo de la tabla de datos self.__mostrar_titulo_t_reg() def __actualizar_reg_interfazdatos(self, row, col, valor): """actualiza un dato en interfazdatos,recogiendo la excepcion en caso de error """ LOG.debug("Actualizando datos de la interfaz:" + str(row) + "," + str(col)) try: self.__idu[row][col] = valor except ValueError: QMessageBox.warning(self, 'Atención', u'El dato no es válido') def __insertar_registro(self): """Inserta un registro genérico, y ademas comprueba que no nos estamos acercando al final de la tabla""" self.__idu.ana_reg() if self.__nreg > (self.table1.numRows() - self.__idu.n_reg()): self.table1.setNumRows(self.table1.numRows() + 1) def __insertar_variable(self): """Inserta una variable genérica, y ademas comprueba que no nos acercamos a ninguno de los limites de las tablas""" self.__idu.ana_var() if self.__nvar > (self.table2.numRows() - self.__idu.n_var()): self.table2.setNumRows(self.table2.numRows() + 1) self.table1.setNumCols(self.table1.numCols() + 1) def __modificacion_t_reg(self, fila, columna): """Actualiza los datos del objeto dato a partir de un cambio en la tabla de datos""" if (fila < self.__idu.n_reg())\ and (columna < self.__idu.n_var())\ and (self.table1.text(fila, columna).latin1() == str(self.__idu[fila][columna])): return #No hay cambio efectivo #FIXME: No detecta reales LOG.debug("Cambiado registro en la tabla") valor = self.table1.text(fila, columna).latin1() self.__portero.guardar_estado() if columna >= self.__idu.n_var(): LOG.debug("Creando nueva variable por demanda en la modificaicon de un registro") #Estamos trabajando sobre una variable inexistente for i in range(self.__idu.n_var(), columna + 1): self.__insertar_variable() self.__mostrar_columna_t_reg(i) self.__mostrar_t_var() #actualizamos la tabla de variables if fila >= self.__idu.n_reg(): #no existen registros intermedios LOG.debug("Creando nuevo registro por demanda en la modificaicon de un registro") for i in range (self.__idu.n_reg(), fila): self.__insertar_registro() self.__mostrar_reg(i) self.__idu.ana_reg() #El último se separa, tenemos que verificar si el usuario ha escrito correctamente self.__actualizar_reg_interfazdatos(fila, columna, valor) self.__mostrar_reg(fila) #Comprobacion de que sobra el numero correcto de celdas if self.__nreg > (self.table1.numRows() - self.__idu.n_reg()): self.table1.setNumRows(self.__idu.n_reg() + self.__nreg) self.parent().parent().parent().mostrar_undo_redo() def __preguntar_conversion(self, variable, objetivo): """Pregunta cual de los metodos disponibles para la conversion desea escoger el usuario""" lista = [] if variable.diccionarioconversion.has_key("Agrupador"): #Conversión a todos los tipos lista += variable.diccionarioconversion["Agrupador"] for tipo in variable.diccionarioconversion.iterkeys(): if tipo == objetivo: lista += variable.diccionarioconversion[tipo] #Elaborar una lista y preguntar al usuario qlista = QStringList() for elemento in lista: qlista.append(elemento) cadena = QInputDialog.getItem("Elige!", u"Elige una función de conversion", qlista, 0, False, self, "Dialogo") #devolver el nombre de la funcion if cadena[1]: return cadena[0].latin1() else: return ""
class Canvasinfo(QWidget): def __init__(self,parent = None,name = None,fl = 0): QWidget.__init__(self,parent,name,fl) if not name: self.setName("Canvasinfo") self.canvaslabels = QTable(self,"canvaslabels") self.canvaslabels.setNumCols(2) self.canvaslabels.horizontalHeader().setLabel(0,"X") self.canvaslabels.horizontalHeader().setLabel(1,"Y") self.canvaslabels.setNumRows(5) for i in range (5): self.canvaslabels.verticalHeader().setLabel(i, QIconSet(QPixmap(sys.path[0]+"/larm_utilities/sprite%d.png" % (i + 1))),QString.null) self.canvaslabels.setGeometry(QRect(0,20,300,128)) self.canvaslabels.setCursor(QCursor(13)) self.canvaslabels.setFocusPolicy(QTable.NoFocus) self.canvaslabels.setFrameShape(QTable.StyledPanel) self.canvaslabels.setResizePolicy(QTable.AutoOne) self.canvaslabels.setReadOnly(1) self.canvaslabels.setSelectionMode(QTable.NoSelection) self.canvaslabels.setFocusStyle(QTable.FollowStyle) self.label = QLabel(self,"label") self.label.setGeometry(QRect(0,0,300,20)) self.label.setPaletteForegroundColor(QColor('gold')) label_font = QFont(self.label.font()) label_font.setFamily("Pigiarniq Heavy") self.label.setFont(label_font) self.label.setAlignment(Qt.AlignCenter) self.canvaslabels.setPaletteBackgroundColor(QColor(50, 50, 50)) self.canvaslabels.setPaletteForegroundColor(QColor('gold')) self.canvaslabels.setColumnWidth(0, 132) self.canvaslabels.setColumnWidth(1, 132) self.canvaslabels.setShowGrid(False) self.clearWState(Qt.WState_Polished) self.connect(self,PYSIGNAL("showMachineLabel"),self.updateLabels) self.connect(self,PYSIGNAL("hideMachineLabel"),self.deleteLabels) def deleteLabels(self): self.label.setText(QString()) for r in range(5): for c in range(2): self.canvaslabels.setText(r, c, QString()) def updateLabels(self,d): #set label[0] as main label self.label.setText(d[0]) #recurse through label[1] and set them for r in range(len(d[1])): for c in range(len(d[1][r])): self.canvaslabels.setText(r, c, QString(d[1][r][c])) def __tr(self,s,c = None): return qApp.translate("Canvasinfo",s,c)