def initUI(self): self.playingId = -1 model = QStandardItemModel() self.setModel(model) #self.selectionModel().selectionChanged.connect(self.selectionChangedCustom) stations = self.radioConfig['stations'].split('|') for station in stations: tags = dict( zip(['NAME', 'FILE'], [st.strip() for st in station.split('!')])) self.addRow( Song('%name%' + self.radioConfig['prefered_informations'], **tags)) # Fill in the header, with capital for the first letter(title()) headers = ['Name', 'Informations'] model.setHeaderData(0, QtCore.Qt.Horizontal, '') for i, h in enumerate(headers): model.setHeaderData(i + 1, QtCore.Qt.Horizontal, h) self.resizeColumnsToContents() self.resizeRowsToContents() self.show()
def __loadRules(self, the_rules, tree_view): model = QStandardItemModel(self) for r in the_rules: item = QStandardItem(r) model.appendRow(item) model.setHeaderData(0, Qt.Horizontal, "Regular Expression") tree_view.setModel(model)
def showParaAndRdnr(self, listItem): paraAndRdnr = self.listToParaAndRdnr.get(listItem.row()) model = QStandardItemModel(self) c = 0 for para, rdnrs in paraAndRdnr.iteritems(): l = self._createListItem(para, rdnrs) model.insertRow(c, l) c += 1 model.setHeaderData(0, Qt.Horizontal, "Paragraph") model.setHeaderData(1, Qt.Horizontal, "Randnummern") self._paraAndRdnr.setModel(model)
def setContent(self, content, blackList = False): model = QStandardItemModel(self) c = 0 for value in self.adjustContent(content): model.insertRow(c, self._createListItem(value)) c += 1 # self._currentCont[blackList] = content model.setHeaderData(0, Qt.Horizontal, "Wort") model.setHeaderData(1, Qt.Horizontal, "Vorkommen") self.setModel(model, blackList)
def _show_mashups(self, mashups): self.switch_btn_apis.hide() self.switch_btn_mashups.hide() self.recommendLabel.hide() row = 0 model = QStandardItemModel(len(mashups), 4) model.setColumnCount(4) for mashup in mashups: model.setData(model.index(row, 0), QVariant(get_mashup_name(mashup))) model.setData(model.index(row, 1), QVariant(mashup['title'])) model.setData(model.index(row, 2), QVariant(mashup['self'])) model.setData(model.index(row, 3), QVariant(mashup['description'])) row += 1 model.setHeaderData(0, Qt.Horizontal, QVariant("Workflow")) model.setHeaderData(1, Qt.Horizontal, QVariant("Short Description")) model.setHeaderData(2, Qt.Horizontal, QVariant("Provider")) model.setHeaderData(3, Qt.Horizontal, QVariant("Detailed Info")) # model.setHeaderData(0, Qt.Horizontal, QVariant("Info")) # model.setHeaderData(1, Qt.Horizontal, QVariant("Title")) # model.setHeaderData(2, Qt.Horizontal, QVariant("self")) # model.setHeaderData(3, Qt.Horizontal, QVariant("Description")) self.table.setModel(model) self.table.resizeColumnsToContents() self.add_btn.show()
def _show_related_mashups(self): self.switch_btn_apis.hide() self.switch_btn_mashups.hide() self.recommendLabel.hide() apis = [] objs = [] for mashup in self.related_mashups: apis.extend(mashup["related_mashups"]) for api in apis: objs.append(api) mashups = self.data_source.mashups_by_api(api) objs.extend(mashups) row = 0 model = QStandardItemModel(len(objs), 4) model.setColumnCount(4) for obj in objs: if obj.get('protocols'): model.setData(model.index(row, 0), QVariant(get_api_name(obj))) model.setData(model.index(row, 1), QVariant(obj['protocols'])) model.setData(model.index(row, 2), QVariant(obj['provider'])) else: model.setData(model.index(row, 3), QVariant(get_mashup_name(obj))) row += 1 model.setHeaderData(0, Qt.Horizontal, QVariant("API")) model.setHeaderData(1, Qt.Horizontal, QVariant("Protocols")) model.setHeaderData(2, Qt.Horizontal, QVariant("Provider")) model.setHeaderData(3, Qt.Horizontal, QVariant("Mashup")) self.table.setModel(model) self.table.resizeColumnsToContents() self.switch_btn_apis.show()
def init_view(self): self.table = QTableView(self) self.table.setMinimumSize(600, 600) manager = core.packagemanager.get_package_manager() package = manager.get_package("edu.cmu.sv.components", "1.0.0") modules = package.descriptors apis = [] self.modules_to_upgrade = [] for module in modules.values(): api = self.data_source.api_by_id(module.name) if ("1.0" != module.version): apis.append(api) self.modules_to_upgrade.append(module) table_model = QStandardItemModel(len(apis), 4) row = 0 for api in apis: table_model.setData(table_model.index(row, 0), QVariant(api['id'])) table_model.setData(table_model.index(row, 1), QVariant(api['category'])) table_model.setData(table_model.index(row, 2), QVariant(api['version'])) table_model.setData(table_model.index(row, 3), QVariant(api['description'])) row += 1 table_model.setHeaderData(0, Qt.Horizontal, QVariant("Link")) table_model.setHeaderData(1, Qt.Horizontal, QVariant("Category")) table_model.setHeaderData(2, Qt.Horizontal, QVariant("Version")) table_model.setHeaderData(3, Qt.Horizontal, QVariant("Description")) self.table.setModel(table_model) btn = QPushButton(self) btn.clicked.connect(self.upgrade_api) btn.setText("Upgrade") btn.move(600, 500)
def initializePage(self): model = QStandardItemModel() # using a document model, we can obtain all the documents to list inside this view... all_docs = DocumentStorage.documents() for doc_filename in all_docs: # find out the last scan date, number of files, etc document = PersistentScanningState(doc_filename) logger.debug("found info: {0}".format(document.info)) creation_date_str = str(document.info.date_created) last_date = str(document.info.date_last_scanned) num_scanned = "{0:,}".format(document.info.files_scanned) num_merged = "{0:,}".format(document.info.files_merged) is_merged = document.info.merge_complete if not is_merged: last_date_str = "" else: last_date_str = last_date doc = os.path.split(doc_filename)[1][:-len('.sqlite')] items = [ QStandardItem(doc), QStandardItem(str(num_scanned)), QStandardItem(creation_date_str), QStandardItem(str(num_merged)), QStandardItem(last_date_str), ] items[1].setData(Qt.AlignRight, Qt.TextAlignmentRole) items[3].setData(Qt.AlignRight, Qt.TextAlignmentRole) model.invisibleRootItem().appendRow(items) self.ui.treeView.setModel(model) header = self.ui.treeView.header() model.setHeaderData(0, Qt.Horizontal, "Name") model.setHeaderData(1, Qt.Horizontal, "# First Scan") model.setHeaderData(2, Qt.Horizontal, "Date Created") model.setHeaderData(3, Qt.Horizontal, "# Second Scan") model.setHeaderData(4, Qt.Horizontal, "Date Scanned") header.setResizeMode(0, QHeaderView.ResizeToContents) header.setResizeMode(1, QHeaderView.ResizeToContents) header.setResizeMode(2, QHeaderView.ResizeToContents) header.setResizeMode(3, QHeaderView.ResizeToContents) header.setResizeMode(4, QHeaderView.ResizeToContents) self.ui.treeView.selectionModel().currentRowChanged.connect( self.__onSelectionChanged)
def initUI(self): self.playingId = -1 model = QStandardItemModel() self.setModel(model) #self.selectionModel().selectionChanged.connect(self.selectionChangedCustom) stations = self.radioConfig['stations'].split('|') for station in stations: tags = dict(zip(['NAME','FILE'], [st.strip() for st in station.split('!')])) self.addRow(Song('%name%'+self.radioConfig['prefered_informations'], **tags)) # Fill in the header, with capital for the first letter(title()) headers = ['Name','Informations'] model.setHeaderData(0,QtCore.Qt.Horizontal,'') for i,h in enumerate(headers): model.setHeaderData(i+1,QtCore.Qt.Horizontal,h) self.resizeColumnsToContents() self.resizeRowsToContents() self.show()
def initializePage(self): model = QStandardItemModel() # using a document model, we can obtain all the documents to list inside this view... all_docs = DocumentStorage.documents() for doc_filename in all_docs: # find out the last scan date, number of files, etc document = PersistentScanningState(doc_filename) logger.debug("found info: {0}".format(document.info)) creation_date_str = str(document.info.date_created) last_date = str(document.info.date_last_scanned) num_scanned = "{0:,}".format(document.info.files_scanned) num_merged = "{0:,}".format(document.info.files_merged) is_merged = document.info.merge_complete if not is_merged: last_date_str = "" else: last_date_str = last_date doc = os.path.split(doc_filename)[1][:-len('.sqlite')] items = [ QStandardItem(doc), QStandardItem(str(num_scanned)), QStandardItem(creation_date_str), QStandardItem(str(num_merged)), QStandardItem(last_date_str), ] items[1].setData(Qt.AlignRight, Qt.TextAlignmentRole) items[3].setData(Qt.AlignRight, Qt.TextAlignmentRole) model.invisibleRootItem().appendRow(items) self.ui.treeView.setModel(model) header = self.ui.treeView.header() model.setHeaderData(0, Qt.Horizontal, "Name") model.setHeaderData(1, Qt.Horizontal, "# First Scan") model.setHeaderData(2, Qt.Horizontal, "Date Created") model.setHeaderData(3, Qt.Horizontal, "# Second Scan") model.setHeaderData(4, Qt.Horizontal, "Date Scanned") header.setResizeMode(0, QHeaderView.ResizeToContents) header.setResizeMode(1, QHeaderView.ResizeToContents) header.setResizeMode(2, QHeaderView.ResizeToContents) header.setResizeMode(3, QHeaderView.ResizeToContents) header.setResizeMode(4, QHeaderView.ResizeToContents) self.ui.treeView.selectionModel().currentRowChanged.connect(self.__onSelectionChanged)
def init_cmd_table(self): model = QStandardItemModel() model.setColumnCount(3) model.setHeaderData(0, Qt.Horizontal, "Command") model.setHeaderData(1, Qt.Horizontal, "Tag") model.setHeaderData(2, Qt.Horizontal, "Description") import json print sys.path[0] os.chdir(sys.path[0]) f = file('command.txt') cmds = json.load(f) f.close() for cmd in cmds: l = [] for field in cmd: if type(field) is types.ListType: f = '\n'.join(field) else: f = field l.append(QStandardItem(f)) model.appendRow(l) self.tableView.setModel(model) self.tableView.resizeRowsToContents() self.model = model
def _show_apis(self, apis, recommend=False): self.switch_btn_apis.hide() self.switch_btn_mashups.hide() self.recommendLabel.hide() row = 0 model = QStandardItemModel(len(apis), 4) model.setColumnCount(4) for api in apis: model.setData(model.index(row, 0), QVariant(get_api_name(api))) model.setData(model.index(row, 1), QVariant(api['protocols'])) model.setData(model.index(row, 2), QVariant(api['provider'])) model.setData(model.index(row, 3), QVariant(api['version'])) row += 1 model.setHeaderData(0, Qt.Horizontal, QVariant("Module")) model.setHeaderData(1, Qt.Horizontal, QVariant("Protocol")) model.setHeaderData(2, Qt.Horizontal, QVariant("Provider")) model.setHeaderData(3, Qt.Horizontal, QVariant("Version")) # model.setHeaderData(0, Qt.Horizontal, QVariant("API")) # model.setHeaderData(1, Qt.Horizontal, QVariant("Protocols")) # model.setHeaderData(2, Qt.Horizontal, QVariant("Provider")) # model.setHeaderData(3, Qt.Horizontal, QVariant("Version")) self.table.setModel(model) self.table.resizeColumnsToContents() if recommend: self.recommendLabel.show() self.add_btn.show()
def initUI(self): self.playingId = -1 model = QStandardItemModel() self.setModel(model) #self.selectionModel().selectionChanged.connect(self.selectionChanged) # Dummy line to display headers self.addRow(Song(self.playlistOrder)) self.model().removeRow(0) # Fill headers, with first capital letter using title() headers = self.playlistOrder.title().replace('%','').split('|') model.setHeaderData(0,QtCore.Qt.Horizontal,'') for i,h in enumerate(headers): model.setHeaderData(i+1,QtCore.Qt.Horizontal,h) # One liner which is slower start1 = time.perf_counter() #map(lambda (i, h): model.setHeaderData(i+1,QtCore.Qt.Horizontal,h), enumerate(headers)) self.resizeColumnsToContents() self.resizeRowsToContents() self.show()
def _show_related_apis(self): self.switch_btn_apis.hide() self.switch_btn_mashups.hide() self.recommendLabel.hide() row = 0 objs = [] for mashup in self.related_mashups: objs.append(mashup) for api in mashup["related_mashups"]: objs.append(api) #Combining similarity and related. similar_apis = self.data_source.search_api_similarity(self.highlighted_api) #return str(mashup['id'])[(len("http://www.programmableweb.com/mashup/")):] objs.append({'id': "http://www.programmableweb.com/mashup/Using-Similarity-Metric"}) objs.extend(similar_apis) #Combining similarity and related. model = QStandardItemModel(len(objs), 5) for obj in objs: if obj.get('protocols'): model.setData(model.index(row, 1), QVariant(get_api_name(obj))) model.setData(model.index(row, 2), QVariant(obj['protocols'])) model.setData(model.index(row, 3), QVariant(obj['provider'])) model.setData(model.index(row, 4), QVariant(obj['version'])) else: model.setData(model.index(row, 0), QVariant(get_mashup_name(obj))) row += 1 model.setHeaderData(0, Qt.Horizontal, QVariant("Mashup")) model.setHeaderData(1, Qt.Horizontal, QVariant("API")) model.setHeaderData(2, Qt.Horizontal, QVariant("Protocols")) model.setHeaderData(3, Qt.Horizontal, QVariant("Provider")) model.setHeaderData(4, Qt.Horizontal, QVariant("Version")) self.table.setModel(model) self.switch_btn_mashups.show()
class Dialog(QDialog, Ui_nbEditor_dialog): def __init__(self, iface, ml, mc): """Constructor for the dialog. Args: iface: QgsInterface instance. """ QDialog.__init__(self, iface.mainWindow()) self.setupUi(self) self.ml = ml self.mCanvas = mc self.mRubberBand = QgsRubberBand(self.mCanvas, True) self.mRubberBand.reset(QGis.Polygon) self.mRubberBand.setColor(Qt.red) self.mRubberBand.setWidth(2) self.ids = [] self.ini(0) self.pushCancel.clicked.connect(self.close) self.pushOK.clicked.connect(self.convert) self.comboBox.addItems(['','Intersections','Touches','Within distance']) self.comboBox.currentIndexChanged.connect(self.nbMethod) self.ml.selectionChanged.connect(self.map2tab) def ini(self, n): self.model = QStandardItemModel(n, 1) self.tableView.setModel(self.model) self.model.setHeaderData(0, Qt.Horizontal, 'Neighbouring IDs') self.tableView.setSelectionMode(QAbstractItemView.SingleSelection) self.selectionModel = QItemSelectionModel(self.model) self.tableView.setSelectionModel(self.selectionModel) self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.selectionModel().selectionChanged.connect(self.tab2map) self.progressBar.setValue(0) def settings(self): self.mod = min(self.ids) self.p = 1 if self.mod==1: self.p = 0 def map2tab(self): s = '' idx = self.tableView.selectionModel().selectedIndexes()[0] ts = str(self.model.itemData(idx)[0]) for fid in sorted(self.ml.selectedFeaturesIds()): s += '%s,' % str(int(fid)+self.p) s = s[:-1] if s!=ts: self.model.setData(idx, s) # in order to handle the symmetry if len(s)>len(ts): iLst = s.strip().replace(' ', '').split(',') jLst = ts.strip().replace(' ', '').split(',') else: iLst = ts.strip().replace(' ', '').split(',') jLst = s.strip().replace(' ', '').split(',') cent = str(idx.row()+self.p) dLst = list(set(iLst)-set(jLst)) for d in dLst: row = int(d)-self.p sor = str(self.model.itemData(self.model.index(row, 0))[0]) eLst = sor.strip().replace(' ', '').split(',') res = '' if cent in set(eLst): ii = eLst.index(cent) del eLst[ii] eLst = sorted(map(int, eLst)) for e in eLst: res += '%s,' % e res = res[:-1] else: u = sor + ',%s' % cent eLst = sorted(map(int, u.strip().replace(' ', '').split(','))) for e in eLst: res += '%s,' % e res = res[:-1] self.model.setData(self.model.index(row, 0, QModelIndex()), res) def nbWithinDist(self): dlg = xdist.Dialog() dlg.setModal(True) dlg.setWindowTitle("Between two objects") if dlg.exec_() == QDialog.Accepted: lDist = float(dlg.lineEdit.text()) if lDist==0: return feat = QgsFeature() provider = self.ml.dataProvider() e = provider.featureCount() self.settings() for ne in range(self.mod, e + self.mod): feat = QgsFeature() geom = QgsGeometry() fiter = self.ml.getFeatures(QgsFeatureRequest(ne)) if fiter.nextFeature(feat): geom = QgsGeometry(feat.geometry()) neighbours = self.hdist(feat, lDist) row = feat.id()-self.mod self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours) self.progressBar.setValue(100*ne/e) def hdist(self, feata, lDist): geoma = QgsGeometry(feata.geometry()) feat = QgsFeature() provider = self.ml.dataProvider() feats = provider.getFeatures() self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0) self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) ne = 0 neighbours = "" while feats.nextFeature(feat): ne += 1 self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne) geomb = QgsGeometry(feat.geometry()) if feata.id()!=feat.id(): if geoma.distance(geomb)<=lDist: neighbours = neighbours + '%s,' % (feat.id()+self.p) return neighbours[:-1] def tab2map(self): QApplication.setOverrideCursor(Qt.WaitCursor) self.ml.selectionChanged.disconnect(self.map2tab) idx = self.tableView.selectionModel().selectedIndexes()[0] featureId = idx.row() + self.p s = self.model.itemData(idx) lst = s[0].strip().replace(' ', '').split(',') self.ml.removeSelection() for sid in lst: self.ml.select(int(sid)-self.p) provider = self.ml.dataProvider() feat = QgsFeature() layer = QgsVectorLayerCache(self.ml, provider.featureCount()) layer.featureAtId(idx.row()+self.mod, feat) geom = QgsGeometry(feat.geometry()) self.mRubberBand.setToGeometry(geom, self.ml) self.mRubberBand.show() self.ml.selectionChanged.connect(self.map2tab) QApplication.restoreOverrideCursor() def closeEvent(self,event): QApplication.setOverrideCursor(Qt.WaitCursor) self.ml.selectionChanged.disconnect(self.map2tab) self.ml.removeSelection() self.mRubberBand.hide() self.close() QApplication.restoreOverrideCursor() def convert(self): dlg = editor.Dialog() dlg.setModal(True) dlg.setWindowTitle("Neighbour list in BUGS format") num = "" adj = "" sumNumNeigh = 0 for row in range(0, self.model.rowCount()): ts = self.model.itemData(self.model.index(row, 0)) lst = ts[0].strip().replace(' ', '').split(',') num += '%s, ' % len(lst) sumNumNeigh += len(lst) lst.reverse() sor = ', '.join(lst) + ',' adj = adj + str(sor) + '\n' num = num[:-2] adj = adj[:-2] nblist = 'list(\nnum = c(%s),\nadj = c(%s),\nsumNumNeigh=%s)' % (num, adj, sumNumNeigh) dlg.plainTextEdit.appendPlainText(nblist) dlg.exec_() def nbMethod(self): QApplication.setOverrideCursor(Qt.WaitCursor) self.ml.selectionChanged.disconnect(self.map2tab) self.model.removeRows(0, self.model.rowCount(QModelIndex()), QModelIndex()) n = self.ml.dataProvider().featureCount() self.ini(n) self.ids = [] provider = self.ml.dataProvider() feats = provider.getFeatures() self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0) self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, n)) ne = 0 feat = QgsFeature() while feats.nextFeature(feat): ne += 1 self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne) self.ids.append(feat.id()) if self.comboBox.currentText()=="Touches": if self.ml.geometryType()==0: return else: self.nbTouches() if self.comboBox.currentText()=="Intersections": if self.ml.geometryType()==0: return else: self.nbIntersects() if self.comboBox.currentText()=="Within distance": self.nbWithinDist() self.ml.selectionChanged.connect(self.map2tab) QApplication.restoreOverrideCursor() def nbTouches(self): feat = QgsFeature() provider = self.ml.dataProvider() e = provider.featureCount() self.settings() for ne in range(self.mod, e + self.mod): feat = QgsFeature() geom = QgsGeometry() fiter = self.ml.getFeatures(QgsFeatureRequest(ne)) if fiter.nextFeature(feat): geom = QgsGeometry(feat.geometry()) neighbours = self.htouch(feat) row = feat.id()-self.mod self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours) self.progressBar.setValue(100*ne/e) def htouch(self, feata): geoma = QgsGeometry(feata.geometry()) feat = QgsFeature() provider = self.ml.dataProvider() feats = provider.getFeatures() self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0) self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) ne = 0 neighbours = "" while feats.nextFeature(feat): ne += 1 self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne) geomb = QgsGeometry(feat.geometry()) if feata.id()!=feat.id(): if geoma.touches(geomb)==True: neighbours = neighbours + '%s,' % (feat.id()+self.p) return neighbours[:-1] def nbIntersects(self): feat = QgsFeature() provider = self.ml.dataProvider() e = provider.featureCount() self.settings() for ne in range(self.mod, e + self.mod): feat = QgsFeature() geom = QgsGeometry() fiter = self.ml.getFeatures(QgsFeatureRequest(ne)) if fiter.nextFeature(feat): geom = QgsGeometry(feat.geometry()) neighbours = self.hintersect(feat) row = feat.id()-self.mod self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours) self.progressBar.setValue(100*ne/e) def hintersect(self, feata): geoma = QgsGeometry(feata.geometry()) feat = QgsFeature() provider = self.ml.dataProvider() feats = provider.getFeatures() self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0) self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) ne = 0 neighbours = "" while feats.nextFeature(feat): ne += 1 self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne) geomb = QgsGeometry(feat.geometry()) if feata.id()!=feat.id(): if geoma.intersects(geomb)==True: neighbours = neighbours + '%s,' % (feat.id()+self.p) return neighbours[:-1]
class route: def __init__(self, name='', desc='', survey_date=None, run_no=''): self.name = name self.desc = desc self.survey_date = survey_date self.run_no = run_no self.model = QStandardItemModel() #self.model=route_model.route_model() self.model.setColumnCount(len(cols)) [self.model.setHeaderData(cols[c], Qt.Horizontal, c) for c in cols] #def add_section(self,label,snode,rev,length,rbt,ch,desc,wkt,row=0): # #self.model.insertRow(row,[make_cell(label),make_cell(rev,True),make_cell(desc,True),make_cell(ch),make_cell(snode),make_cell(length),make_cell(rbt),make_cell(wkt)]) def add_section(self, label, rev, desc, ch, snode, length, rbt, wkt, row=0): self.model.insertRow(row, [ make_cell(label), make_cell(rev, True), make_cell(desc, True), make_cell(ch), make_cell(snode), make_cell(length), make_cell(rbt), make_cell(wkt) ]) #converts to qgis features def to_features(self, layer): return [ self.to_feat(i, layer) for i in range(0, self.model.rowCount()) ] def remove_rows(self, rows): # removing changes following row numbers.Start with highest row number. for r in reversed(sorted(rows)): self.model.takeRow(r) #key like [route_att:feature_att] def add_feat(self, f, transform, row, rev, key): geom = f.geometry() geom.transform(transform) snode = f[key['snode']] if rev: geom = reversed_geom(geom) snode = f[key['enode']] #chainage will be recalculated so irrelevant self.add_section(f[key['section_label']], rev, f[key['section_description']], 0, snode, f[key['section_length']], f[key['roundabout']], geom.exportToWkt(), row) # g.geometry().asWkt()))) for qgis 3 #make qgis feature from row of model def to_feat(self, row, layer): feat = QgsFeature(layer.fields()) for c in cols: if c != 'wkt': feat.setAttribute(c, self.get_val(row, cols[c])) feat.setAttribute('route', self.name) feat.setAttribute('route_description', self.desc) feat.setAttribute('survey_date', self.desc) feat.setAttribute('run_no', self.run_no) if self.get_val(row, cols['reversed']): geom = reversed_geom( QgsGeometry.fromWkt(self.get_val(row, cols['wkt']))) else: geom = QgsGeometry.fromWkt(self.get_val(row, cols['wkt'])) feat.setGeometry(geom) return feat def get_val(self, row, col): return self.model.item(row, col).data(Qt.EditRole) def __eq__(self, other): return self.name == other.name and self.desc == other.desc and self.run_no == other.run_no #and self.survey_date=other.survey_date #def __add__(self,other): # if self==other: # r=route(self.name,self.desc,self.survey_date,self.run_no) # else: # raise ValueError('conflicting route data') def consume_other(self, other): if self == other: for i in other.model.rowCount(): self.model.appendRow(other.model.takeRow(i)) else: raise ValueError('conflicting route data')
class Dialog_report(QDialog, Ui_Dialog_report): """ Class documentation goes here. """ def __init__(self, parent=None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self) #construct Customer list class self.clist = Customer_list() #construct accounting class self.caccount = Dfile() #construct customer price class self.cprice = Customer_price() #construct standard table self.tablemodel = QStandardItemModel(31, len(PRODUCT_NAME)) self.setTableheader() #save customer list int self.list_customer = self.clist.readCompany() self.setCombo(1, self.list_customer) def setMode(self, str_mode): if str_mode == 'init': self.clearAllshow() def setCombo(self, comboselect, m_str): """ set combo box """ if comboselect == 1: for i in m_str: self.comboBox_name.addItem(i) elif comboselect == 2: self.comboBox_date.clear() for i in m_str: self.comboBox_date.addItem(i) def clearAllshow(self): #clear all spin box self.setAllspin(0) #clear table self.clearTableview() def setAllspin(self, int_value): self.spinBox_1.setValue(int_value) self.spinBox_2.setValue(int_value) self.spinBox_3.setValue(int_value) self.spinBox_4.setValue(int_value) self.spinBox_5.setValue(int_value) self.spinBox_6.setValue(int_value) self.spinBox_7.setValue(int_value) self.spinBox_8.setValue(int_value) self.spinBox_9.setValue(int_value) self.spinBox_10.setValue(int_value) self.spinBox_11.setValue(int_value) self.spinBox_12.setValue(int_value) self.spinBox_13.setValue(int_value) self.spinBox_14.setValue(int_value) self.spinBox_15.setValue(int_value) self.spinBox_16.setValue(int_value) self.spinBox_17.setValue(int_value) self.spinBox_18.setValue(int_value) self.spinBox_19.setValue(int_value) self.spinBox_19.setValue(0) def setTableheader(self): #set header data self.tablemodel.setHeaderData(0, Qt.Horizontal, PRODUCT_NAME[0]) self.tablemodel.setHeaderData(1, Qt.Horizontal, PRODUCT_NAME[1]) self.tablemodel.setHeaderData(2, Qt.Horizontal, PRODUCT_NAME[2]) self.tablemodel.setHeaderData(3, Qt.Horizontal, PRODUCT_NAME[3]) self.tablemodel.setHeaderData(4, Qt.Horizontal, PRODUCT_NAME[4]) self.tablemodel.setHeaderData(5, Qt.Horizontal, PRODUCT_NAME[5]) def setTableview(self, dlist_data): """ set data into tableview model """ #show data row = 0 for i in dlist_data: self.tablemodel.setData(self.tablemodel.index(row, 0), QVariant(i[0])) self.tablemodel.setData(self.tablemodel.index(row, 1), QVariant(i[1])) self.tablemodel.setData(self.tablemodel.index(row, 2), QVariant(i[2])) self.tablemodel.setData(self.tablemodel.index(row, 3), QVariant(i[3])) self.tablemodel.setData(self.tablemodel.index(row, 4), QVariant(i[4])) self.tablemodel.setData(self.tablemodel.index(row, 5), QVariant(i[5])) row += 1 #set table into tableview self.tableView.setModel(self.tablemodel) def clearTableview(self): """ clear table """ #show data row = 0 i = [0, 0, 0, 0, 0, 0] for row in range(31): self.tablemodel.setData(self.tablemodel.index(row, 0), QVariant(i[0])) self.tablemodel.setData(self.tablemodel.index(row, 1), QVariant(i[1])) self.tablemodel.setData(self.tablemodel.index(row, 2), QVariant(i[2])) self.tablemodel.setData(self.tablemodel.index(row, 3), QVariant(i[3])) self.tablemodel.setData(self.tablemodel.index(row, 4), QVariant(i[4])) self.tablemodel.setData(self.tablemodel.index(row, 5), QVariant(i[5])) #set table into tableview self.tableView.setModel(self.tablemodel) @pyqtSignature("QString") def on_comboBox_name_currentIndexChanged(self, p0): """ when name index change, set combo date """ #set to initial status self.setMode('init') #read combo text and dict value self.str_customercombo = str(self.comboBox_name.currentText().toUtf8()) self.i_customercombo = self.clist.readCvalue(self.str_customercombo) #read all guest accounting data self.list_date = self.caccount.listDatafile(self.i_customercombo) self.setCombo(2, self.list_date) @pyqtSignature("QString") def on_comboBox_date_currentIndexChanged(self, p0): """ search price data and load accounting into table """ self.str_filename = str(self.comboBox_date.currentText()) if self.str_filename != '': self.str_datecombo = self.str_filename[3:9] #get price version self.i_priceversion = self.cprice.selectPrice( self.i_customercombo, self.str_datecombo) #get price dict dict_price = self.cprice.readPrice(self.i_customercombo, self.i_priceversion) self.list_price = self.cprice.getClist(dict_price) #show price self.setPricespin(self.list_price) #show table self.caccount.open_dfile(self.str_filename) self.table_data = self.caccount.read_alldfile() self.setTableview(self.table_data) #calculate and show single amount self.eachamount = self.sumEachamount(self.table_data) self.setEachamount(self.eachamount) #calculate single price amount self.eachpriceamount = [ self.eachamount[i] * self.list_price[i] for i in range(len(PRODUCT_NAME)) ] self.setEachpriceamount(self.eachpriceamount) #show in total income self.spinBox_19.setValue(sum(self.eachpriceamount)) def setPricespin(self, list): self.spinBox_1.setValue(list[0]) self.spinBox_2.setValue(list[1]) self.spinBox_3.setValue(list[2]) self.spinBox_4.setValue(list[3]) self.spinBox_5.setValue(list[4]) self.spinBox_6.setValue(list[5]) def setEachamount(self, list): self.spinBox_7.setValue(list[0]) self.spinBox_8.setValue(list[1]) self.spinBox_9.setValue(list[2]) self.spinBox_10.setValue(list[3]) self.spinBox_11.setValue(list[4]) self.spinBox_12.setValue(list[5]) def setEachpriceamount(self, list): self.spinBox_13.setValue(list[0]) self.spinBox_14.setValue(list[1]) self.spinBox_15.setValue(list[2]) self.spinBox_16.setValue(list[3]) self.spinBox_17.setValue(list[4]) self.spinBox_18.setValue(list[5]) #sum each item total amount def sumEachamount(self, duallist): eachamount = [0, 0, 0, 0, 0, 0] count = 0 for i in duallist: for j in i: eachamount[count] += j count += 1 count = 0 return eachamount
class ResultView(QWidget): """This class represent a search result view. """ def __init__(self, filter='', attributes=[], resultlist=[], parent=None): """Initialize a result view for the `SearchPlugin`. :param filter: the filter applied on the search :type filter: string :param attributes: a list containing the attributes used in the search operation. Usually extracted from the `filter`. :type attributes: list :param resultlist: a list of `SmartDataObject` from the search operation. :type resultlist: list :param parent: the parent for this widget. :type parent: QWidget """ super(ResultView, self).__init__(parent) self.setObjectName('ResultView') self.layout = QtGui.QVBoxLayout(self) # Only display the no-result message if resultlist is empty if len(resultlist) == 0: self.retranslate(all=False) self.onNoResult() return # The proxy model is used for sort and filter support self.proxymodel = QSortFilterProxyModel(self) self.proxymodel.setDynamicSortFilter(True) self.headerdata = ['dn'] self.headerdata.extend(attributes) self.resultdata = resultlist # FIXME: should we create a custom item model ? self.model = QStandardItemModel(0, len(self.headerdata), parent=self) #self.model = ResultItemModel(self) #self.model = ResultItemModel(self.headerdata, self.resultdata, self) self.proxymodel.setSourceModel(self.model) self.resultview = QTreeView(self) self.resultview.setUniformRowHeights(True) self.resultview.setRootIsDecorated(False) self.resultview.setAlternatingRowColors(True) self.resultview.setSortingEnabled(True) self.resultview.setModel(self.proxymodel) # For right-click context menu self.resultview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.resultview.setSelectionMode(QAbstractItemView.ExtendedSelection) self.layout.addWidget(self.resultview) # The filter box enables the user to filter the returned search # results. It becomes accessible with Ctrl-F (QKeySequence.Find) self.filterBox = ResultFilterWidget(self.headerdata, parent=self) self.filterBox.setVisible(False) self.layout.addWidget(self.filterBox) # We need to call the retranslate method before populating # the result data self.retranslate() #self.model.populateHeader(self.headerdata) #self.model.populateModel(self.resultdata) self.setHeaderData(self.headerdata) self.setResultData(self.resultdata) self.resultview.resizeColumnToContents(0) self.__createContextMenu() self.__connectSlots() def __connectSlots(self): """Connect signal and slots. """ self.resultview.customContextMenuRequested.connect( self.onContextMenuRequested) self.filterBox.inputEdit.textChanged['QString'].connect( self.onFilterInputChanged) self.filterBox.columnBox.currentIndexChanged[int].connect( self.onFilterColumnChanged) def __getVSpacer(self): return QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) def __createContextMenu(self): """Display the context menu. """ self.contextMenu = QtGui.QMenu() self.contextMenuView = QtGui.QAction(self) self.contextMenuDelete = QtGui.QAction(self) self.contextMenuExport = QtGui.QAction(self) self.contextMenu.addAction(self.contextMenuView) self.contextMenu.addAction(self.contextMenuDelete) self.contextMenu.addAction(self.contextMenuExport) # Connect the context menu actions to the correct slots self.contextMenuView.triggered.connect(self.onViewItemsSelected) self.contextMenuDelete.triggered.connect(self.onDeleteItemsSelected) self.contextMenuExport.triggered.connect(self.onExportItemsSelected) def onNoResult(self): """Adds a styled *no result* message to the main layout. """ font = QtGui.QFont() font.setBold(True) sadface = QtGui.QLabel(self) sadface.setPixmap(pixmapFromTheme('face-sad', ':/icons/48/face-sad')) noresult = QtGui.QLabel(self) noresult.setText(self.str_NO_RESULT) noresult.setFont(font) hlayout = QtGui.QHBoxLayout() hlayout.addItem(self.__getVSpacer()) hlayout.addWidget(sadface) hlayout.addWidget(noresult) hlayout.addItem(self.__getVSpacer()) self.layout.addLayout(hlayout) def setHeaderData(self, data=[]): """Populates the ``resultview`` model with header data. Parameters: - `data`: a list with header items. Usually this is the attributelist from the LDAP search. """ i = 0 for header in data: self.model.setHeaderData(i, QtCore.Qt.Horizontal, header) i += 1 def setResultData(self, data=[]): """Populates the ``resultview`` model with result data. Parameters: - `data`: a list containing the SmartDataObjects representing items in the LDAP search result. """ row = 0 for obj in data: self.model.insertRow(row) col = 0 for attr in self.headerdata: if self.isDistinguishedName(attr): modelData = obj.getPrettyDN() elif self.isObjectClass(attr): modelData = ','.join(obj.getObjectClasses()) elif obj.hasAttribute(attr): if obj.isAttributeBinary(attr): modelData = self.str_BINARY_DATA else: modelData = ','.join(obj.getAttributeValueList(attr)) self.model.setData(self.model.index(row, col), modelData) col += 1 row += 1 def isDistinguishedName(self, attr): """Returns ``True`` if `attr` is a distinguished name, ``False`` otherwise. Parameters: - `attr`: the LDAP string attribute value to check. """ return attr.lower() == 'dn' def isObjectClass(self, attr): """Returns ``True`` if `attr` is an object class, ``False`` otherwise. Parameters: - `attr`: the LDAP string attribute value to check. """ return attr.lower() == 'objectclass' def onContextMenuRequested(self, point): """Display the context menu """ # FIXME: In order to be able to export, delete and view search # result entries. We should make use of the various dialogs in # the Browser plugin. Unitl we have refactored the design in a # way that allow us to use these without accessing the browser # modules, we simple don't provide these options yet. return self.selection = self.resultview.selectedIndexes() deleteSupport = True exportSupport = True rowsselected = len(self.selection) / len(self.headerdata) if not rowsselected > 0: self.contextMenu.setEnabled(False) self.contextMenu.exec_(self.resultview.mapToGlobal(point)) return self.contextMenu.setEnabled(True) # Look over at Browser plugin for implementation of # multiselect and operation support validation print rowsselected self.contextMenuView.setEnabled(True) if rowsselected == 1: self.contextMenuView.setText(self.str_VIEW_ITEM) else: self.contextMenuView.setText(self.str_VIEW_ITEMS) if deleteSupport: self.contextMenuDelete.setEnabled(True) if rowsselected == 1: self.contextMenuDelete.setText(self.str_DELETE_ITEM) else: self.contextMenuDelete.setText(self.str_DELETE_ITEMS) if exportSupport: self.contextMenuExport.setEnabled(True) if rowsselected == 1: self.contextMenuExport.setText(self.str_EXPORT_ITEM) else: self.contextMenuExport.setText(self.str_EXPORT_ITEMS) # Finally we execute the context menu self.contextMenu.exec_(self.resultview.mapToGlobal(point)) def onViewItemsSelected(self): """Slot for the *view* context menu action. """ raise NotImplementedError( 'Need to implement a proper model for this to be supported') def onDeleteItemsSelected(self): """Slot for the *delete* context menu action. """ msg = 'Delete from the Search Plugin is not implemented jet.' dialog = DeleteDialog(self, msg) dialog.setDeleteItems([]) dialog.exec_() def onExportItemsSelected(self): """Slot for the 'export' context menu action. """ msg = 'Export from the Search Plugin is not implemented jet.' dialog = ExportDialog(self, msg) # Only for proof of concept dialog.setExportData([]) dialog.exec_() def onFilterBoxVisibilityChanged(self, visible): """Slot for the QKeySequence.Find. - `visible`: a boolean value indicating wether or not to toggle the filter box widget visibility on or off. """ if visible: self.filterBox.setVisible(True) self.filterBox.inputEdit.setFocus() else: # I belive it's common practise to clear the filter when # the filter box is closed. This is at least the way the # filter boxes works for most webbrowsers. self.filterBox.inputEdit.clear() self.filterBox.setVisible(False) self.resultview.setFocus() def onFilterInputChanged(self, filter=''): """Slot for the filter input in the result filter widget. We get the selected syntax from the syntax combobox """ # The PyQt4 QVariant is causing some problems here, when we try # to use the <combobox>.itemData directly, even though the data # holds valid QRexExp.PatternSyntax values. # We therefore need to explicitly make the QVariant and integer. i = self.filterBox.syntaxBox.currentIndex() syntaxIndex = self.filterBox.syntaxBox.itemData(i).toInt()[0] syntax = QtCore.QRegExp.PatternSyntax(syntaxIndex) # As of now we do filtering in a case insensitive way, until we # come up with a way to introduce case sensitivity selection in a # UI inexpensive way. We want to keep the filter widget as clean # and simple as possible. regex = QtCore.QRegExp(filter, QtCore.Qt.CaseInsensitive, syntax) self.proxymodel.setFilterRegExp(regex) def onFilterColumnChanged(self, index): """Slot for the column combobox in the filter box widget. """ self.proxymodel.setFilterKeyColumn(index) def retranslate(self, all=True): """For dynamic translation support. """ self.str_VIEW_ITEM = QtGui.QApplication.translate( 'ResultView', 'View Item') self.str_VIEW_ITEMS = QtGui.QApplication.translate( 'ResultView', 'View Items') self.str_DELETE_ITEM = QtGui.QApplication.translate( 'ResultView', 'Delete Item') self.str_DELETE_ITEMS = QtGui.QApplication.translate( 'ResultView', 'Delete Items') self.str_EXPORT_ITEM = QtGui.QApplication.translate( 'ResultView', 'Export Item') self.str_EXPORT_ITEMS = QtGui.QApplication.translate( 'ResultView', 'Export Items') self.str_NO_RESULT = QtGui.QApplication.translate( 'ResultView', 'Sorry, no result to display!') self.str_BINARY_DATA = QtGui.QApplication.translate( 'ResultView', 'Binary Data') if all: self.filterBox.retranslate()
class SetupDialog(QDialog, Ui_SetupDialog): """ Function and Event handling class for the Ui_SetupDialog. """ def __init__(self, parent): QDialog.__init__(self, parent) self._gui_logger = GUILogger("GUILogger", logging.INFO) self._gui_job = None EventLogger.add_logger(self._gui_logger) # FIXME better way to find interval and uids in tree_widget?! self.__tree_interval_tooltip = "Update interval in seconds" self.__tree_uid_tooltip = "UID cannot be empty" self.data_logger_thread = None self.tab_debug_warning = False self.device_dialog = None self.host_infos = None self.last_host = None self.host_index_changing = None self.setupUi(self) self.model_data = QStandardItemModel(self) self.model_data.setHorizontalHeaderLabels(['Time', 'Name', 'UID', 'Var', 'Raw', 'Unit']) self.table_data.setModel(self.model_data) self.table_data.setColumnWidth(0, 160) self.table_data.setColumnWidth(1, 170) self.table_data.setColumnWidth(2, 50) self.table_data.setColumnWidth(3, 110) self.table_data.setColumnWidth(4, 70) self.table_data.setColumnWidth(5, 100) self.model_devices = QStandardItemModel(self) self.model_devices.setHorizontalHeaderLabels(['Device', 'Value']) self.tree_devices.setModel(self.model_devices) self.tree_devices.setColumnWidth(0, 300) self.widget_initialization() self.btn_start_logging.setIcon(QIcon(load_pixmap('data_logger/start-icon.png'))) timestamp = int(time.time()) self.edit_csv_file_name.setText(os.path.join(get_home_path(), 'logger_data_{0}.csv'.format(timestamp))) self.edit_log_file_name.setText(os.path.join(get_home_path(), 'logger_debug_{0}.log'.format(timestamp))) self.combo_data_time_format.addItem(utils.timestamp_to_de(timestamp) + ' (DD.MM.YYYY HH:MM:SS)', 'de') self.combo_data_time_format.addItem(utils.timestamp_to_us(timestamp) + ' (MM/DD/YYYY HH:MM:SS)', 'us') self.combo_data_time_format.addItem(utils.timestamp_to_iso(timestamp) + ' (ISO 8601)', 'iso') self.combo_data_time_format.addItem(utils.timestamp_to_unix(timestamp) + ' (Unix)', 'unix') self.combo_debug_time_format.addItem(utils.timestamp_to_de(timestamp) + ' (DD.MM.YYYY HH:MM:SS)', 'de') self.combo_debug_time_format.addItem(utils.timestamp_to_us(timestamp) + ' (MM/DD/YYYY HH:MM:SS)', 'us') self.combo_debug_time_format.addItem(utils.timestamp_to_iso(timestamp) + ' (ISO 8601)', 'iso') self.combo_debug_time_format.addItem(utils.timestamp_to_unix(timestamp) + ' (Unix)', 'unix') self.combo_log_level.addItem('Debug', 'debug') self.combo_log_level.addItem('Info', 'info') self.combo_log_level.addItem('Warning', 'warning') self.combo_log_level.addItem('Error', 'error') self.combo_log_level.addItem('Critical', 'critical') self.combo_log_level.setCurrentIndex(0) # debug self.combo_debug_level.addItem('Debug', logging.DEBUG) self.combo_debug_level.addItem('Info', logging.INFO) self.combo_debug_level.addItem('Warning', logging.WARNING) self.combo_debug_level.addItem('Error', logging.ERROR) self.combo_debug_level.addItem('Critical', logging.CRITICAL) self.combo_debug_level.setCurrentIndex(1) # info self.update_ui_state() def update_ui_state(self): data_to_csv_file = self.check_data_to_csv_file.isChecked() debug_to_log_file = self.check_debug_to_log_file.isChecked() self.label_csv_file_name.setVisible(data_to_csv_file) self.edit_csv_file_name.setVisible(data_to_csv_file) self.btn_browse_csv_file_name.setVisible(data_to_csv_file) self.label_log_file_name.setVisible(debug_to_log_file) self.edit_log_file_name.setVisible(debug_to_log_file) self.btn_browse_log_file_name.setVisible(debug_to_log_file) self.label_log_level.setVisible(debug_to_log_file) self.combo_log_level.setVisible(debug_to_log_file) def widget_initialization(self): """ Sets default values for some widgets """ # Login data self.host_info_initialization() self.signal_initialization() def signal_initialization(self): """ Init of all important Signals and connections. """ # Buttons self.btn_start_logging.clicked.connect(self.btn_start_logging_clicked) self.btn_save_config.clicked.connect(self.btn_save_config_clicked) self.btn_load_config.clicked.connect(self.btn_load_config_clicked) self.check_data_to_csv_file.stateChanged.connect(self.update_ui_state) self.check_debug_to_log_file.stateChanged.connect(self.update_ui_state) self.btn_browse_csv_file_name.clicked.connect(self.btn_browse_csv_file_name_clicked) self.btn_browse_log_file_name.clicked.connect(self.btn_browse_log_file_name_clicked) self.btn_clear_debug.clicked.connect(self.btn_clear_debug_clicked) self.combo_debug_level.currentIndexChanged.connect(self.combo_debug_level_changed) self.btn_add_device.clicked.connect(self.btn_add_device_clicked) self.btn_remove_device.clicked.connect(self.btn_remove_device_clicked) self.btn_remove_all_devices.clicked.connect(self.btn_remove_all_devices_clicked) self.tab_widget.currentChanged.connect(self.tab_reset_warning) self.btn_clear_data.clicked.connect(self.btn_clear_data_clicked) self.connect(self._gui_logger, QtCore.SIGNAL(GUILogger.SIGNAL_NEW_MESSAGE), self.add_debug_message) self.connect(self._gui_logger, QtCore.SIGNAL(GUILogger.SIGNAL_NEW_MESSAGE_TAB_HIGHLIGHT), self.highlight_debug_tab) self.combo_host.currentIndexChanged.connect(self._host_index_changed) self.spin_port.valueChanged.connect(self._port_changed) def host_info_initialization(self): """ initialize host by getting information out of brickv.config """ self.host_infos = config.get_host_infos(config.HOST_INFO_COUNT) self.host_index_changing = True for host_info in self.host_infos: self.combo_host.addItem(host_info.host) self.last_host = None self.combo_host.setCurrentIndex(0) self.spin_port.setValue(self.host_infos[0].port) self.host_index_changing = False def btn_start_logging_clicked(self): """ Start/Stop of the logging process """ if (self.data_logger_thread is not None) and (not self.data_logger_thread.stopped): self.btn_start_logging.clicked.disconnect() self.data_logger_thread.stop() self._reset_stop() elif self.data_logger_thread is None: from brickv.data_logger import main self._gui_job = GuiDataJob(name="GuiData-Writer") self.connect(self._gui_job, QtCore.SIGNAL(GuiDataJob.SIGNAL_NEW_DATA), self.table_add_row) self.data_logger_thread = main.main(None, GuiConfigHandler.create_config(self), self._gui_job) if self.data_logger_thread is not None: self.btn_start_logging.setText("Stop Logging") self.btn_start_logging.setIcon(QIcon(load_pixmap('data_logger/stop-icon.png'))) self.tab_devices.setEnabled(False) self.tab_setup.setEnabled(False) self.tab_widget.setCurrentIndex(self.tab_widget.indexOf(self.tab_data)) self.tab_reset_warning() def _reset_stop(self): self.tab_devices.setEnabled(True) self.tab_setup.setEnabled(True) self.btn_start_logging.setText("Start Logging") self.btn_start_logging.setIcon(QIcon(load_pixmap('data_logger/start-icon.png'))) self.disconnect(self._gui_job, QtCore.SIGNAL(GuiDataJob.SIGNAL_NEW_DATA), self.table_add_row) self.data_logger_thread = None self._gui_job = None self.btn_start_logging.clicked.connect(self.btn_start_logging_clicked) def btn_save_config_clicked(self): filename = get_save_file_name(get_main_window(), 'Save Config', get_home_path(), 'JSON Files (*.json)') if len(filename) == 0: return if not filename.lower().endswith('.json'): filename += '.json' config = GuiConfigHandler.create_config(self) if not save_config(config, filename): QMessageBox.warning(get_main_window(), 'Save Config', 'Could not save config to file! See Debug tab for details.', QMessageBox.Ok) def btn_load_config_clicked(self): filename = get_open_file_name(get_main_window(), 'Load Config', get_home_path(), 'JSON Files (*.json)') if len(filename) == 0: return config = load_and_validate_config(filename) if config == None: QMessageBox.warning(get_main_window(), 'Load Config', 'Could not load config from file! See Debug tab for details.', QMessageBox.Ok) return self.update_setup_tab(config) self.update_devices_tab(config) def btn_browse_csv_file_name_clicked(self): if len(self.edit_csv_file_name.text()) > 0: last_dir = os.path.dirname(os.path.realpath(self.edit_csv_file_name.text())) else: last_dir = get_home_path() filename = get_save_file_name(get_main_window(), 'Choose CSV File', last_dir, "CSV Files (*.csv)") if len(filename) > 0: if not filename.lower().endswith('.csv'): filename += '.csv' self.edit_csv_file_name.setText(filename) def btn_browse_log_file_name_clicked(self): if len(self.edit_log_file_name.text()) > 0: last_dir = os.path.dirname(os.path.realpath(self.edit_log_file_name.text())) else: last_dir = get_home_path() filename = get_save_file_name(get_main_window(), 'Choose Log File', last_dir, "Log Files (*.log)") if len(filename) > 0: if not filename.lower().endswith('.log'): filename += '.log' self.edit_log_file_name.setText(filename) def btn_add_device_clicked(self): """ Opens the DeviceDialog in Add-Mode. """ if self.device_dialog is None: self.device_dialog = DeviceDialog(self) self.device_dialog.btn_refresh_clicked() self.device_dialog.show() def btn_remove_device_clicked(self): selection = self.tree_devices.selectionModel().selectedIndexes() while len(selection) > 0: index = selection[0] while index.parent() != self.model_devices.invisibleRootItem().index(): index = index.parent() self.model_devices.removeRows(index.row(), 1) # get new selection, because row removal might invalid indices selection = self.tree_devices.selectionModel().selectedIndexes() def btn_remove_all_devices_clicked(self): self.model_devices.removeRows(0, self.model_devices.rowCount()) def btn_clear_data_clicked(self): self.model_data.removeRows(0, self.model_data.rowCount()) def tab_reset_warning(self): """ Resets the Warning @ the debug tab. """ if not self.tab_debug_warning or self.tab_widget.currentWidget().objectName() != self.tab_debug.objectName(): return self.tab_debug_warning = False self.tab_set(self.tab_widget.indexOf(self.tab_debug), self.palette().color(QPalette.WindowText), None) def combo_debug_level_changed(self): """ Changes the log level dynamically. """ self._gui_logger.level = self.combo_debug_level.itemData(self.combo_debug_level.currentIndex()) def tab_set(self, tab_index, color, icon=None): """ Sets the font Color and an icon, if given, at a specific tab. """ from PyQt4.QtGui import QIcon self.tab_widget.tabBar().setTabTextColor(tab_index, color) if icon is not None: self.tab_widget.setTabIcon(tab_index, QIcon(icon)) else: self.tab_widget.setTabIcon(tab_index, QIcon()) def _host_index_changed(self, i): """ Persists host information changes like in brickv.mainwindow Changes port if the host was changed """ if i < 0: return self.host_index_changing = True self.spin_port.setValue(self.host_infos[i].port) self.host_index_changing = False def _port_changed(self, value): """ Persists host information changes like in brickv.mainwindow """ if self.host_index_changing: return i = self.combo_host.currentIndex() if i < 0: return self.host_infos[i].port = self.spin_port.value() def update_setup_tab(self, config): EventLogger.debug('Updating setup tab from config') self.combo_host.setEditText(config['hosts']['default']['name']) self.spin_port.setValue(config['hosts']['default']['port']) self.combo_data_time_format.setCurrentIndex(max(self.combo_data_time_format.findData(config['data']['time_format']), 0)) self.check_data_to_csv_file.setChecked(config['data']['csv']['enabled']) self.edit_csv_file_name.setText(config['data']['csv']['file_name'].decode('utf-8')) self.combo_debug_time_format.setCurrentIndex(max(self.combo_debug_time_format.findData(config['debug']['time_format']), 0)) self.check_debug_to_log_file.setChecked(config['debug']['log']['enabled']) self.edit_log_file_name.setText(config['debug']['log']['file_name'].decode('utf-8')) self.combo_log_level.setCurrentIndex(max(self.combo_debug_time_format.findData(config['debug']['log']['level']), 0)) def update_devices_tab(self, config): EventLogger.debug('Updating devices tab from config') self.model_devices.removeRows(0, self.model_data.rowCount()) for device in config['devices']: self.add_device_to_tree(device) def add_device_to_tree(self, device): # check if device is already added if len(device['uid']) > 0: for row in range(self.model_devices.rowCount()): existing_name = self.model_devices.item(row, 0).text() exisitng_uid = self.tree_devices.indexWidget(self.model_devices.item(row, 1).index()).text() if device['name'] == existing_name and device['uid'] == exisitng_uid: EventLogger.info('Ignoring duplicate device "{0}" with UID "{1}"' .format(device['name'], device['uid'])) return # add device name_item = QStandardItem(device['name']) uid_item = QStandardItem('') self.model_devices.appendRow([name_item, uid_item]) edit_uid = QLineEdit() edit_uid.setPlaceholderText('Enter UID') edit_uid.setValidator(QRegExpValidator(QRegExp('^[{0}]{{1,6}}$'.format(BASE58)))) # FIXME: use stricter logic edit_uid.setText(device['uid']) self.tree_devices.setIndexWidget(uid_item.index(), edit_uid) value_specs = device_specs[device['name']]['values'] parent_item = QStandardItem('Values') name_item.appendRow([parent_item, QStandardItem('')]) self.tree_devices.expand(parent_item.index()) # add values for value_spec in value_specs: value_name_item = QStandardItem(value_spec['name']) value_interval_item = QStandardItem('') parent_item.appendRow([value_name_item, value_interval_item]) spinbox_interval = QSpinBox() spinbox_interval.setRange(0, (1 << 31) - 1) spinbox_interval.setSingleStep(1) spinbox_interval.setValue(device['values'][value_spec['name']]['interval']) spinbox_interval.setSuffix(' seconds') self.tree_devices.setIndexWidget(value_interval_item.index(), spinbox_interval) if value_spec['subvalues'] != None: for subvalue_name in value_spec['subvalues']: subvalue_name_item = QStandardItem(subvalue_name) subvalue_check_item = QStandardItem('') value_name_item.appendRow([subvalue_name_item, subvalue_check_item]) check_subvalue = QCheckBox() check_subvalue.setChecked(device['values'][value_spec['name']]['subvalues'][subvalue_name]) self.tree_devices.setIndexWidget(subvalue_check_item.index(), check_subvalue) self.tree_devices.expand(name_item.index()) # add options option_specs = device_specs[device['name']]['options'] if option_specs != None: parent_item = QStandardItem('Options') name_item.appendRow([parent_item, QStandardItem('')]) for option_spec in option_specs: option_name_item = QStandardItem(option_spec['name']) option_widget_item = QStandardItem('') parent_item.appendRow([option_name_item, option_widget_item]) if option_spec['type'] == 'choice': widget_option_value = QComboBox() for option_value_spec in option_spec['values']: widget_option_value.addItem(option_value_spec[0].decode('utf-8'), option_value_spec[1]) widget_option_value.setCurrentIndex(widget_option_value.findText(device['options'][option_spec['name']]['value'].decode('utf-8'))) elif option_spec['type'] == 'int': widget_option_value = QSpinBox() widget_option_value.setRange(option_spec['minimum'], option_spec['maximum']) widget_option_value.setSuffix(option_spec['suffix']) widget_option_value.setValue(device['options'][option_spec['name']]['value']) elif option_spec['type'] == 'bool': widget_option_value = QCheckBox() widget_option_value.setChecked(device['options'][option_spec['name']]['value']) self.tree_devices.setIndexWidget(option_widget_item.index(), widget_option_value) def add_debug_message(self, message): self.text_debug.append(message) while self.text_debug.document().blockCount() > 1000: cursor = QTextCursor(self.text_debug.document().begin()) cursor.select(QTextCursor.BlockUnderCursor) cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) cursor.removeSelectedText() if self.checkbox_debug_auto_scroll.isChecked(): self.text_debug.verticalScrollBar().setValue(self.text_debug.verticalScrollBar().maximum()) def btn_clear_debug_clicked(self): self.text_debug.clear() def highlight_debug_tab(self): """ SIGNAL function: Highlight the debug tab when an error occurs. """ if not self.tab_debug_warning and self.tab_widget.currentWidget().objectName() != self.tab_debug.objectName(): self.tab_debug_warning = True self.tab_set(self.tab_widget.indexOf(self.tab_debug), QColor(255, 0, 0), os.path.join(get_resources_path(), "warning-icon.png")) def table_add_row(self, csv_data): """ SIGNAL function: Adds new CSV Data into the Table. """ rows = self.model_data.rowCount() while rows >= 1000: self.model_data.removeRow(0) rows = self.model_data.rowCount() row_number = None if rows > 0: try: row_number = int(self.model_data.headerData(rows - 1, Qt.Vertical)) except ValueError: pass self.model_data.appendRow([QStandardItem(csv_data.timestamp), QStandardItem(csv_data.name), QStandardItem(csv_data.uid), QStandardItem(csv_data.var_name), QStandardItem(str(csv_data.raw_data)), QStandardItem(csv_data.var_unit.decode('utf-8'))]) if row_number != None: self.model_data.setHeaderData(rows, Qt.Vertical, str(row_number + 1)) if self.checkbox_data_auto_scroll.isChecked(): self.table_data.scrollToBottom()
class SetupDialog(QDialog, Ui_SetupDialog): """ Function and Event handling class for the Ui_SetupDialog. """ def __init__(self, parent): QDialog.__init__(self, parent) self._gui_logger = GUILogger("GUILogger", logging.INFO) self._gui_job = None EventLogger.add_logger(self._gui_logger) # FIXME better way to find interval and uids in tree_widget?! self.__tree_interval_tooltip = "Update interval in seconds" self.__tree_uid_tooltip = "UID cannot be empty" self.data_logger_thread = None self.tab_debug_warning = False self.device_dialog = None self.host_infos = None self.last_host = None self.host_index_changing = None self.setupUi(self) self.model_data = QStandardItemModel(self) self.model_data.setHorizontalHeaderLabels( ['Time', 'Name', 'UID', 'Var', 'Raw', 'Unit']) self.table_data.setModel(self.model_data) self.table_data.setColumnWidth(0, 160) self.table_data.setColumnWidth(1, 170) self.table_data.setColumnWidth(2, 50) self.table_data.setColumnWidth(3, 110) self.table_data.setColumnWidth(4, 70) self.table_data.setColumnWidth(5, 100) self.model_devices = QStandardItemModel(self) self.model_devices.setHorizontalHeaderLabels(['Device', 'Value']) self.tree_devices.setModel(self.model_devices) self.tree_devices.setColumnWidth(0, 300) self.widget_initialization() self.btn_start_logging.setIcon( QIcon(load_pixmap('data_logger/start-icon.png'))) timestamp = int(time.time()) self.edit_csv_file_name.setText( os.path.join(get_home_path(), 'logger_data_{0}.csv'.format(timestamp))) self.edit_log_file_name.setText( os.path.join(get_home_path(), 'logger_debug_{0}.log'.format(timestamp))) self.combo_data_time_format.addItem( utils.timestamp_to_de(timestamp) + ' (DD.MM.YYYY HH:MM:SS)', 'de') self.combo_data_time_format.addItem( utils.timestamp_to_us(timestamp) + ' (MM/DD/YYYY HH:MM:SS)', 'us') self.combo_data_time_format.addItem( utils.timestamp_to_iso(timestamp) + ' (ISO 8601)', 'iso') self.combo_data_time_format.addItem( utils.timestamp_to_unix(timestamp) + ' (Unix)', 'unix') self.combo_debug_time_format.addItem( utils.timestamp_to_de(timestamp) + ' (DD.MM.YYYY HH:MM:SS)', 'de') self.combo_debug_time_format.addItem( utils.timestamp_to_us(timestamp) + ' (MM/DD/YYYY HH:MM:SS)', 'us') self.combo_debug_time_format.addItem( utils.timestamp_to_iso(timestamp) + ' (ISO 8601)', 'iso') self.combo_debug_time_format.addItem( utils.timestamp_to_unix(timestamp) + ' (Unix)', 'unix') self.combo_log_level.addItem('Debug', 'debug') self.combo_log_level.addItem('Info', 'info') self.combo_log_level.addItem('Warning', 'warning') self.combo_log_level.addItem('Error', 'error') self.combo_log_level.addItem('Critical', 'critical') self.combo_log_level.setCurrentIndex(0) # debug self.combo_debug_level.addItem('Debug', logging.DEBUG) self.combo_debug_level.addItem('Info', logging.INFO) self.combo_debug_level.addItem('Warning', logging.WARNING) self.combo_debug_level.addItem('Error', logging.ERROR) self.combo_debug_level.addItem('Critical', logging.CRITICAL) self.combo_debug_level.setCurrentIndex(1) # info self.update_ui_state() def update_ui_state(self): data_to_csv_file = self.check_data_to_csv_file.isChecked() debug_to_log_file = self.check_debug_to_log_file.isChecked() self.label_csv_file_name.setVisible(data_to_csv_file) self.edit_csv_file_name.setVisible(data_to_csv_file) self.btn_browse_csv_file_name.setVisible(data_to_csv_file) self.label_log_file_name.setVisible(debug_to_log_file) self.edit_log_file_name.setVisible(debug_to_log_file) self.btn_browse_log_file_name.setVisible(debug_to_log_file) self.label_log_level.setVisible(debug_to_log_file) self.combo_log_level.setVisible(debug_to_log_file) def widget_initialization(self): """ Sets default values for some widgets """ # Login data self.host_info_initialization() self.signal_initialization() def signal_initialization(self): """ Init of all important Signals and connections. """ # Buttons self.btn_start_logging.clicked.connect(self.btn_start_logging_clicked) self.btn_save_config.clicked.connect(self.btn_save_config_clicked) self.btn_load_config.clicked.connect(self.btn_load_config_clicked) self.check_data_to_csv_file.stateChanged.connect(self.update_ui_state) self.check_debug_to_log_file.stateChanged.connect(self.update_ui_state) self.btn_browse_csv_file_name.clicked.connect( self.btn_browse_csv_file_name_clicked) self.btn_browse_log_file_name.clicked.connect( self.btn_browse_log_file_name_clicked) self.btn_clear_debug.clicked.connect(self.btn_clear_debug_clicked) self.combo_debug_level.currentIndexChanged.connect( self.combo_debug_level_changed) self.btn_add_device.clicked.connect(self.btn_add_device_clicked) self.btn_remove_device.clicked.connect(self.btn_remove_device_clicked) self.btn_remove_all_devices.clicked.connect( self.btn_remove_all_devices_clicked) self.tab_widget.currentChanged.connect(self.tab_reset_warning) self.btn_clear_data.clicked.connect(self.btn_clear_data_clicked) self.connect(self._gui_logger, QtCore.SIGNAL(GUILogger.SIGNAL_NEW_MESSAGE), self.add_debug_message) self.connect(self._gui_logger, QtCore.SIGNAL(GUILogger.SIGNAL_NEW_MESSAGE_TAB_HIGHLIGHT), self.highlight_debug_tab) self.combo_host.currentIndexChanged.connect(self._host_index_changed) self.spin_port.valueChanged.connect(self._port_changed) def host_info_initialization(self): """ initialize host by getting information out of brickv.config """ self.host_infos = config.get_host_infos(config.HOST_INFO_COUNT) self.host_index_changing = True for host_info in self.host_infos: self.combo_host.addItem(host_info.host) self.last_host = None self.combo_host.setCurrentIndex(0) self.spin_port.setValue(self.host_infos[0].port) self.host_index_changing = False def btn_start_logging_clicked(self): """ Start/Stop of the logging process """ if (self.data_logger_thread is not None) and (not self.data_logger_thread.stopped): self.btn_start_logging.clicked.disconnect() self.data_logger_thread.stop() self._reset_stop() elif self.data_logger_thread is None: from brickv.data_logger import main self._gui_job = GuiDataJob(name="GuiData-Writer") self.connect(self._gui_job, QtCore.SIGNAL(GuiDataJob.SIGNAL_NEW_DATA), self.table_add_row) self.data_logger_thread = main.main( None, GuiConfigHandler.create_config(self), self._gui_job) if self.data_logger_thread is not None: self.btn_start_logging.setText("Stop Logging") self.btn_start_logging.setIcon( QIcon(load_pixmap('data_logger/stop-icon.png'))) self.tab_devices.setEnabled(False) self.tab_setup.setEnabled(False) self.tab_widget.setCurrentIndex( self.tab_widget.indexOf(self.tab_data)) self.tab_reset_warning() def _reset_stop(self): self.tab_devices.setEnabled(True) self.tab_setup.setEnabled(True) self.btn_start_logging.setText("Start Logging") self.btn_start_logging.setIcon( QIcon(load_pixmap('data_logger/start-icon.png'))) self.disconnect(self._gui_job, QtCore.SIGNAL(GuiDataJob.SIGNAL_NEW_DATA), self.table_add_row) self.data_logger_thread = None self._gui_job = None self.btn_start_logging.clicked.connect(self.btn_start_logging_clicked) def btn_save_config_clicked(self): filename = get_save_file_name(get_main_window(), 'Save Config', get_home_path(), 'JSON Files (*.json)') if len(filename) == 0: return if not filename.lower().endswith('.json'): filename += '.json' config = GuiConfigHandler.create_config(self) if not save_config(config, filename): QMessageBox.warning( get_main_window(), 'Save Config', 'Could not save config to file! See Debug tab for details.', QMessageBox.Ok) def btn_load_config_clicked(self): filename = get_open_file_name(get_main_window(), 'Load Config', get_home_path(), 'JSON Files (*.json)') if len(filename) == 0: return config = load_and_validate_config(filename) if config == None: QMessageBox.warning( get_main_window(), 'Load Config', 'Could not load config from file! See Debug tab for details.', QMessageBox.Ok) return self.update_setup_tab(config) self.update_devices_tab(config) def btn_browse_csv_file_name_clicked(self): if len(self.edit_csv_file_name.text()) > 0: last_dir = os.path.dirname( os.path.realpath(self.edit_csv_file_name.text())) else: last_dir = get_home_path() filename = get_save_file_name(get_main_window(), 'Choose CSV File', last_dir, "CSV Files (*.csv)") if len(filename) > 0: if not filename.lower().endswith('.csv'): filename += '.csv' self.edit_csv_file_name.setText(filename) def btn_browse_log_file_name_clicked(self): if len(self.edit_log_file_name.text()) > 0: last_dir = os.path.dirname( os.path.realpath(self.edit_log_file_name.text())) else: last_dir = get_home_path() filename = get_save_file_name(get_main_window(), 'Choose Log File', last_dir, "Log Files (*.log)") if len(filename) > 0: if not filename.lower().endswith('.log'): filename += '.log' self.edit_log_file_name.setText(filename) def btn_add_device_clicked(self): """ Opens the DeviceDialog in Add-Mode. """ if self.device_dialog is None: self.device_dialog = DeviceDialog(self) self.device_dialog.btn_refresh_clicked() self.device_dialog.show() def btn_remove_device_clicked(self): selection = self.tree_devices.selectionModel().selectedIndexes() while len(selection) > 0: index = selection[0] while index.parent() != self.model_devices.invisibleRootItem( ).index(): index = index.parent() self.model_devices.removeRows(index.row(), 1) # get new selection, because row removal might invalid indices selection = self.tree_devices.selectionModel().selectedIndexes() def btn_remove_all_devices_clicked(self): self.model_devices.removeRows(0, self.model_devices.rowCount()) def btn_clear_data_clicked(self): self.model_data.removeRows(0, self.model_data.rowCount()) def tab_reset_warning(self): """ Resets the Warning @ the debug tab. """ if not self.tab_debug_warning or self.tab_widget.currentWidget( ).objectName() != self.tab_debug.objectName(): return self.tab_debug_warning = False self.tab_set(self.tab_widget.indexOf(self.tab_debug), self.palette().color(QPalette.WindowText), None) def combo_debug_level_changed(self): """ Changes the log level dynamically. """ self._gui_logger.level = self.combo_debug_level.itemData( self.combo_debug_level.currentIndex()) def tab_set(self, tab_index, color, icon=None): """ Sets the font Color and an icon, if given, at a specific tab. """ from PyQt4.QtGui import QIcon self.tab_widget.tabBar().setTabTextColor(tab_index, color) if icon is not None: self.tab_widget.setTabIcon(tab_index, QIcon(icon)) else: self.tab_widget.setTabIcon(tab_index, QIcon()) def _host_index_changed(self, i): """ Persists host information changes like in brickv.mainwindow Changes port if the host was changed """ if i < 0: return self.host_index_changing = True self.spin_port.setValue(self.host_infos[i].port) self.host_index_changing = False def _port_changed(self, value): """ Persists host information changes like in brickv.mainwindow """ if self.host_index_changing: return i = self.combo_host.currentIndex() if i < 0: return self.host_infos[i].port = self.spin_port.value() def update_setup_tab(self, config): EventLogger.debug('Updating setup tab from config') self.combo_host.setEditText(config['hosts']['default']['name']) self.spin_port.setValue(config['hosts']['default']['port']) self.combo_data_time_format.setCurrentIndex( max( self.combo_data_time_format.findData( config['data']['time_format']), 0)) self.check_data_to_csv_file.setChecked( config['data']['csv']['enabled']) self.edit_csv_file_name.setText( config['data']['csv']['file_name'].decode('utf-8')) self.combo_debug_time_format.setCurrentIndex( max( self.combo_debug_time_format.findData( config['debug']['time_format']), 0)) self.check_debug_to_log_file.setChecked( config['debug']['log']['enabled']) self.edit_log_file_name.setText( config['debug']['log']['file_name'].decode('utf-8')) self.combo_log_level.setCurrentIndex( max( self.combo_debug_time_format.findData( config['debug']['log']['level']), 0)) def update_devices_tab(self, config): EventLogger.debug('Updating devices tab from config') self.model_devices.removeRows(0, self.model_data.rowCount()) for device in config['devices']: self.add_device_to_tree(device) def add_device_to_tree(self, device): # check if device is already added if len(device['uid']) > 0: for row in range(self.model_devices.rowCount()): existing_name = self.model_devices.item(row, 0).text() exisitng_uid = self.tree_devices.indexWidget( self.model_devices.item(row, 1).index()).text() if device['name'] == existing_name and device[ 'uid'] == exisitng_uid: EventLogger.info( 'Ignoring duplicate device "{0}" with UID "{1}"'. format(device['name'], device['uid'])) return # add device name_item = QStandardItem(device['name']) uid_item = QStandardItem('') self.model_devices.appendRow([name_item, uid_item]) edit_uid = QLineEdit() edit_uid.setPlaceholderText('Enter UID') edit_uid.setValidator( QRegExpValidator(QRegExp( '^[{0}]{{1,6}}$'.format(BASE58)))) # FIXME: use stricter logic edit_uid.setText(device['uid']) self.tree_devices.setIndexWidget(uid_item.index(), edit_uid) value_specs = device_specs[device['name']]['values'] parent_item = QStandardItem('Values') name_item.appendRow([parent_item, QStandardItem('')]) self.tree_devices.expand(parent_item.index()) # add values for value_spec in value_specs: value_name_item = QStandardItem(value_spec['name']) value_interval_item = QStandardItem('') parent_item.appendRow([value_name_item, value_interval_item]) spinbox_interval = QSpinBox() spinbox_interval.setRange(0, (1 << 31) - 1) spinbox_interval.setSingleStep(1) spinbox_interval.setValue( device['values'][value_spec['name']]['interval']) spinbox_interval.setSuffix(' seconds') self.tree_devices.setIndexWidget(value_interval_item.index(), spinbox_interval) if value_spec['subvalues'] != None: for subvalue_name in value_spec['subvalues']: subvalue_name_item = QStandardItem(subvalue_name) subvalue_check_item = QStandardItem('') value_name_item.appendRow( [subvalue_name_item, subvalue_check_item]) check_subvalue = QCheckBox() check_subvalue.setChecked(device['values'][ value_spec['name']]['subvalues'][subvalue_name]) self.tree_devices.setIndexWidget( subvalue_check_item.index(), check_subvalue) self.tree_devices.expand(name_item.index()) # add options option_specs = device_specs[device['name']]['options'] if option_specs != None: parent_item = QStandardItem('Options') name_item.appendRow([parent_item, QStandardItem('')]) for option_spec in option_specs: option_name_item = QStandardItem(option_spec['name']) option_widget_item = QStandardItem('') parent_item.appendRow([option_name_item, option_widget_item]) if option_spec['type'] == 'choice': widget_option_value = QComboBox() for option_value_spec in option_spec['values']: widget_option_value.addItem( option_value_spec[0].decode('utf-8'), option_value_spec[1]) widget_option_value.setCurrentIndex( widget_option_value.findText(device['options'][ option_spec['name']]['value'].decode('utf-8'))) elif option_spec['type'] == 'int': widget_option_value = QSpinBox() widget_option_value.setRange(option_spec['minimum'], option_spec['maximum']) widget_option_value.setSuffix(option_spec['suffix']) widget_option_value.setValue( device['options'][option_spec['name']]['value']) elif option_spec['type'] == 'bool': widget_option_value = QCheckBox() widget_option_value.setChecked( device['options'][option_spec['name']]['value']) self.tree_devices.setIndexWidget(option_widget_item.index(), widget_option_value) def add_debug_message(self, message): self.text_debug.append(message) while self.text_debug.document().blockCount() > 1000: cursor = QTextCursor(self.text_debug.document().begin()) cursor.select(QTextCursor.BlockUnderCursor) cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) cursor.removeSelectedText() if self.checkbox_debug_auto_scroll.isChecked(): self.text_debug.verticalScrollBar().setValue( self.text_debug.verticalScrollBar().maximum()) def btn_clear_debug_clicked(self): self.text_debug.clear() def highlight_debug_tab(self): """ SIGNAL function: Highlight the debug tab when an error occurs. """ if not self.tab_debug_warning and self.tab_widget.currentWidget( ).objectName() != self.tab_debug.objectName(): self.tab_debug_warning = True self.tab_set( self.tab_widget.indexOf(self.tab_debug), QColor(255, 0, 0), os.path.join(get_resources_path(), "warning-icon.png")) def table_add_row(self, csv_data): """ SIGNAL function: Adds new CSV Data into the Table. """ rows = self.model_data.rowCount() while rows >= 1000: self.model_data.removeRow(0) rows = self.model_data.rowCount() row_number = None if rows > 0: try: row_number = int( self.model_data.headerData(rows - 1, Qt.Vertical)) except ValueError: pass self.model_data.appendRow([ QStandardItem(csv_data.timestamp), QStandardItem(csv_data.name), QStandardItem(csv_data.uid), QStandardItem(csv_data.var_name), QStandardItem(str(csv_data.raw_data)), QStandardItem(csv_data.var_unit.decode('utf-8')) ]) if row_number != None: self.model_data.setHeaderData(rows, Qt.Vertical, str(row_number + 1)) if self.checkbox_data_auto_scroll.isChecked(): self.table_data.scrollToBottom()
class Dialog_report(QDialog, Ui_Dialog_report): """ Class documentation goes here. """ def __init__(self, parent = None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self) #construct Customer list class self.clist = Customer_list() #construct accounting class self.caccount = Dfile() #construct customer price class self.cprice = Customer_price() #construct standard table self.tablemodel = QStandardItemModel(31, len(PRODUCT_NAME) ) self.setTableheader() #save customer list int self.list_customer = self.clist.readCompany() self.setCombo( 1, self.list_customer ) def setMode(self, str_mode): if str_mode == 'init': self.clearAllshow() def setCombo(self, comboselect, m_str): """ set combo box """ if comboselect == 1: for i in m_str: self.comboBox_name.addItem(i) elif comboselect == 2: self.comboBox_date.clear() for i in m_str: self.comboBox_date.addItem(i) def clearAllshow(self): #clear all spin box self.setAllspin(0) #clear table self.clearTableview() def setAllspin(self, int_value): self.spinBox_1.setValue(int_value) self.spinBox_2.setValue(int_value) self.spinBox_3.setValue(int_value) self.spinBox_4.setValue(int_value) self.spinBox_5.setValue(int_value) self.spinBox_6.setValue(int_value) self.spinBox_7.setValue(int_value) self.spinBox_8.setValue(int_value) self.spinBox_9.setValue(int_value) self.spinBox_10.setValue(int_value) self.spinBox_11.setValue(int_value) self.spinBox_12.setValue(int_value) self.spinBox_13.setValue(int_value) self.spinBox_14.setValue(int_value) self.spinBox_15.setValue(int_value) self.spinBox_16.setValue(int_value) self.spinBox_17.setValue(int_value) self.spinBox_18.setValue(int_value) self.spinBox_19.setValue(int_value) self.spinBox_19.setValue(0) def setTableheader(self): #set header data self.tablemodel.setHeaderData(0, Qt.Horizontal, PRODUCT_NAME[0] ) self.tablemodel.setHeaderData(1, Qt.Horizontal, PRODUCT_NAME[1] ) self.tablemodel.setHeaderData(2, Qt.Horizontal, PRODUCT_NAME[2] ) self.tablemodel.setHeaderData(3, Qt.Horizontal, PRODUCT_NAME[3] ) self.tablemodel.setHeaderData(4, Qt.Horizontal, PRODUCT_NAME[4] ) self.tablemodel.setHeaderData(5, Qt.Horizontal, PRODUCT_NAME[5] ) def setTableview(self, dlist_data ): """ set data into tableview model """ #show data row = 0 for i in dlist_data: self.tablemodel.setData(self.tablemodel.index(row, 0), QVariant(i[0])) self.tablemodel.setData(self.tablemodel.index(row, 1), QVariant(i[1])) self.tablemodel.setData(self.tablemodel.index(row, 2), QVariant(i[2])) self.tablemodel.setData(self.tablemodel.index(row, 3), QVariant(i[3])) self.tablemodel.setData(self.tablemodel.index(row, 4), QVariant(i[4])) self.tablemodel.setData(self.tablemodel.index(row, 5), QVariant(i[5])) row += 1 #set table into tableview self.tableView.setModel(self.tablemodel) def clearTableview(self): """ clear table """ #show data row = 0 i = [0, 0, 0, 0, 0, 0] for row in range(31): self.tablemodel.setData(self.tablemodel.index(row, 0), QVariant(i[0])) self.tablemodel.setData(self.tablemodel.index(row, 1), QVariant(i[1])) self.tablemodel.setData(self.tablemodel.index(row, 2), QVariant(i[2])) self.tablemodel.setData(self.tablemodel.index(row, 3), QVariant(i[3])) self.tablemodel.setData(self.tablemodel.index(row, 4), QVariant(i[4])) self.tablemodel.setData(self.tablemodel.index(row, 5), QVariant(i[5])) #set table into tableview self.tableView.setModel(self.tablemodel) @pyqtSignature("QString") def on_comboBox_name_currentIndexChanged(self, p0): """ when name index change, set combo date """ #set to initial status self.setMode('init') #read combo text and dict value self.str_customercombo = str( self.comboBox_name.currentText().toUtf8() ) self.i_customercombo = self.clist.readCvalue( self.str_customercombo ) #read all guest accounting data self.list_date = self.caccount.listDatafile( self.i_customercombo ) self.setCombo(2, self.list_date) @pyqtSignature("QString") def on_comboBox_date_currentIndexChanged(self, p0): """ search price data and load accounting into table """ self.str_filename = str( self.comboBox_date.currentText() ) if self.str_filename != '': self.str_datecombo = self.str_filename[3:9] #get price version self.i_priceversion = self.cprice.selectPrice( self.i_customercombo, self.str_datecombo ) #get price dict dict_price = self.cprice.readPrice( self.i_customercombo, self.i_priceversion ) self.list_price = self.cprice.getClist( dict_price ) #show price self.setPricespin( self.list_price ) #show table self.caccount.open_dfile( self.str_filename ) self.table_data = self.caccount.read_alldfile() self.setTableview( self.table_data ) #calculate and show single amount self.eachamount = self.sumEachamount( self.table_data ) self.setEachamount( self.eachamount ) #calculate single price amount self.eachpriceamount = [ self.eachamount[i]*self.list_price[i] for i in range(len(PRODUCT_NAME))] self.setEachpriceamount( self.eachpriceamount ) #show in total income self.spinBox_19.setValue( sum(self.eachpriceamount ) ) def setPricespin( self, list ): self.spinBox_1.setValue( list[0] ) self.spinBox_2.setValue( list[1] ) self.spinBox_3.setValue( list[2] ) self.spinBox_4.setValue( list[3] ) self.spinBox_5.setValue( list[4] ) self.spinBox_6.setValue( list[5] ) def setEachamount( self, list ): self.spinBox_7.setValue( list[0] ) self.spinBox_8.setValue( list[1] ) self.spinBox_9.setValue( list[2] ) self.spinBox_10.setValue( list[3] ) self.spinBox_11.setValue( list[4] ) self.spinBox_12.setValue( list[5] ) def setEachpriceamount(self, list ): self.spinBox_13.setValue( list[0] ) self.spinBox_14.setValue( list[1] ) self.spinBox_15.setValue( list[2] ) self.spinBox_16.setValue( list[3] ) self.spinBox_17.setValue( list[4] ) self.spinBox_18.setValue( list[5] ) #sum each item total amount def sumEachamount(self, duallist ): eachamount = [0, 0, 0, 0, 0, 0] count = 0 for i in duallist: for j in i: eachamount[count] += j count += 1 count = 0 return eachamount
def createCherryModel(self, data, parent): """Creates a model for the tableview using data retrieved from the cherry picking database. """ total = len(data) self.progressBar.setMaximum(total) self.progressBar.show() model = QStandardItemModel(0, len(CHERRY_COLUMNS), parent) for position, column in enumerate(CHERRY_COLUMNS): model.setHeaderData(position, Qt.Horizontal, column) # get additional data for each item keys = [item[CHERRY_COLUMNS.index("Key")] for item in data] itemIds = [] missing = [] itemIdsAll = dict((v, k) for k, v in self.itemIdsAll.iteritems()) for key in keys: if key in itemIdsAll: itemIds.append(itemIdsAll[key]) else: missing.append(key) if len(missing): msg = ("Keys exist in cherry picking database but absent " "in Bionumerics {0}".format(", ".join(missing))) self.mkWarn(msg) if not len(itemIds): msg = "No entries in cherry picking database" self.statusBar().showMessage(msg, 5000) self.mkInfo(msg) return None itemIds = list(set(itemIds)) (dnaData, noData, errors) = lims.GetNewestDNAForCherryPicking(itemIds) if len(noData): msg = ", ".join(str(item) for item in noData) self.mkWarn("{0}: {1}".format("No DNA's for these strains", msg)) if len(errors): msg = ", ".join(errors) self.mkError(msg) for count, result in enumerate(data): result = list(result) key = result[0] if key in itemIdsAll: self.progressBar.setValue(count) #QApplication.processEvents() parentID = itemIdsAll[key] if parentID in dnaData: properties = dnaData[parentID] for value in ("ItemName", "DNA concentration", "Volume", "Freezer", "Rack", "Shelf", "PlateRack", "Position"): if value in properties: result.append(properties[value]) else: result.append("") self.addCherryData(model, result) return model
"Monty": "The Circus", "David": "Oslo"} model = QStandardItemModel(6, 4) row = 0 for name, address in phonebook.items(): model.setData(model.index(row, 0), QVariant(name)) model.setData(model.index(row, 1), QVariant(address)) font = QFont() font.setPointSize(16) font.setBold(True) model.setData(model.index(row, 0), QVariant(font), Qt.FontRole) model.setData(model.index(row, 1), QVariant(font), Qt.FontRole) row += 1 model.setHeaderData(0, Qt.Horizontal, QVariant("Name")) model.setHeaderData(1, Qt.Horizontal, QVariant("Address")) tree = QTreeView() tree.setModel(model) tree.show() table = QTableView() table.setModel(model) table.show() sys.exit(app.exec_())
class GmApp(QMainWindow): def __init__(self): super(QMainWindow, self).__init__() self.setWindowTitle("GuloMail by GulonSoft") self.setWindowIcon(QIcon("g-square.png")) self.createActions() self.createStatusBar() self.createMenus() self.createToolbars() self.createWidgets() self.createLayouts() def createActions(self): self.newAction=QAction("&New", self, shortcut=QKeySequence.New, statusTip="New") self.sendReceiveAction=QAction("Send / &Receive", self, shortcut="F9", statusTip="Send / Receive") self.printAction=QAction("&Print...", self, shortcut="Ctrl+P", statusTip="Print") self.quitAction=QAction("&Quit", self, shortcut="Ctrl+Q", statusTip="Quit", triggered=self.close) self.copyAction=QAction("&Copy", self, statusTip="Copy", shortcut=QKeySequence.Copy) self.deleteAction=QAction("&Delete", self, statusTip="Delete Message") self.nextAction=QAction("Next &Unread Message", self, shortcut="Ctrl+]", statusTip="Next unread message") self.previousAction=QAction("P&revious Unread Message", self, shortcut="Ctrl+[", statusTip="Previous unread message") self.replyAction=QAction("&Reply", self, shortcut="Ctrl+R", statusTip="Reply to sender", triggered=self.reply) self.replyToAllAction=QAction("Reply to &All", self, shortcut="Ctrl+Shift+R", statusTip="Reply to all", triggered=self.replyToAll) self.forwardAction=QAction("&Forward", self, shortcut="Ctrl+F", statusTip="Forward") self.junkAction=QAction("Junk", self, shortcut="Ctrl+J", statusTip="Mark as Junk") self.notJunkAction=QAction("Not junk", self, shortcut="Shift+Ctrl+J", statusTip="Mark as Not Junk") self.contentsAction=QAction("&Contents", self, statusTip="Help Contents", shortcut="F1", triggered=self.helpContents) self.aboutAction=QAction("&About", self, statusTip="About GuloMail", triggered=self.about) self.cancelAction=QAction("&Cancel", self, statusTip="Cancel") def createStatusBar(self): self.statusBar() def createMenus(self): self.fileMenu=self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.sendReceiveAction) self.fileMenu.addAction(self.printAction) self.fileMenu.addAction(self.quitAction) self.editMenu=self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.copyAction) self.editMenu.addAction(self.deleteAction) self.viewMenu=self.menuBar().addMenu("&View") self.folderMenu=self.menuBar().addMenu("F&older") self.messageMenu=self.menuBar().addMenu("&Message") self.goToMenu=self.messageMenu.addMenu("&Go To") self.goToMenu.addAction(self.nextAction) self.goToMenu.addAction(self.previousAction) self.messageMenu.addAction(self.replyAction) self.messageMenu.addAction(self.replyToAllAction) self.messageMenu.addAction(self.forwardAction) self.markAsMenu=self.messageMenu.addMenu("Mar&k as...") self.markAsMenu.addAction(self.junkAction) self.markAsMenu.addAction(self.notJunkAction) self.searchMenu=self.menuBar().addMenu("&Search") self.helpMenu=self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.contentsAction) self.helpMenu.addAction(self.aboutAction) def createToolbars(self): self.toolbar=self.addToolBar('Main Toolbar') self.toolbar.setMovable(False) self.toolbar.addAction(self.newAction) self.toolbar.addSeparator() self.toolbar.addAction(self.sendReceiveAction) self.toolbar.addSeparator() self.toolbar.addAction(self.replyAction) self.toolbar.addAction(self.replyToAllAction) self.toolbar.addAction(self.forwardAction) self.toolbar.addSeparator() self.toolbar.addAction(self.printAction) self.toolbar.addAction(self.deleteAction) self.toolbar.addAction(self.junkAction) self.toolbar.addAction(self.notJunkAction) self.toolbar.addAction(self.cancelAction) self.toolbar.addSeparator() self.toolbar.addAction(self.previousAction) self.toolbar.addAction(self.nextAction) def createWidgets(self): ## Message Table self.table=QTableView() self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setGridStyle(Qt.NoPen) self.model = QStandardItemModel(8, 3, self) self.model.setHeaderData(0, Qt.Horizontal, "From") self.model.setHeaderData(1, Qt.Horizontal, "Subject") self.model.setHeaderData(2, Qt.Horizontal, "Received") self.table.setModel(self.model) self.selectionModel = QItemSelectionModel(self.model) self.selectionModel.SelectionFlag=0x0020 self.table.setSelectionModel(self.selectionModel) self.table.horizontalHeader().setStretchLastSection(True) self.table.verticalHeader().setVisible(False) self.table.setSortingEnabled(True) self.table.setAlternatingRowColors(True) ## Folder Tree View self.folderTree=QTreeWidget() self.folderTree.setColumnCount(1) self.folderTree.setHeaderLabel(QString('Folders')) self.treeItem=QTreeWidgetItem() self.treeItem.setText(0, 'Folders') self.inbox=QTreeWidgetItem() self.inbox.setText(0, 'Inbox') self.deletedItems=QTreeWidgetItem() self.deletedItems.setText(0, 'Deleted Items') self.drafts=QTreeWidgetItem() self.drafts.setText(0, 'Drafts') self.junk=QTreeWidgetItem() self.junk.setText(0, 'Junk') self.outbox=QTreeWidgetItem() self.outbox.setText(0, 'Outbox') self.sent=QTreeWidgetItem() self.sent.setText(0, 'Sent') self.treeItem.addChild(self.inbox) self.treeItem.addChild(self.deletedItems) self.treeItem.addChild(self.drafts) self.treeItem.addChild(self.junk) self.treeItem.addChild(self.outbox) self.treeItem.addChild(self.sent) self.folderTree.addTopLevelItem(self.treeItem) self.folderTree.expandAll() self.folderTree.setAnimated(True) self.folderTree.setMaximumWidth(150) ## Temp. placeholders self.textEdit=QTextEdit() self.textEdit2=QTextEdit() def createLayouts(self): self.mainSplitter=QSplitter() self.setCentralWidget(self.mainSplitter) self.mainSplitter.addWidget(self.folderTree) self.messageSplitter=QSplitter(Qt.Vertical) self.messageSplitter.addWidget(self.table) self.messageSplitter.addWidget(self.textEdit2) self.mainSplitter.addWidget(self.messageSplitter) def helpContents(self): print "Help" def reply(self): print "Reply" def replyToAll(self): print "Reply To All" def about(self): text=QString("GuloMail v0.1\n\n") text.append("GuloMail is a freeware email client written in Python using PyQt4 (Python bindings for Nokia's Qt)\n\n") text.append(QChar(0x00A9)) text.append("GulonSoft 2010\nhttp://www.gulon.co.uk/") QMessageBox.about(self, "About GuloMail", text)
def _show_related_apis(self): self.switch_btn_apis.hide() self.switch_btn_mashups.hide() self.recommendLabel.hide() row = 0 objs = [] for mashup in self.related_mashups: objs.append(mashup) for api in mashup["related_mashups"]: objs.append(api) #Combining similarity and related. similar_apis = self.data_source.search_api_similarity(self.highlighted_api) #return str(mashup['id'])[(len("http://www.programmableweb.com/mashup/")):] objs.append({'id': "http://www.programmableweb.com/mashup/Using-Similarity-Metric"}) objs.extend(similar_apis) #Combining similarity and related. #http://localhost:9000/getReputation/John%20Lions model = QStandardItemModel(len(objs), 6) for obj in objs: if obj.get('protocols'): model.setData(model.index(row, 1), QVariant(get_api_name(obj))) model.setData(model.index(row, 2), QVariant(obj['protocols'])) model.setData(model.index(row, 3), QVariant(obj['provider'])) model.setData(model.index(row, 4), QVariant(obj['version'])) trust = requests.get('http://localhost:9000/getReputation/Luis Ramos').content #model.setData(model.index(row, 5), QVariant(str(random.random()))) model.setData(model.index(row, 5), QVariant(trust)) else: model.setData(model.index(row, 0), QVariant(get_mashup_name(obj))) row += 1 model.setHeaderData(0, Qt.Horizontal, QVariant("Mashup")) model.setHeaderData(1, Qt.Horizontal, QVariant("API")) model.setHeaderData(2, Qt.Horizontal, QVariant("Protocols")) model.setHeaderData(3, Qt.Horizontal, QVariant("Provider")) model.setHeaderData(4, Qt.Horizontal, QVariant("Version")) model.setHeaderData(5, Qt.Horizontal, QVariant("Trust")) self.table.setModel(model) self.table.resizeColumnsToContents() self.switch_btn_mashups.show()
class GmApp(QMainWindow): def __init__(self): super(QMainWindow, self).__init__() self.setWindowTitle("GuloMail by GulonSoft") self.setWindowIcon(QIcon("g-square.png")) self.createActions() self.createStatusBar() self.createMenus() self.createToolbars() self.createWidgets() self.createLayouts() def createActions(self): self.newAction = QAction("&New", self, shortcut=QKeySequence.New, statusTip="New") self.sendReceiveAction = QAction("Send / &Receive", self, shortcut="F9", statusTip="Send / Receive") self.printAction = QAction("&Print...", self, shortcut="Ctrl+P", statusTip="Print") self.quitAction = QAction("&Quit", self, shortcut="Ctrl+Q", statusTip="Quit", triggered=self.close) self.copyAction = QAction("&Copy", self, statusTip="Copy", shortcut=QKeySequence.Copy) self.deleteAction = QAction("&Delete", self, statusTip="Delete Message") self.nextAction = QAction("Next &Unread Message", self, shortcut="Ctrl+]", statusTip="Next unread message") self.previousAction = QAction("P&revious Unread Message", self, shortcut="Ctrl+[", statusTip="Previous unread message") self.replyAction = QAction("&Reply", self, shortcut="Ctrl+R", statusTip="Reply to sender", triggered=self.reply) self.replyToAllAction = QAction("Reply to &All", self, shortcut="Ctrl+Shift+R", statusTip="Reply to all", triggered=self.replyToAll) self.forwardAction = QAction("&Forward", self, shortcut="Ctrl+F", statusTip="Forward") self.junkAction = QAction("Junk", self, shortcut="Ctrl+J", statusTip="Mark as Junk") self.notJunkAction = QAction("Not junk", self, shortcut="Shift+Ctrl+J", statusTip="Mark as Not Junk") self.contentsAction = QAction("&Contents", self, statusTip="Help Contents", shortcut="F1", triggered=self.helpContents) self.aboutAction = QAction("&About", self, statusTip="About GuloMail", triggered=self.about) self.cancelAction = QAction("&Cancel", self, statusTip="Cancel") def createStatusBar(self): self.statusBar() def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.sendReceiveAction) self.fileMenu.addAction(self.printAction) self.fileMenu.addAction(self.quitAction) self.editMenu = self.menuBar().addMenu("&Edit") self.editMenu.addAction(self.copyAction) self.editMenu.addAction(self.deleteAction) self.viewMenu = self.menuBar().addMenu("&View") self.folderMenu = self.menuBar().addMenu("F&older") self.messageMenu = self.menuBar().addMenu("&Message") self.goToMenu = self.messageMenu.addMenu("&Go To") self.goToMenu.addAction(self.nextAction) self.goToMenu.addAction(self.previousAction) self.messageMenu.addAction(self.replyAction) self.messageMenu.addAction(self.replyToAllAction) self.messageMenu.addAction(self.forwardAction) self.markAsMenu = self.messageMenu.addMenu("Mar&k as...") self.markAsMenu.addAction(self.junkAction) self.markAsMenu.addAction(self.notJunkAction) self.searchMenu = self.menuBar().addMenu("&Search") self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.contentsAction) self.helpMenu.addAction(self.aboutAction) def createToolbars(self): self.toolbar = self.addToolBar('Main Toolbar') self.toolbar.setMovable(False) self.toolbar.addAction(self.newAction) self.toolbar.addSeparator() self.toolbar.addAction(self.sendReceiveAction) self.toolbar.addSeparator() self.toolbar.addAction(self.replyAction) self.toolbar.addAction(self.replyToAllAction) self.toolbar.addAction(self.forwardAction) self.toolbar.addSeparator() self.toolbar.addAction(self.printAction) self.toolbar.addAction(self.deleteAction) self.toolbar.addAction(self.junkAction) self.toolbar.addAction(self.notJunkAction) self.toolbar.addAction(self.cancelAction) self.toolbar.addSeparator() self.toolbar.addAction(self.previousAction) self.toolbar.addAction(self.nextAction) def createWidgets(self): ## Message Table self.table = QTableView() self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setGridStyle(Qt.NoPen) self.model = QStandardItemModel(8, 3, self) self.model.setHeaderData(0, Qt.Horizontal, "From") self.model.setHeaderData(1, Qt.Horizontal, "Subject") self.model.setHeaderData(2, Qt.Horizontal, "Received") self.table.setModel(self.model) self.selectionModel = QItemSelectionModel(self.model) self.selectionModel.SelectionFlag = 0x0020 self.table.setSelectionModel(self.selectionModel) self.table.horizontalHeader().setStretchLastSection(True) self.table.verticalHeader().setVisible(False) self.table.setSortingEnabled(True) self.table.setAlternatingRowColors(True) ## Folder Tree View self.folderTree = QTreeWidget() self.folderTree.setColumnCount(1) self.folderTree.setHeaderLabel(QString('Folders')) self.treeItem = QTreeWidgetItem() self.treeItem.setText(0, 'Folders') self.inbox = QTreeWidgetItem() self.inbox.setText(0, 'Inbox') self.deletedItems = QTreeWidgetItem() self.deletedItems.setText(0, 'Deleted Items') self.drafts = QTreeWidgetItem() self.drafts.setText(0, 'Drafts') self.junk = QTreeWidgetItem() self.junk.setText(0, 'Junk') self.outbox = QTreeWidgetItem() self.outbox.setText(0, 'Outbox') self.sent = QTreeWidgetItem() self.sent.setText(0, 'Sent') self.treeItem.addChild(self.inbox) self.treeItem.addChild(self.deletedItems) self.treeItem.addChild(self.drafts) self.treeItem.addChild(self.junk) self.treeItem.addChild(self.outbox) self.treeItem.addChild(self.sent) self.folderTree.addTopLevelItem(self.treeItem) self.folderTree.expandAll() self.folderTree.setAnimated(True) self.folderTree.setMaximumWidth(150) ## Temp. placeholders self.textEdit = QTextEdit() self.textEdit2 = QTextEdit() def createLayouts(self): self.mainSplitter = QSplitter() self.setCentralWidget(self.mainSplitter) self.mainSplitter.addWidget(self.folderTree) self.messageSplitter = QSplitter(Qt.Vertical) self.messageSplitter.addWidget(self.table) self.messageSplitter.addWidget(self.textEdit2) self.mainSplitter.addWidget(self.messageSplitter) def helpContents(self): print "Help" def reply(self): print "Reply" def replyToAll(self): print "Reply To All" def about(self): text = QString("GuloMail v0.1\n\n") text.append( "GuloMail is a freeware email client written in Python using PyQt4 (Python bindings for Nokia's Qt)\n\n" ) text.append(QChar(0x00A9)) text.append("GulonSoft 2010\nhttp://www.gulon.co.uk/") QMessageBox.about(self, "About GuloMail", text)