class OfflineDialog(QDialog): def __init__(self, parent=None): super(OfflineDialog, self).__init__(parent) self.pagetitle = 'Offline Back Up' stylesheet = Valid().background() + Valid().font() self.hold_data = {} self.tree = QTreeWidget() self.tree.setHeaderLabel("Choose Sessions to Back-up") self.tree.headerItem().setText(0, 'Name') #self.tree.setStyleSheet(treeStyleSheet) arr = Db().selectn('session','', 5) if arr and len(arr) > 0: for val in arr: child = QTreeWidgetItem(self.tree) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, str(val['name']).upper()) self.hold_data[val['id']] = child child.setCheckState(0, Qt.Checked) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Save") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Close") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(self.tree, 0, 0) grid.addWidget(groupBox2, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self)) self.setStyleSheet(stylesheet) #self.setWindowIcon(QIcon(self.titleIcon)) self.setWindowTitle(self.pagetitle) def button_close(self, a): a.close() def getSelected(self): k = [] for i in self.hold_data: if self.hold_data[i].checkState(0) == Qt.Checked: k.append(i) return k def button_click(self): session = self.getSelected() arr = [] g = Db() for a in session: arr.append('school_awards'+str(a)) arr.append('school_expenses'+str(a)) arr.append('school_mails'+str(a)) arr.append('school_medicals'+str(a)) arr.append('school_stores'+str(a)) terms = g.selectn('terms', '', '', {'sessionID': a}) for b in terms: arr.append('student_affective'+str(b['id'])) arr.append('student_class'+str(b['id'])) arr.append('student_fee'+str(b['id'])) arr.append('student_pay'+str(b['id'])) arr.append('student_psy'+str(b['id'])) arr.append('student_result'+str(b['id'])) arr.append('student_subject'+str(b['id'])) arr.append('session') arr.append('terms') arr.append('students') arr.append('datas') try: f = open('_temp/data.txt', "w") save_date = time.time() f.write('SAVED_DATE='+str(save_date)+'\n SAVED_TABLES='+str(arr)+'\n SAVED_IDS='+str(session)) f.close() except: pass for c in arr: try: df = g.selectPandas(c) df.to_csv('_temp/'+c+'.csv', index=False) except: pass fileName = QFileDialog.getSaveFileName(self, 'Save File as', '', '*.zip') achi_zip = zipfile.ZipFile(fileName+'.zip', 'w') for root, dirs, files in os.walk('_temp/'): for afile in files: achi_zip.write(os.path.join(root, afile), afile, compress_type = zipfile.ZIP_DEFLATED) achi_zip.close() #self.clearFolder() def clearFolder(self): folder = '_temp' for f in os.listdir(folder): f_path = os.path.join(folder, f) try: if os.path.isfile(f_path): os.unlink(f_path) except: pass
class OfflinerDialog(QDialog): def __init__(self, parent = None): super(OfflinerDialog, self).__init__(parent) self.pagetitle = 'Offline Restore' stylesheet = Valid().background() + Valid().font() fileName = QFileDialog.getOpenFileName(self, 'Save File as', '', '*.zip') achi_zip = zipfile.ZipFile(fileName) achi_zip.extractall('_temp') achi_zip.close() re = open('_temp/data.txt', 'r') arr_string = {} contents = re.readlines() for con in contents: r = con.split('=') arr_string[r[0].strip()] = r[1] #print(arr_string) list_dt = arr_string['SAVED_DATE'] damt = datetime.utcfromtimestamp(float(list_dt)).strftime('%d-%m-%Y, %H:%M:%S') #dt = self.sessions = ast.literal_eval(arr_string['SAVED_IDS']) self.list_data = ast.literal_eval(arr_string['SAVED_TABLES']) self.hold_data = {} self.tree = QTreeWidget() self.tree.setHeaderLabel("Choose Sessions to restore") self.tree.headerItem().setText(0, 'Choose Sessions') #self.tree.setStyleSheet(treeStyleSheet) for t in self.sessions: arr = Db().selectn('session', '', 1, {'id':t}) if arr and arr['id'] > 0: child = QTreeWidgetItem(self.tree) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, str(arr['name']).upper()) self.hold_data[arr['id']] = child child.setCheckState(0, Qt.Checked) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Restore") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Close") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) self.lbl = QLabel('Saved on the '+damt) grid = QGridLayout() grid.addWidget(self.lbl, 0, 0) grid.addWidget(self.tree, 1, 0) grid.addWidget(groupBox2, 2, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self)) self.setStyleSheet(stylesheet) #self.setWindowIcon(QIcon(self.titleIcon)) self.setWindowTitle(self.pagetitle) def button_close(self, a): a.close() def getSelected(self): k = [] for i in self.hold_data: if self.hold_data[i].checkState(0) == Qt.Checked: k.append(i) return k def button_click(self): g = Db() g.createDatas() g.createStudent() g.createSession() g.createTerm() for z in self.sessions: g.createExpenses(z) g.createStores(z) g.createAwards(z) g.createConducts(z) g.createMails(z) g.createMedicals(z) arr = g.selectn('terms', '', '', {'id':z}) for t1 in arr: t = t1['id'] g.createClass(t) g.createSubject(t) g.createFee(t) g.createPay(t) g.createResult(t) g.createAffective(t) g.createPsychomoto(t) for c in self.list_data: try: g.replacePandas(c) except: pass off = OfflineDialog() off.clearFolder()
class PluginWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.pluginMetadata = {} # Main layout self.mainLayout = QVBoxLayout() self.setLayout(self.mainLayout) # Define size used for the underlines self.underlineSize = QSize() self.underlineSize.setHeight(1) # Define font used for headers self.font = QFont() self.font.setPointSize(11) self.font.setBold(True) self.font.setUnderline(True) # Plugins Description self.pluginDescription = QLabel() self.pluginDescription.setText("Click a plugin to see more information." + " Plugins can be configured from the Recording tab. \n") self.pluginDescription.setWordWrap(True) # Plugins GroupBox self.pluginLayout = QVBoxLayout() self.pluginGroupBox = QGroupBox("Plugins extend the functionality of Freeseer") self.pluginGroupBox.setLayout(self.pluginLayout) self.pluginLayout.insertWidget(0, self.pluginDescription) self.mainLayout.insertWidget(0, self.pluginGroupBox) # Plugins list self.list = QTreeWidget() self.list.setHeaderHidden(True) self.list.headerItem().setText(0, "1") self.pluginLayout.insertWidget(1, self.list) # Details self.detailPane = QGroupBox() self.detailLayout = QVBoxLayout() self.detailPane.setLayout(self.detailLayout) self.detailPaneDesc = QLabel() self.detailPaneDesc.setWordWrap(True) self.detailLayout.addWidget(self.detailPaneDesc) self.pluginLayout.insertWidget(2, self.detailPane) self.list.itemSelectionChanged.connect(self.treeViewSelect) def treeViewSelect(self): item = self.list.currentItem() key = str(item.text(0)) if key in self.pluginMetadata.keys(): self.showDetails(key) else: self.hideDetails() def showDetails(self, key): self.detailPane.setTitle(key) self.detailPaneDesc.setText(self.pluginMetadata[key]) self.detailPane.show() def hideDetails(self): self.detailPane.hide() def getWidgetPlugin(self, plugin, plugin_category, plugman): plugin_name = plugin.plugin_object.get_name() item = QTreeWidgetItem() # Display Plugin's meta data in a tooltip pluginDetails = """ <table> <tr> <td>Name: </td> <td><b>%(name)s</b></td> </tr> <tr> <td>Version: </td> <td><b>%(version)s</b></td> <tr> <td>Author: </td> <td><b>%(author)s</b></td> </tr> <tr> <td>Website: </td> <td><b>%(website)s</b></td> </tr> <tr> <td>Description: </td> <td><b>%(description)s</b></td> </tr> </table> """ % {"name": plugin.name, "version": plugin.version, "author": plugin.author, "website": plugin.website, "description": plugin.description} # put the details in the hash table self.pluginMetadata[plugin_name] = pluginDetails item.setText(0, plugin_name) return item
class Main(plugin.Plugin): " Main Class " def initialize(self, *args, **kwargs): " Init Main Class " super(Main, self).initialize(*args, **kwargs) self.scriptPath, self.scriptArgs = "", [] self.profilerPath, self.tempPath = profilerPath, tempPath self.output = " ERROR: FAIL: No output ! " self.process = QProcess() self.process.finished.connect(self.on_process_finished) self.process.error.connect(self.on_process_error) self.tabWidget, self.stat = QTabWidget(), QWidget() self.tabWidget.tabCloseRequested.connect( lambda: self.tabWidget.setTabPosition(1) if self.tabWidget. tabPosition() == 0 else self.tabWidget.setTabPosition(0)) self.tabWidget.setStyleSheet('QTabBar{font-weight:bold;}') self.tabWidget.setMovable(True) self.tabWidget.setTabsClosable(True) self.vboxlayout1 = QVBoxLayout(self.stat) self.hboxlayout1 = QHBoxLayout() self.filterTableLabel = QLabel("<b>Type to Search : </b>", self.stat) self.hboxlayout1.addWidget(self.filterTableLabel) self.filterTableLineEdit = QLineEdit(self.stat) self.filterTableLineEdit.setPlaceholderText(' Type to Search . . . ') self.hboxlayout1.addWidget(self.filterTableLineEdit) self.filterHintTableLabel = QLabel(" ? ", self.stat) self.hboxlayout1.addWidget(self.filterHintTableLabel) self.vboxlayout1.addLayout(self.hboxlayout1) self.tableWidget = QTableWidget(self.stat) self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setColumnCount(8) self.tableWidget.setRowCount(2) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(2, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(3, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(4, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(5, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(6, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(7, item) self.tableWidget.itemDoubleClicked.connect( self.on_tableWidget_itemDoubleClicked) self.vboxlayout1.addWidget(self.tableWidget) self.tabWidget.addTab(self.stat, " ? ") self.source = QWidget() self.gridlayout = QGridLayout(self.source) self.scintillaWarningLabel = QLabel( "QScintilla is not installed!. Falling back to basic text edit!.", self.source) self.gridlayout.addWidget(self.scintillaWarningLabel, 1, 0, 1, 2) self.sourceTreeWidget = QTreeWidget(self.source) self.sourceTreeWidget.setAlternatingRowColors(True) self.sourceTreeWidget.itemActivated.connect( self.on_sourceTreeWidget_itemActivated) self.sourceTreeWidget.itemClicked.connect( self.on_sourceTreeWidget_itemClicked) self.sourceTreeWidget.itemDoubleClicked.connect( self.on_sourceTreeWidget_itemClicked) self.gridlayout.addWidget(self.sourceTreeWidget, 0, 0, 1, 1) self.sourceTextEdit = QTextEdit(self.source) self.sourceTextEdit.setReadOnly(True) self.gridlayout.addWidget(self.sourceTextEdit, 0, 1, 1, 1) self.tabWidget.addTab(self.source, " ? ") self.result = QWidget() self.vlayout = QVBoxLayout(self.result) self.globalStatGroupBox = QGroupBox(self.result) self.hboxlayout = QHBoxLayout(self.globalStatGroupBox) self.totalTimeLcdNumber = QLCDNumber(self.globalStatGroupBox) self.totalTimeLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.totalTimeLcdNumber.setNumDigits(7) self.totalTimeLcdNumber.display(1000000) self.totalTimeLcdNumber.setFrameShape(QFrame.StyledPanel) self.totalTimeLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.totalTimeLcdNumber) self.tTimeLabel = QLabel("<b>Total Time (Sec)</b>", self.globalStatGroupBox) self.tTimeLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.tTimeLabel) self.numCallLcdNumber = QLCDNumber(self.globalStatGroupBox) self.numCallLcdNumber.setNumDigits(7) self.numCallLcdNumber.display(1000000) self.numCallLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.numCallLcdNumber.setFrameShape(QFrame.StyledPanel) self.numCallLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.numCallLcdNumber) self.numCallLabel = QLabel("<b>Number of calls</b>", self.globalStatGroupBox) self.numCallLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.numCallLabel) self.primCallLcdNumber = QLCDNumber(self.globalStatGroupBox) self.primCallLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.primCallLcdNumber.setFrameShape(QFrame.StyledPanel) self.primCallLcdNumber.setNumDigits(7) self.primCallLcdNumber.display(1000000) self.primCallLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.primCallLcdNumber) self.primCallLabel = QLabel("<b>Primitive calls (%)</b>", self.globalStatGroupBox) self.primCallLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.primCallLabel) self.vlayout.addWidget(self.globalStatGroupBox) try: from PyKDE4.kdeui import KRatingWidget self.rating = KRatingWidget(self.globalStatGroupBox) self.rating.setToolTip('Profiling Performance Rating') except ImportError: pass self.tabWidget.addTab(self.result, " Get Results ! ") self.resgraph = QWidget() self.vlayout2 = QVBoxLayout(self.result) self.graphz = QGroupBox(self.resgraph) self.hboxlayout2 = QHBoxLayout(self.graphz) try: from PyKDE4.kdeui import KLed KLed(self.graphz) except ImportError: pass self.hboxlayout2.addWidget( QLabel(''' Work in Progress :) Not Ready Yet''')) self.vlayout2.addWidget(self.graphz) self.tabWidget.addTab(self.resgraph, " Graphs and Charts ") self.pathz = QWidget() self.vlayout3 = QVBoxLayout(self.pathz) self.patz = QGroupBox(self.pathz) self.hboxlayout3 = QVBoxLayout(self.patz) self.profilepath = QLineEdit(profilerPath) self.getprofile = QPushButton(QIcon.fromTheme("document-open"), 'Open') self.getprofile.setToolTip( 'Dont touch if you dont know what are doing') self.getprofile.clicked.connect(lambda: self.profilepath.setText( str( QFileDialog.getOpenFileName( self.patz, ' Open the profile.py file ', path.expanduser("~"), ';;(profile.py)')))) self.hboxlayout3.addWidget( QLabel( '<center><b>Profile.py Python Library Full Path:</b></center>') ) self.hboxlayout3.addWidget(self.profilepath) self.hboxlayout3.addWidget(self.getprofile) self.argGroupBox = QGroupBox(self.pathz) self.hbxlayout = QHBoxLayout(self.argGroupBox) self.argLineEdit = QLineEdit(self.argGroupBox) self.argLineEdit.setToolTip( 'Not touch if you dont know what are doing') self.argLineEdit.setPlaceholderText( 'Dont touch if you dont know what are doing') self.hbxlayout.addWidget( QLabel('<b>Additional Profile Arguments:</b>')) self.hbxlayout.addWidget(self.argLineEdit) self.hboxlayout3.addWidget(self.argGroupBox) self.vlayout3.addWidget(self.patz) self.tabWidget.addTab(self.pathz, " Paths and Configs ") self.outp = QWidget() self.vlayout4 = QVBoxLayout(self.outp) self.outgro = QGroupBox(self.outp) self.outgro.setTitle(" MultiProcessing Output Logs ") self.hboxlayout4 = QVBoxLayout(self.outgro) self.outputlog = QTextEdit() self.outputlog.setText(''' I do not fear computers, I fear the lack of them. -Isaac Asimov ''') self.hboxlayout4.addWidget(self.outputlog) self.vlayout4.addWidget(self.outgro) self.tabWidget.addTab(self.outp, " Logs ") self.actionNew_profiling = QAction(QIcon.fromTheme("document-new"), 'New Profiling', self) self.actionLoad_profile = QAction(QIcon.fromTheme("document-open"), 'Open Profiling', self) self.actionClean = QAction(QIcon.fromTheme("edit-clear"), 'Clean', self) self.actionClean.triggered.connect(lambda: self.clearContent) self.actionAbout = QAction(QIcon.fromTheme("help-about"), 'About', self) self.actionAbout.triggered.connect(lambda: QMessageBox.about( self.dock, __doc__, ', '.join( (__doc__, __license__, __author__, __email__)))) self.actionSave_profile = QAction(QIcon.fromTheme("document-save"), 'Save Profiling', self) self.actionManual = QAction(QIcon.fromTheme("help-contents"), 'Help', self) self.actionManual.triggered.connect(lambda: open_new_tab( 'http://docs.python.org/library/profile.html')) self.tabWidget.setCurrentIndex(2) self.globalStatGroupBox.setTitle("Global Statistics") item = self.tableWidget.horizontalHeaderItem(0) item.setText("Number of Calls") item = self.tableWidget.horizontalHeaderItem(1) item.setText("Total Time") item = self.tableWidget.horizontalHeaderItem(2) item.setText("Per Call") item = self.tableWidget.horizontalHeaderItem(3) item.setText("Cumulative Time") item = self.tableWidget.horizontalHeaderItem(4) item.setText("Per Call") item = self.tableWidget.horizontalHeaderItem(5) item.setText("Filename") item = self.tableWidget.horizontalHeaderItem(6) item.setText("Line") item = self.tableWidget.horizontalHeaderItem(7) item.setText("Function") self.tabWidget.setTabText(self.tabWidget.indexOf(self.stat), "Statistics per Function") self.sourceTreeWidget.headerItem().setText(0, "Source files") self.tabWidget.setTabText(self.tabWidget.indexOf(self.source), "Sources Navigator") ####################################################################### self.scrollable, self.dock = QScrollArea(), QDockWidget() self.scrollable.setWidgetResizable(True) self.scrollable.setWidget(self.tabWidget) self.dock.setWindowTitle(__doc__) self.dock.setStyleSheet('QDockWidget::title{text-align: center;}') self.dock.setWidget(self.scrollable) QToolBar(self.dock).addActions( (self.actionNew_profiling, self.actionClean, self.actionSave_profile, self.actionLoad_profile, self.actionManual, self.actionAbout)) self.actionNew_profiling.triggered.connect( self.on_actionNew_profiling_triggered) self.actionLoad_profile.triggered.connect( self.on_actionLoad_profile_triggered) self.actionSave_profile.triggered.connect( self.on_actionSave_profile_triggered) self.locator.get_service('misc').add_widget( self.dock, QIcon.fromTheme("document-open-recent"), __doc__) if QSCI: # Scintilla source editor management self.scintillaWarningLabel.setText(' QScintilla is Ready ! ') layout = self.source.layout() layout.removeWidget(self.sourceTextEdit) self.sourceTextEdit = Qsci.QsciScintilla(self.source) layout.addWidget(self.sourceTextEdit, 0, 1) doc = self.sourceTextEdit doc.setLexer(Qsci.QsciLexerPython(self.sourceTextEdit)) doc.setReadOnly(True) doc.setEdgeMode(Qsci.QsciScintilla.EdgeLine) doc.setEdgeColumn(80) doc.setEdgeColor(QColor("#FF0000")) doc.setFolding(Qsci.QsciScintilla.BoxedTreeFoldStyle) doc.setBraceMatching(Qsci.QsciScintilla.SloppyBraceMatch) doc.setCaretLineVisible(True) doc.setMarginLineNumbers(1, True) doc.setMarginWidth(1, 25) doc.setTabWidth(4) doc.setEolMode(Qsci.QsciScintilla.EolUnix) self.marker = {} for color in COLORS: mnr = doc.markerDefine(Qsci.QsciScintilla.Background) doc.setMarkerBackgroundColor(color, mnr) self.marker[color] = mnr self.currentSourcePath = None # Connect table and tree filter edit signal to unique slot self.filterTableLineEdit.textEdited.connect( self.on_filterLineEdit_textEdited) # Timer to display filter hint message self.filterHintTimer = QTimer(self) self.filterHintTimer.setSingleShot(True) self.filterHintTimer.timeout.connect(self.on_filterHintTimer_timeout) # Timer to start search self.filterSearchTimer = QTimer(self) self.filterSearchTimer.setSingleShot(True) self.filterSearchTimer.timeout.connect( self.on_filterSearchTimer_timeout) self.tabLoaded = {} for i in range(10): self.tabLoaded[i] = False self.backgroundTreeMatchedItems = {} self.resizeWidgetToContent(self.tableWidget) def on_actionNew_profiling_triggered(self): self.clearContent() self.scriptPath = str( QFileDialog.getOpenFileName(self.dock, "Choose your script to profile", path.expanduser("~"), "Python (*.py *.pyw)")) commandLine = [ self.profilerPath, "-o", self.tempPath, self.scriptPath ] + self.scriptArgs commandLine = " ".join(commandLine) ##if self.termCheckBox.checkState() == Qt.Checked: #termList = ["xterm", "aterm"] #for term in termList: #termPath = which(term) #if termPath: #break #commandLine = """%s -e "%s ; echo 'Press ENTER Exit' ; read" """ \ #% (termPath, commandLine) self.process.start(commandLine) if not self.process.waitForStarted(): print((" ERROR: {} failed!".format(commandLine))) return def on_process_finished(self, exitStatus): ' whan the process end ' print((" INFO: OK: QProcess is %s" % self.process.exitCode())) self.output = self.process.readAll().data() if not self.output: self.output = " ERROR: FAIL: No output ! " self.outputlog.setText(self.output + str(self.process.exitCode())) if path.exists(self.tempPath): self.setStat(self.tempPath) remove(self.tempPath) else: self.outputlog.setText(" ERROR: QProcess FAIL: Profiling failed.") self.tabWidget.setCurrentIndex(2) def on_process_error(self, error): ' when the process fail, I hope you never see this ' print(" ERROR: QProcess FAIL: Profiler Dead, wheres your God now ? ") if error == QProcess.FailedToStart: self.outputlog.setText(" ERROR: FAIL: Profiler execution failed ") elif error == QProcess.Crashed: self.outputlog.setText(" ERROR: FAIL: Profiler execution crashed ") else: self.outputlog.setText(" ERROR: FAIL: Profiler unknown error ") def on_actionLoad_profile_triggered(self): """Load a previous profile sessions""" statPath = str( QFileDialog.getOpenFileName(self.dock, "Open profile dump", path.expanduser("~"), "Profile file (*)")) if statPath: self.clearContent() print(' INFO: OK: Loading profiling from ' + statPath) self.setStat(statPath) def on_actionSave_profile_triggered(self): """Save a profile sessions""" statPath = str( QFileDialog.getSaveFileName(self.dock, "Save profile dump", path.expanduser("~"), "Profile file (*)")) if statPath: #TODO: handle error case and give feelback to user print(' INFO: OK: Saving profiling to ' + statPath) self.stat.save(statPath) #=======================================================================# # Common parts # #=======================================================================# def on_tabWidget_currentChanged(self, index): """slot for tab change""" # Kill search and hint timer if running to avoid cross effect for timer in (self.filterHintTimer, self.filterSearchTimer): if timer.isActive(): timer.stop() if not self.stat: #No stat loaded, nothing to do return self.populateTable() self.populateSource() def on_filterLineEdit_textEdited(self, text): """slot for filter change (table or tree""" if self.filterSearchTimer.isActive(): # Already runnning, stop it self.filterSearchTimer.stop() # Start timer self.filterSearchTimer.start(300) def on_filterHintTimer_timeout(self): """Timeout to warn user about text length""" print("timeout") tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: label = self.filterHintTableLabel label.setText("Type > 2 characters to search") def on_filterSearchTimer_timeout(self): """timeout to start search""" tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: text = self.filterTableLineEdit.text() label = self.filterHintTableLabel edit = self.filterTableLineEdit widget = self.tableWidget else: print("Unknow tab for filterSearch timeout !") print(("do search for %s" % text)) if not len(text): # Empty keyword, just clean all if self.filterHintTimer.isActive(): self.filterHintTimer.stop() label.setText(" ? ") self.warnUSer(True, edit) self.clearSearch() return if len(text) < 2: # Don't filter if text is too short and tell it to user self.filterHintTimer.start(600) return else: if self.filterHintTimer.isActive(): self.filterHintTimer.stop() label.setText(" ? ") # Search self.clearSearch() matchedItems = [] if tab == TAB_FUNCTIONSTAT: # Find items matchedItems = widget.findItems(text, Qt.MatchContains) widget.setSortingEnabled(False) matchedRows = [item.row() for item in matchedItems] # Hide matched items header = widget.verticalHeader() for row in range(widget.rowCount()): if row not in matchedRows: header.hideSection(row) widget.setSortingEnabled(True) else: print(" Unknow tab for filterSearch timeout ! ") print(("got %s members" % len(matchedItems))) self.warnUSer(matchedItems, edit) self.resizeWidgetToContent(widget) def resizeWidgetToContent(self, widget): """Resize all columns according to content""" for i in range(widget.columnCount()): widget.resizeColumnToContents(i) def clearSearch(self): """Clean search result For table, show all items For tree, remove colored items""" tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: header = self.tableWidget.verticalHeader() if header.hiddenSectionCount(): for i in range(header.count()): if header.isSectionHidden(i): header.showSection(i) def clearContent(self): # Clear tabs self.tableWidget.clearContents() self.sourceTreeWidget.clear() # Reset LCD numbers for lcdNumber in (self.totalTimeLcdNumber, self.numCallLcdNumber, self.primCallLcdNumber): lcdNumber.display(1000000) # Reset stat self.pstat = None # Disable save as menu self.actionSave_profile.setEnabled(False) # Mark all tabs as unloaded for i in range(10): self.tabLoaded[i] = False def warnUSer(self, result, inputWidget): palette = inputWidget.palette() if result: palette.setColor(QPalette.Normal, QPalette.Base, QColor(255, 255, 255)) else: palette.setColor(QPalette.Normal, QPalette.Base, QColor(255, 136, 138)) inputWidget.setPalette(palette) inputWidget.update() def setStat(self, statPath): self.stat = Stat(path=statPath) # Global stat update self.totalTimeLcdNumber.display(self.stat.getTotalTime()) self.numCallLcdNumber.display(self.stat.getCallNumber()) self.primCallLcdNumber.display(self.stat.getPrimitiveCallRatio()) # Refresh current tab self.on_tabWidget_currentChanged(self.tabWidget.currentIndex()) # Activate save as menu self.actionSave_profile.setEnabled(True) try: self.rating.setMaxRating(10) self.rating.setRating( int(self.stat.getPrimitiveCallRatio()) / 10 - 1) except: pass #========================================================================# # Statistics table # #=======================================================================# def populateTable(self): row = 0 rowCount = self.stat.getStatNumber() progress = QProgressDialog("Populating statistics table...", "Abort", 0, 2 * rowCount) self.tableWidget.setSortingEnabled(False) self.tableWidget.setRowCount(rowCount) progress.setWindowModality(Qt.WindowModal) for (key, value) in self.stat.getStatItems(): #ncalls item = StatTableWidgetItem(str(value[0])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_NCALLS, item) colorTableItem(item, self.stat.getCallNumber(), value[0]) #total time item = StatTableWidgetItem(str(value[2])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_TTIME, item) colorTableItem(item, self.stat.getTotalTime(), value[2]) #per call (total time) if value[0] != 0: tPerCall = str(value[2] / value[0]) cPerCall = str(value[3] / value[0]) else: tPerCall = "" cPerCall = "" item = StatTableWidgetItem(tPerCall) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_TPERCALL, item) colorTableItem( item, 100.0 * self.stat.getTotalTime() / self.stat.getCallNumber(), tPerCall) #per call (cumulative time) item = StatTableWidgetItem(cPerCall) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_CPERCALL, item) colorTableItem( item, 100.0 * self.stat.getTotalTime() / self.stat.getCallNumber(), cPerCall) #cumulative time item = StatTableWidgetItem(str(value[3])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_CTIME, item) colorTableItem(item, self.stat.getTotalTime(), value[3]) #Filename self.tableWidget.setItem(row, STAT_FILENAME, StatTableWidgetItem(str(key[0]))) #Line item = StatTableWidgetItem(str(key[1])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_LINE, item) #Function name self.tableWidget.setItem(row, STAT_FUNCTION, StatTableWidgetItem(str(key[2]))) row += 1 # Store it in stat hash array self.stat.setStatLink(item, key, TAB_FUNCTIONSTAT) progress.setValue(row) if progress.wasCanceled(): return for i in range(self.tableWidget.rowCount()): progress.setValue(row + i) for j in range(self.tableWidget.columnCount()): item = self.tableWidget.item(i, j) if item: item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setSortingEnabled(True) self.resizeWidgetToContent(self.tableWidget) progress.setValue(2 * rowCount) def on_tableWidget_itemDoubleClicked(self, item): matchedItems = [] filename = str(self.tableWidget.item(item.row(), STAT_FILENAME).text()) if not filename or filename.startswith("<"): # No source code associated, return immediatly return function = self.tableWidget.item(item.row(), STAT_FUNCTION).text() line = self.tableWidget.item(item.row(), STAT_LINE).text() self.on_tabWidget_currentChanged(TAB_SOURCE) # load source tab function = "%s (%s)" % (function, line) fathers = self.sourceTreeWidget.findItems(filename, Qt.MatchContains, SOURCE_FILENAME) print(("find %s father" % len(fathers))) for father in fathers: findItems(father, function, SOURCE_FILENAME, matchedItems) print(("find %s items" % len(matchedItems))) if matchedItems: self.tabWidget.setCurrentIndex(TAB_SOURCE) self.sourceTreeWidget.scrollToItem(matchedItems[0]) self.on_sourceTreeWidget_itemClicked(matchedItems[0], SOURCE_FILENAME) matchedItems[0].setSelected(True) else: print("oups, item found but cannot scroll to it !") #=======================================================================# # Source explorer # #=====================================================================# def populateSource(self): items = {} for stat in self.stat.getStatKeys(): source = stat[0] function = "%s (%s)" % (stat[2], stat[1]) if source in ("", "profile") or source.startswith("<"): continue # Create the function child child = QTreeWidgetItem([function]) # Store it in stat hash array self.stat.setStatLink(child, stat, TAB_SOURCE) if source in items: father = items[source] else: # Create the father father = QTreeWidgetItem([source]) items[source] = father father.addChild(child) self.sourceTreeWidget.setSortingEnabled(False) for value in list(items.values()): self.sourceTreeWidget.addTopLevelItem(value) self.sourceTreeWidget.setSortingEnabled(True) def on_sourceTreeWidget_itemActivated(self, item, column): self.on_sourceTreeWidget_itemClicked(item, column) def on_sourceTreeWidget_itemClicked(self, item, column): line = 0 parent = item.parent() if QSCI: doc = self.sourceTextEdit if parent: pathz = parent.text(column) result = match("(.*) \(([0-9]+)\)", item.text(column)) if result: try: function = str(result.group(1)) line = int(result.group(2)) except ValueError: # We got garbage... falling back to line 0 pass else: pathz = item.text(column) pathz = path.abspath(str(pathz)) if self.currentSourcePath != pathz: # Need to load source self.currentSourcePath == pathz try: if QSCI: doc.clear() doc.insert(file(pathz).read()) else: self.sourceTextEdit.setPlainText(file(pathz).read()) except IOError: QMessageBox.warning(self, "Error", "Source file could not be found", QMessageBox.Ok) return if QSCI: for function, line in [(i[2], i[1]) for i in self.stat.getStatKeys() if i[0] == pathz]: # expr, regexp, case sensitive, whole word, wrap, forward doc.findFirst("def", False, True, True, False, True, line, 0, True) end, foo = doc.getCursorPosition() time = self.stat.getStatTotalTime((pathz, line, function)) colorSource(doc, self.stat.getTotalTime(), time, line, end, self.marker) if QSCI: doc.ensureLineVisible(line)
class DictParameterWidget(GenericParameterWidget): """Widget class for DictParameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 3.1 :param parameter: A DictParameter object. :type parameter: DictParameter """ # pylint: disable=E1002 super(DictParameterWidget, self).__init__(parameter, parent) # pylint: enable=E1002 self.input = QTreeWidget() # generate tree model widget_items = self.generate_tree_model(self._parameter.value) self.input.addTopLevelItems(widget_items) # set header self.input.headerItem().setText(0, 'Keys') self.input.headerItem().setText(1, 'Values') self.inner_input_layout.addWidget(self.input) # override self._input_layout arrangement to make the label at the top # reset the layout self.input_layout.setParent(None) self.help_layout.setParent(None) self.label.setParent(None) self.inner_input_layout.setParent(None) self.input_layout = QVBoxLayout() self.input_layout.setSpacing(0) # put element into layout self.input_layout.addWidget(self.label) self.input_layout.addLayout(self.inner_input_layout) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) def generate_tree_model(self, data_dict): """Generate a tree model for specified dictionary :param data_dict: A dictionary :type data_dict: dict :return: list of QTreeWidgetItem :rtype list: """ widget_items = [] font = QFont() font.setBold(True) for key in data_dict.keys(): entry = data_dict[key] key_item = QTreeWidgetItem() key_item.setText(0, str(key)) key_item.setFont(0, font) if isinstance(entry, dict): items = self.generate_tree_model(entry) key_item.addChildren(items) else: # value_item = QTreeWidgetItem() key_item.setText(1, str(entry)) key_item.setFlags(key_item.flags() | Qt.ItemIsEditable) # key_item.addChild(key_item) widget_items.append(key_item) return widget_items def extract_dict(self, widget_items): """Extract dictionary key and values from QTreeWidgetItems :param widget_items: List of QTreeWidgetItems :type widget_items: list :return: hierarchical dictionary extracted from widget_items :rtype dict: """ data_dict = {} element_type = self._parameter.element_type if element_type == object: def object_cast(obj): return obj element_type = object_cast for key_item in widget_items: key = str(key_item.text(0)) value = None if key_item.childCount() == 0: # value_item = key_item.child(0) value = element_type(key_item.text(1)) elif key_item.childCount() > 1: value_items = [key_item.child(i) for i in range(key_item.childCount())] value = self.extract_dict(value_items) data_dict[key] = value return data_dict def get_parameter(self): """Obtain the parameter object from the current widget state. :returns: A DictParameter from the current state of widget """ root_widget_item = self.input.invisibleRootItem() widget_items = [root_widget_item.child(i) for i in range(root_widget_item.childCount())] data_dict = self.extract_dict(widget_items) self._parameter.value = data_dict return self._parameter
class CustomStaff(SymbolManager, QWidget): def __init__(self, dialog): QWidget.__init__(self, dialog) SymbolManager.__init__(self) self.setDefaultSymbolSize(40) self.dialog = dialog self.setLayout(QGridLayout()) self.tree = QTreeWidget() self.stack = QStackedWidget() StackFader(self.stack) self.systems = QSpinBox() newStaves = QVBoxLayout() operations = QHBoxLayout() self.layout().addLayout(newStaves, 0, 0) self.layout().addWidget(self.tree, 0, 1) self.layout().addWidget(self.stack, 0, 2, 1, 2) self.layout().addWidget(self.systems, 1, 3) self.systems.setRange(1, 64) l = QLabel(i18n("Systems per page:")) l.setBuddy(self.systems) self.layout().addWidget(l, 1, 2, Qt.AlignRight) self.layout().addLayout(operations, 1, 1) operations.setSpacing(0) operations.setContentsMargins(0, 0, 0, 0) removeButton = KPushButton(KStandardGuiItem.remove()) removeButton.clicked.connect(self.removeSelectedItems) operations.addWidget(removeButton) upButton = QToolButton() upButton.clicked.connect(self.moveSelectedItemsUp) upButton.setIcon(KIcon("go-up")) operations.addWidget(upButton) downButton = QToolButton() downButton.clicked.connect(self.moveSelectedItemsDown) downButton.setIcon(KIcon("go-down")) operations.addWidget(downButton) newStaves.setSpacing(0) newStaves.setContentsMargins(0, 0, 0, 0) self.tree.setIconSize(QSize(32, 32)) self.tree.setDragDropMode(QTreeWidget.InternalMove) self.tree.headerItem().setHidden(True) self.tree.itemSelectionChanged.connect(self.slotSelectionChanged) for staffType in ( BracketItem, BraceItem, StaffItem, ): b = QPushButton(staffType.name()) b.clicked.connect((lambda t: lambda: self.createItem(t))(staffType)) b.setIconSize(QSize(40, 40)) self.addSymbol(b, staffType.symbol()) newStaves.addWidget(b) def createItem(self, staffType): empty = self.tree.topLevelItemCount() == 0 items = self.tree.selectedItems() if len(items) == 1 and items[0].flags() & Qt.ItemIsDropEnabled: parent = items[0] else: parent = self.tree item = staffType(self, parent) if empty: item.setSelected(True) def slotSelectionChanged(self): items = self.tree.selectedItems() if items: self.stack.setCurrentWidget(items[0].widget) def moveSelectedItemsUp(self): items = self.tree.selectedItems() if items: item = items[0] # currently we support only one selected item parent = item.parent() or self.tree.invisibleRootItem() index = parent.indexOfChild(item) if index > 0: parent.takeChild(index) parent.insertChild(index - 1, item) self.tree.clearSelection() item.setSelected(True) item.setExpanded(True) def moveSelectedItemsDown(self): items = self.tree.selectedItems() if items: item = items[0] # currently we support only one selected item parent = item.parent() or self.tree.invisibleRootItem() index = parent.indexOfChild(item) if index < parent.childCount() - 1: parent.takeChild(index) parent.insertChild(index + 1, item) self.tree.clearSelection() item.setSelected(True) item.setExpanded(True) def removeSelectedItems(self): for item in self.tree.selectedItems(): item.remove() def systemCount(self): return self.systems.value() def name(self): return i18n("Custom Staff") def default(self): while self.tree.topLevelItemCount(): self.tree.topLevelItem(0).remove() self.systems.setValue(4) def items(self): for i in range(self.tree.topLevelItemCount()): yield self.tree.topLevelItem(i) def music(self, layout): music = sum((i.music(layout) for i in self.items()), ['<<']) music.append('>>') return music def staffCount(self): return sum(i.staffCount() for i in self.items())
class DictParameterWidget(GenericParameterWidget): """Widget class for DictParameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 3.1 :param parameter: A DictParameter object. :type parameter: DictParameter """ # pylint: disable=E1002 super(DictParameterWidget, self).__init__(parameter, parent) # pylint: enable=E1002 self._input = QTreeWidget() # generate tree model widget_items = self.generate_tree_model(self._parameter.value) self._input.addTopLevelItems(widget_items) # set header self._input.headerItem().setText(0, 'Keys') self._input.headerItem().setText(1, 'Values') self._inner_input_layout.addWidget(self._input) # override self._input_layout arrangement to make the label at the top # reset the layout self._input_layout.setParent(None) self._help_layout.setParent(None) self._label.setParent(None) self._inner_input_layout.setParent(None) self._input_layout = QVBoxLayout() self._input_layout.setSpacing(0) # put element into layout self._input_layout.addWidget(self._label) self._input_layout.addLayout(self._inner_input_layout) self._main_layout.addLayout(self._input_layout) self._main_layout.addLayout(self._help_layout) def generate_tree_model(self, data_dict): """Generate a tree model for specified dictionary :param data_dict: A dictionary :type data_dict: dict :return: list of QTreeWidgetItem :rtype list: """ widget_items = [] font = QFont() font.setBold(True) for key in data_dict.keys(): entry = data_dict[key] key_item = QTreeWidgetItem() key_item.setText(0, str(key)) key_item.setFont(0, font) if isinstance(entry, dict): items = self.generate_tree_model(entry) key_item.addChildren(items) else: # value_item = QTreeWidgetItem() key_item.setText(1, str(entry)) key_item.setFlags(key_item.flags() | Qt.ItemIsEditable) # key_item.addChild(key_item) widget_items.append(key_item) return widget_items def extract_dict(self, widget_items): """Extract dictionary key and values from QTreeWidgetItems :param widget_items: List of QTreeWidgetItems :type widget_items: list :return: hierarchical dictionary extracted from widget_items :rtype dict: """ data_dict = {} element_type = self._parameter.element_type if element_type == object: def object_cast(obj): return obj element_type = object_cast for key_item in widget_items: key = str(key_item.text(0)) value = None if key_item.childCount() == 0: # value_item = key_item.child(0) value = element_type(key_item.text(1)) elif key_item.childCount() > 1: value_items = [key_item.child(i) for i in range(key_item.childCount())] value = self.extract_dict(value_items) data_dict[key] = value return data_dict def get_parameter(self): """Obtain the parameter object from the current widget state. :returns: A DictParameter from the current state of widget """ root_widget_item = self._input.invisibleRootItem() widget_items = [root_widget_item.child(i) for i in range(root_widget_item.childCount())] data_dict = self.extract_dict(widget_items) self._parameter.value = data_dict return self._parameter
class DAyarlar(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(600, 375) self.gridLayout = QGridLayout(self) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.treeWidget = QTreeWidget(self) self.treeWidget.setMaximumSize(200, 1500) self.virux = QTreeWidgetItem(self.treeWidget) self.virux.setExpanded(True) icon = QIcon() icon.addPixmap(QPixmap("data/logo.png"), QIcon.Normal, QIcon.On) self.virux.setIcon(0, icon) item_1 = QTreeWidgetItem(self.virux) item_1 = QTreeWidgetItem(self.virux) self.dialog = QTreeWidgetItem(self.treeWidget) self.dialog.setExpanded(True) item_1 = QTreeWidgetItem(self.dialog) item_1 = QTreeWidgetItem(self.dialog) self.treeWidget.header().setVisible(False) self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1) self.groupBox = QGroupBox(self) self.groupBox.setFlat(True) self.gridLayout_3 = QGridLayout(self.groupBox) self.gridLayout_3.setMargin(0) self.gridLayout_3.setSpacing(0) self.widget = QWidget(self.groupBox) self.gridLayout_4 = QGridLayout(self.widget) self.gridLayout_4.setMargin(0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setMargin(0) spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 0, 0, 1, 1) self.gridLayout_3.addWidget(self.widget, 0, 0, 1, 1) self.gridLayout.addWidget(self.groupBox, 0, 1, 1, 1) self.pButton = QPushButton(self) self.pButton.setText("asd") self.pButton.setDefault(True) self.buttonBox = QDialogButtonBox(self) self.buttonBox.addButton(self.pButton, QDialogButtonBox.AcceptRole) #self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 2) self.setWindowTitle("Virux Ayarlar") self.treeWidget.headerItem().setText(0, "") self.treeWidget.topLevelItem(0).setText(0, u"Virux") self.treeWidget.topLevelItem(0).child(0).setText(0, u"Virux1") self.treeWidget.topLevelItem(0).child(1).setText(0, u"Virux2") self.treeWidget.topLevelItem(1).setText(0, u"Dialog") self.treeWidget.topLevelItem(1).child(0).setText(0, u"Dialog1") self.treeWidget.topLevelItem(1).child(1).setText(0, u"Dialog2") self.groupBox.setTitle(u"GroupBox") self.groupYaz() self.treeWidget.itemPressed.connect(self.lale) def lale(self, item): print item self.groupBox.setTitle(item.text(0)) def groupYaz(self): for option in DOptions: if hasattr(option, "getOption"): #self.gridLayout_3.addWidget(option.getOption(), 0, 0, 1, 1) item = QTreeWidgetItem(self.dialog) a = option.getOption() if hasattr(a, "name"): item.setText(0, a.name) else: item.setText(0, "F**k") #self.gridLayout_3.addWidget(a, 0, 0, 1, 1)
class SettingsManager(QDialog): def __init__(self, num, n, parent=None): super(SettingsManager, self).__init__(parent) #main self.par = n title = Settingz().positions(num) self.titleID = title['id'] self.titleIDx = str(title['id']) + 'x' self.titlePage = title['page'] self.titleName = title['name'] self.titleSub = title['subID'] self.titleIcon = title['icon'] self.pagetitle = self.titlePage self.sessionMain = 0 #stylesheet stylesheet = Valid().background() + Valid().font() treeStyleSheet = Valid().treez() self.groupBox1 = QGroupBox(self.titleName) self.groupBox2 = QGroupBox('Add') #items self.tree = QTreeWidget() self.tree.setHeaderLabel("Choose " + self.titleName) self.tree.headerItem().setText(0, 'Name') self.tree.headerItem().setText(1, 'Abbrv.') self.tree.setStyleSheet(treeStyleSheet) self.makeTree() self.tree.setMinimumHeight(250) self.tree.clicked.connect(lambda: self.getSelection()) self.tree.itemClicked.connect(lambda state: self.getChecked(state)) #buttons #add nImg = Buttons().addButton() self.pb = QPushButton() self.pb.setFlat(True) self.pb.setIcon(QIcon(nImg)) self.pb.setMaximumHeight(30) self.pb.setMaximumWidth(30) nImg1 = Buttons().closeButton() self.pb1 = QPushButton() self.pb1.setFlat(True) self.pb1.setIcon(QIcon(nImg1)) self.pb1.setMaximumHeight(30) self.pb1.setMaximumWidth(30) nImg2 = Buttons().editButton() self.pb2 = QPushButton() self.pb2.setFlat(True) self.pb2.setIcon(QIcon(nImg2)) self.pb2.setMaximumHeight(30) self.pb2.setMaximumWidth(30) nImg3 = Buttons().deleteButton() self.pb3 = QPushButton() self.pb3.setFlat(True) self.pb3.setIcon(QIcon(nImg3)) self.pb3.setMaximumHeight(30) self.pb3.setMaximumWidth(30) nImg4 = Buttons().saveButton() self.pb4 = QPushButton() self.pb4.setFlat(True) self.pb4.setIcon(QIcon(nImg4)) self.pb4.setMaximumHeight(30) self.pb4.setMaximumWidth(30) nImg5 = Buttons().resetButton() self.pb5 = QPushButton() self.pb5.setFlat(True) self.pb5.setIcon(QIcon(nImg5)) self.pb5.setMaximumHeight(30) self.pb5.setMaximumWidth(30) nImg6 = Buttons().closeButton() self.pb6 = QPushButton() self.pb6.setFlat(True) self.pb6.setIcon(QIcon(nImg6)) self.pb6.setMaximumHeight(30) self.pb6.setMaximumWidth(30) nImg7 = Buttons().addButton() self.pb7 = QPushButton() self.pb7.setFlat(True) self.pb7.setIcon(QIcon(nImg7)) self.pb7.setMaximumHeight(30) self.pb7.setMaximumWidth(30) hbo = QHBoxLayout() hbo.addStretch() hbo.addWidget(self.pb1) hbo.addWidget(self.pb3) hbo.addWidget(self.pb2) hbo.addWidget(self.pb7) vbo = QVBoxLayout() vbo.addWidget(self.tree) vbo.addLayout(hbo) self.l1 = QLabel("Name") self.le1 = QLineEdit() self.le1.setObjectName("name") vals1 = Valid().fullText() self.le1.setValidator(vals1) self.le1.setPlaceholderText("Lowercase max 25 letters") self.l2 = QLabel("Abbrv") self.le2 = QLineEdit() self.le2.setObjectName("abbrv") vals2 = Valid().limitText() self.le2.setValidator(vals2) self.le2.setPlaceholderText("Lowercase max 5 letters") FormLayout = QFormLayout() FormLayout.addRow(self.l1, self.le1) FormLayout.addRow(self.l2, self.le2) Hlayout1 = QHBoxLayout() Hlayout1.addStretch() Hlayout1.addWidget(self.pb6) Hlayout1.addWidget(self.pb5) Hlayout1.addWidget(self.pb4) Hlayout1.addWidget(self.pb) Vlayout1 = QVBoxLayout() Vlayout1.addLayout(FormLayout) Vlayout1.addLayout(Hlayout1) self.groupBox1.setLayout(vbo) self.groupBox2.setLayout(Vlayout1) self.groupBox2.hide() self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_add()) #add self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close()) #close self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_edit()) #edit self.connect(self.pb3, SIGNAL("clicked()"), lambda: self.button_delete()) #delete self.connect(self.pb4, SIGNAL("clicked()"), lambda: self.button_save()) #save self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_reset()) #reset self.pb4.hide() self.pb7.hide() grid = QGridLayout() grid.addWidget(self.groupBox1, 0, 0) grid.addWidget(self.groupBox2, 1, 0) self.setLayout(grid) self.setStyleSheet(stylesheet) self.setWindowIcon(QIcon(self.titleIcon)) self.setWindowTitle(self.pagetitle) def makeTree(self): self.tree.clear() arr = Valid().pullData('datas', '', {'pubID': self.titleID}) self.hold_data = {} self.hold_mdata = {} self.hold_data_add = {} self.hold_data_add_item = {} if self.titleSub and self.titleSub > 0: if arr and len(arr) > 0: for val in arr: ch = Valid().pullData('datas', '', {'subID': val['id']}) child = QTreeWidgetItem(self.tree) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, str(val['name']).upper()) child.setText(1, str(val['abbrv']).upper()) self.hold_data[val['id']] = child self.hold_mdata[val['id']] = child if (val['active'] == 0): child.setCheckState(0, Qt.Checked) else: child.setCheckState(0, Qt.Unchecked) for va in ch: child1 = QTreeWidgetItem(child) child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable) child1.setText(0, str(va['name']).upper()) child1.setText(1, str(va['abbrv']).upper()) self.hold_data[va['id']] = child1 if (va['active'] == 0): child1.setCheckState(0, Qt.Checked) else: child1.setCheckState(0, Qt.Unchecked) child1 = QTreeWidgetItem(child) child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable) child1.setText(0, 'Add New Item') self.hold_data_add_item[val['id']] = child1 else: if arr and len(arr) > 0: for val in arr: child = QTreeWidgetItem(self.tree) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, str(val['name']).upper()) child.setText(1, str(val['abbrv']).upper()) self.hold_data[val['id']] = child if (val['active'] == 0): child.setCheckState(0, Qt.Checked) else: child.setCheckState(0, Qt.Unchecked) child = QTreeWidgetItem(self.tree) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, 'Add New') self.hold_data_add['addnew'] = child def getChecked(self, a): g = Db() for i in self.hold_data: if self.hold_data[i].checkState(0) == Qt.Checked: g.update('datas', {'active': 0}, {'id': i}) else: g.update('datas', {'active': 1}, {'id': i}) if self.titleID == 1: #if class was changed only reload class menu on main window self.par.menuStudent() self.par.dropdownStudent() def getSelected(self): r = None k = None for i in self.hold_data: if self.hold_data[i].isSelected(): r = i for j in self.hold_mdata: if self.hold_mdata[j].isSelected(): k = j if r and r > 0: if r == k: self.sessionMain = r else: self.sessionMain = 0 self.groupBox2.show() return r else: self.groupBox2.hide() def getSelection(self): self.le1.clear() self.le2.clear() if self.hold_data_add['addnew'].isSelected(): self.sessionMain = 0 self.groupBox2.setTitle('Add New') self.groupBox2.show() else: r = None for i in self.hold_data_add_item: if self.hold_data_add_item[i].isSelected(): r = i if r: self.sessionMain = r g = Db() v = g.selectn('datas', '', 1, {'id': r}) vname = str(v['name']).upper() self.groupBox2.setTitle('ADD ' + str(vname) + ' ITEM') self.groupBox2.show() else: self.groupBox2.setTitle('Add') self.groupBox2.hide() def setActive(self): g = Db() for i in self.hold_data: if self.hold_data[i].checkState(0) == Qt.Checked: g.update('datas', {'active': 0}, {'id': i}) else: g.update('datas', {'active': 1}, {'id': i}) def button_add(self): s1 = self.le1.text() s2 = self.le2.text() g = Db() try: if (len(s1) > 0) and (len(s2) > 0): if self.sessionMain == 0: y = { 'name': s1.lower(), 'abbrv': s2.lower(), 'pubID': self.titleID, 'active': 0 } else: y = { 'name': s1.lower(), 'abbrv': s2.lower(), 'subID': self.sessionMain, 'pubID': self.titleIDx, 'active': 0 } g.insert('datas', y) self.makeTree() self.button_reset() if self.titleID == 1: #if class was changed only relod class menu on main window self.par.menuStudent() self.par.dropdownStudent() else: pass except: pass def button_save(self): row = self.editrow s1 = self.le1.text() s2 = self.le2.text() g = Db() try: if (len(s1) > 0) and (len(s2) > 0) and row and row > 0: y = {'name': s1.lower(), 'abbrv': s2.lower(), 'active': 0} z = {'id': row} g.update('datas', y, z) self.makeTree() self.button_reset() if self.titleID == 1: #if class was changed only relod class menu on main window self.par.menuStudent() self.par.dropdownStudent() else: pass except: pass def button_delete(self): row = self.getSelected() g = Db() try: if row and row > 0: y = {'abbrv': '', 'active': 2} z = {'id': row} g.update('datas', y, z) self.makeTree() else: pass except: pass def button_reset(self): self.le1.clear() self.le2.clear() self.groupBox2.setTitle('Add') self.groupBox2.hide() self.pb.show() self.pb4.hide() self.sessionMain = 0 def button_edit(self): row = self.getSelected() self.sessionMain = 0 if row: self.groupBox2.setTitle('Edit') self.editrow = row g = Db() data = g.selectn('datas', '', 1, {'id': row}) if self.titleID == data['pubID']: self.sessionMain = 1 else: self.sessionMain = 0 try: self.le1.setText(data['name']) except: self.le1.setText('') try: self.le2.setText(data['abbrv']) except: self.le2.setText('') self.pb.hide() self.pb4.show() def button_close(self): self.close()
class SessionsManager(QDialog): def __init__(self, n, parent=None): super(SessionsManager, self).__init__(parent) self.par = n #main title = Settingz().positions(30) self.titleID = title['id'] self.titlePage = title['page'] self.titleName = title['name'] self.titleSub = title['subID'] self.titleIcon = title['icon'] self.pagetitle = self.titlePage #stylesheet stylesheet = Valid().background() + Valid().font() treeStyleSheet = Valid().treez() self.groupBox1 = QGroupBox(self.titleName) self.groupBox2 = QGroupBox('Add') #items self.tree = QTreeWidget() self.tree.setHeaderLabel("Choose " + self.titleName) #tree.setItemDelegate(Delegate()) self.tree.setItemDelegate(Delegates()) self.tree.headerItem().setText(0, 'Name') self.tree.setStyleSheet(treeStyleSheet) self.makeTree() self.tree.setMinimumHeight(250) self.tree.clicked.connect(lambda: self.getSelection()) self.tree.itemClicked.connect(lambda state: self.getChecked(state)) #buttons #add nImg = Buttons().addButton() self.pb = QPushButton() self.pb.setFlat(True) self.pb.setIcon(QIcon(nImg)) self.pb.setMaximumHeight(30) self.pb.setMaximumWidth(30) nImg1 = Buttons().closeButton() self.pb1 = QPushButton() self.pb1.setFlat(True) self.pb1.setIcon(QIcon(nImg1)) self.pb1.setMaximumHeight(30) self.pb1.setMaximumWidth(30) nImg2 = Buttons().editButton() self.pb2 = QPushButton() self.pb2.setFlat(True) self.pb2.setIcon(QIcon(nImg2)) self.pb2.setMaximumHeight(30) self.pb2.setMaximumWidth(30) nImg3 = Buttons().deleteButton() self.pb3 = QPushButton() self.pb3.setFlat(True) self.pb3.setIcon(QIcon(nImg3)) self.pb3.setMaximumHeight(30) self.pb3.setMaximumWidth(30) nImg4 = Buttons().saveButton() self.pb4 = QPushButton() self.pb4.setFlat(True) self.pb4.setIcon(QIcon(nImg4)) self.pb4.setMaximumHeight(30) self.pb4.setMaximumWidth(30) nImg5 = Buttons().resetButton() self.pb5 = QPushButton() self.pb5.setFlat(True) self.pb5.setIcon(QIcon(nImg5)) self.pb5.setMaximumHeight(30) self.pb5.setMaximumWidth(30) nImg6 = Buttons().closeButton() self.pb6 = QPushButton() self.pb6.setFlat(True) self.pb6.setIcon(QIcon(nImg6)) self.pb6.setMaximumHeight(30) self.pb6.setMaximumWidth(30) nImg7 = Buttons().addButton() self.pb7 = QPushButton() self.pb7.setFlat(True) self.pb7.setIcon(QIcon(nImg7)) self.pb7.setMaximumHeight(30) self.pb7.setMaximumWidth(30) hbo = QHBoxLayout() hbo.addStretch() hbo.addWidget(self.pb1) hbo.addWidget(self.pb3) hbo.addWidget(self.pb2) hbo.addWidget(self.pb7) vbo = QVBoxLayout() vbo.addWidget(self.tree) vbo.addLayout(hbo) self.l1 = QLabel("Name") self.le1 = QLineEdit() self.le1.setObjectName("name") vals1 = Valid().fullNum() self.le1.setValidator(vals1) self.le1.setPlaceholderText("Lowercase max 25 letters") self.fromLbl = QLabel("Starts") self.toLbl = QLabel("Ends") self.fromData = QDateEdit() self.toData = QDateEdit() currentDate = QDate() self.fromData.setDate(currentDate.currentDate()) self.fromData.setCalendarPopup(True) self.toData.setDate(currentDate.currentDate()) self.toData.setCalendarPopup(True) FormLayout = QFormLayout() FormLayout.addRow(self.l1, self.le1) FormLayout.addRow(self.fromLbl, self.fromData) FormLayout.addRow(self.toLbl, self.toData) Hlayout1 = QHBoxLayout() Hlayout1.addStretch() Hlayout1.addWidget(self.pb6) Hlayout1.addWidget(self.pb5) Hlayout1.addWidget(self.pb4) Hlayout1.addWidget(self.pb) Vlayout1 = QVBoxLayout() Vlayout1.addLayout(FormLayout) Vlayout1.addLayout(Hlayout1) self.groupBox1.setLayout(vbo) self.groupBox2.setLayout(Vlayout1) self.groupBox2.hide() self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_add()) #add self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close()) #close self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_edit()) #edit self.connect(self.pb3, SIGNAL("clicked()"), lambda: self.button_delete()) #delete self.connect(self.pb4, SIGNAL("clicked()"), lambda: self.button_save()) #save self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_reset()) #reset self.pb4.hide() self.pb7.hide() grid = QGridLayout() grid.addWidget(self.groupBox1, 0, 0) grid.addWidget(self.groupBox2, 1, 0) self.setLayout(grid) self.setStyleSheet(stylesheet) self.setWindowIcon(QIcon(self.titleIcon)) self.setWindowTitle(self.pagetitle) def makeTree(self): self.tree.clear() arr = Db().selectn('session', '', 5) self.hold_data = {} self.hold_mdata = {} self.hold_data_add = {} self.hold_data_add_item = {} current = time.time() if self.titleSub and self.titleSub > 0: if arr and len(arr) > 0: for val in arr: ch = Valid().pullData('terms', '', {'sessionID': val['id']}) child = QTreeWidgetItem(self.tree) child.setIcon(0, QIcon('icons.cfolder.png')) try: ts = int(float(val['start_date'])) except: ts = int(current) ts = datetime.utcfromtimestamp(ts).strftime('%d-%m-%Y') try: ts1 = int(float(val['end_date'])) except: ts1 = int(current) ts1 = datetime.utcfromtimestamp(ts1).strftime('%d-%m-%Y') child.setText( 0, str(val['name']).upper() + " - " + ts + " " + ts1) self.hold_mdata[val['id']] = child for va in ch: child1 = QTreeWidgetItem(child) child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable) try: ts2 = int(float(va['start_date'])) except: ts2 = int(current) ts2 = datetime.utcfromtimestamp(ts2).strftime( '%d-%m-%Y') try: ts3 = int(float(va['end_date'])) except: ts3 = int(current) ts3 = datetime.utcfromtimestamp(ts3).strftime( '%d-%m-%Y') child1.setText( 0, str(va['name']).upper() + " " + ts2 + " " + ts3) self.hold_data[va['id']] = child1 if (va['active'] == 1): child1.setCheckState(0, Qt.Checked) else: child1.setCheckState(0, Qt.Unchecked) child1 = QTreeWidgetItem(child) child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable) child1.setText(0, 'Add New Term') self.hold_data_add_item[val['id']] = child1 else: if arr and len(arr) > 0: for val in arr: child = QTreeWidgetItem(self.tree) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, str(val['name']).upper()) child.setText(1, str(val['abbrv']).upper()) self.hold_data[val['id']] = child if (val['active'] == 0): child.setCheckState(0, Qt.Checked) else: child.setCheckState(0, Qt.Unchecked) child = QTreeWidgetItem(self.tree) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, 'Add New Session') self.hold_data_add['addnew'] = child def getChecked(self, a): arr_hold = [] g = Db() for i in self.hold_data: if self.hold_data[i].checkState(0) == Qt.Checked: arr_hold.append(i) self.hold_data[i].setCheckState(0, Qt.Checked) g.update('terms', {'active': 0}, {'active': 1}) g.update('terms', {'active': 1}, {'id': i}) tt = g.selectn('terms', '', 1, {'id': i}) g.update('session', {'active': 0}, {'active': 1}) g.update('session', {'active': 1}, {'id': tt['sessionID']}) g.selectn('session', '', 1, {'id': tt['sessionID']}) else: self.hold_data[i].setCheckState(0, Qt.Unchecked) self.reloadTerm() def reloadTerm(self): session = self.par.activeTerm() activeTerm = str(session[1]) + ' SESSION ' + str(session[3]) + ' TERM' self.par.majorSession = session[2] self.par.lbl.setText(activeTerm) def getSelected(self): r = False self.sessionMain = False for i in self.hold_mdata: if self.hold_mdata[i].isSelected(): r = i if r and r > 0: self.groupBox2.show() self.sessionMain = True return r else: for i in self.hold_data: if self.hold_data[i].isSelected(): r = i if r and r > 0: self.sessionMain = False self.groupBox2.show() return r else: self.groupBox2.hide() def getSession(self): self.sessionID = None for i in self.hold_data_session: if self.hold_data_session[i].isSelected(): r = i if r and r > 0: self.sessionID = r def getSelection(self): self.le1.clear() currentDate = QDate() self.fromData.setDate(currentDate.currentDate()) self.toData.setDate(currentDate.currentDate()) self.sessionMain = False if self.hold_data_add['addnew'].isSelected(): self.groupBox2.setTitle('Add New') self.groupBox2.show() self.sessionMain = True self.sessionID = False else: self.sessionMain = False r = None for i in self.hold_data_add_item: if self.hold_data_add_item[i].isSelected(): r = i if r: g = Db() v = g.selectn('session', '', 1, {'id': r}) vname = str(v['name']).upper() + ' Session' self.groupBox2.setTitle('ADD ' + str(vname) + ' Term') self.sessionID = r self.groupBox2.show() else: self.groupBox2.setTitle('Add') self.sessionID = False self.groupBox2.hide() def setActive(self): g = Db() for i in self.hold_data: if self.hold_data[i].checkState(0) == Qt.Checked: g.update('datas', {'active': 0}, {'id': i}) else: g.update('datas', {'active': 1}, {'id': i}) def button_add(self): s1 = self.le1.text() _datef = self.fromData.date().toPyDate() _datef = time.mktime(_datef.timetuple()) _datee = self.toData.date().toPyDate() _datee = time.mktime(_datee.timetuple()) g = Db() if self.sessionID and self.sessionID > 0: try: if (len(s1) > 0): y = { 'name': s1.lower(), 'start_date': _datef, 'sessionID': self.sessionID, 'end_date': _datee, 'active': 0 } z = g.insert('terms', y) if z and z > 0: g.createClass(z) g.createSubject(z) g.createFee(z) g.createPay(z) g.createResult(z) g.createAffective(z) g.createPsychomoto(z) self.makeTree() self.button_reset() self.par.menuSession() self.par.dropdownSession() else: pass except: pass else: try: if (len(s1) > 0): y = { 'name': s1.lower(), 'start_date': _datef, 'end_date': _datee, 'active': 0 } z = g.insert('session', y) if z and z > 0: g.createExpenses(z) g.createStores(z) g.createAwards(z) g.createConducts(z) g.createMails(z) g.createMedicals(z) self.makeTree() self.button_reset() self.par.menuSession() self.par.dropdownSession() else: pass except: pass def button_save(self): row = self.editrow s1 = self.le1.text() _datef = self.fromData.date().toPyDate() _datef = time.mktime(_datef.timetuple()) _datee = self.toData.date().toPyDate() _datee = time.mktime(_datee.timetuple()) g = Db() if (len(s1) > 0) and row and row > 0: if self.sessionID and self.sessionID > 0: try: if (len(s1) > 0): y = { 'name': s1.lower(), 'start_date': _datef, 'sessionID': self.sessionID, 'end_date': _datee, 'active': 0 } k = {'id': row} g.update('terms', y, k) z = row if z and z > 0: g.createClass(z) g.createSubject(z) g.createFee(z) g.createPay(z) g.createResult(z) g.createAffective(z) g.createPsychomoto(z) self.makeTree() self.button_reset() self.par.menuSession() self.par.dropdownSession() else: pass except: pass else: try: if (len(s1) > 0): y = { 'name': s1.lower(), 'start_date': _datef, 'end_date': _datee, 'active': 0 } k = {'id': row} g.update('session', y, k) z = row if z and z > 0: g.createExpenses(z) g.createStores(z) g.createAwards(z) g.createConducts(z) g.createMails(z) g.createMedicals(z) self.makeTree() self.button_reset() self.par.menuSession() self.par.dropdownSession() else: pass except: pass def button_delete(self): row = self.getSelected() g = Db() try: if row and row > 0: y = {'abbrv': '', 'active': 2} z = {'id': row} g.update('datas', y, z) self.makeTree() else: pass except: pass def button_reset(self): self.le1.clear() currentDate = QDate() self.fromData.setDate(currentDate.currentDate()) self.toData.setDate(currentDate.currentDate()) self.groupBox2.setTitle('Add') self.groupBox2.hide() self.pb.show() self.pb4.hide() def button_edit(self): row = self.getSelected() currentDate = QDate() if row: self.editrow = row g = Db() if self.sessionMain: data = g.selectn('session', '', 1, {'id': row}) data_name = str(data['name']) self.groupBox2.setTitle('Edit') self.sessionID = False else: data = g.selectn('terms', '', 1, {'id': row}) data_sess = g.selectn('session', '', 1, {'id': data['sessionID']}) data_name = str(data['name']) self.sessionID = data['sessionID'] self.groupBox2.setTitle('Edit ' + str(data_sess['name'])) try: self.le1.setText(data_name) except: self.le1.setText('') try: self.fromData.setDate(data['start_date']) except: self.fromData.setDate(currentDate.currentDate()) try: self.toData.setDate(data['end_date']) except: self.toData.setDate(currentDate.currentDate()) self.pb.hide() self.pb4.show() def button_close(self): self.close()
class sub_canvas(MyMplCanvas): def __init__(self, *args, **kwargs): MyMplCanvas.__init__(self, *args, **kwargs) self.widget = QWidget(self) self.horizontalLayout = QHBoxLayout(self.widget) self.treeWidget = QTreeWidget(self.widget) self.horizontalLayout.addWidget(self.treeWidget) self.label_1 = QLabel(self.widget) self.horizontalLayout.addWidget(self.label_1) self.label_2 = QLabel(self.widget ) self.lineEdit = QLineEdit(self.widget) self.horizontalLayout.addWidget(self.lineEdit) self.horizontalLayout.addWidget(self.label_2) self.dateEdit = QDateEdit(self.widget) self.horizontalLayout.addWidget(self.dateEdit) self.label_3 = QLabel(self.widget) self.horizontalLayout.addWidget(self.label_3) self.dateEdit_2 = QDateEdit(self.widget) self.horizontalLayout.addWidget(self.dateEdit_2) self.button1 = QPushButton(self.widget) self.horizontalLayout.addWidget(self.button1) self.button2 = QPushButton(self.widget) self.horizontalLayout.addWidget(self.button2) self.lineEdit.setText(QtCore.QString('M')) three_month = QtCore.QDate.currentDate().toJulianDay() - 60 self.dateEdit.setDate(QtCore.QDate.fromJulianDay(three_month)) self.dateEdit_2.setDate(QtCore.QDate.currentDate()) self.button1.clicked.connect(self.get_value) self.button2.clicked.connect(self.clear) self.treeWidget.headerItem().setText(0, _translate("MainWindow", "期货品种", None)) self.root1 = QTreeWidgetItem(self.treeWidget) self.root1.setText(0, _translate("MainWindow", "中金所", None)) self.root2 = QTreeWidgetItem(self.treeWidget) self.root2.setText(0, _translate("MainWindow", "上海期货", None)) self.root3 = QTreeWidgetItem(self.treeWidget) self.root3.setText(0, _translate("MainWindow", "大连商品", None)) self.root4 = QTreeWidgetItem(self.treeWidget) self.root4.setText(0, _translate("MainWindow", "郑州商品", None)) self.child11 = QTreeWidgetItem(self.root1) self.child12 = QTreeWidgetItem(self.root1) self.child13 = QTreeWidgetItem(self.root1) self.child14 = QTreeWidgetItem(self.root1) self.child15 = QTreeWidgetItem(self.root1) self.child16 = QTreeWidgetItem(self.root1) self.child17 = QTreeWidgetItem(self.root1) self.child18 = QTreeWidgetItem(self.root1) self.child11.setText(0, _translate("MainWindow", "CFFEX 沪深300指数期货(IF)", None)) self.child12.setText(0, _translate("MainWindow", "CFFEX 上证50指数期货(IH)", None)) self.child13.setText(0, _translate("MainWindow", "CFFEX 中证500指数期货(IC)", None)) self.child14.setText(0, _translate("MainWindow", "CFFEX 5年期国债期货(TF)", None)) self.child15.setText(0, _translate("MainWindow", "CFFEX 10年期国债期货(T)", None)) self.child16.setText(0, _translate("MainWindow", "CFFEX 3年期国债期货(仿真)(TT)", None)) self.child17.setText(0, _translate("MainWindow", "CFFEX 澳元兑美元(AUDUSD)期货(仿真)(AF)", None)) self.child18.setText(0, _translate("MainWindow", "CFFEX 欧元兑美元(EURUSD)期货(仿真)(EF)", None)) self.child21 = QTreeWidgetItem(self.root2) self.child22 = QTreeWidgetItem(self.root2) self.child23 = QTreeWidgetItem(self.root2) self.child24 = QTreeWidgetItem(self.root2) self.child25 = QTreeWidgetItem(self.root2) self.child26 = QTreeWidgetItem(self.root2) self.child27 = QTreeWidgetItem(self.root2) self.child28 = QTreeWidgetItem(self.root2) self.child29 = QTreeWidgetItem(self.root2) self.child210 = QTreeWidgetItem(self.root2) self.child211 = QTreeWidgetItem(self.root2) self.child212 = QTreeWidgetItem(self.root2) self.child213 = QTreeWidgetItem(self.root2) self.child214 = QTreeWidgetItem(self.root2) self.child21.setText(0, _translate("MainWindow", "SHFE 铜(CU)", None)) self.child22.setText(0, _translate("MainWindow", "SHFE 铝(AL)", None)) self.child23.setText(0, _translate("MainWindow", "SHFE 铅(ZN)", None)) self.child24.setText(0, _translate("MainWindow", "SHFE 黄金(AU)", None)) self.child25.setText(0, _translate("MainWindow", "SHFE 白银(AG)", None)) self.child26.setText(0, _translate("MainWindow", "SHFE 螺纹钢(RB)", None)) self.child27.setText(0, _translate("MainWindow", "SHFE 橡胶(RU)", None)) self.child28.setText(0, _translate("MainWindow", "SHFE 燃油(FU)", None)) self.child29.setText(0, _translate("MainWindow", "SHFE 线材(WR)", None)) self.child210.setText(0, _translate("MainWindow", "SHFE 石油沥青(BU)", None)) self.child211.setText(0, _translate("MainWindow", "SHFE 热轧卷板(HC)", None)) self.child212.setText(0, _translate("MainWindow", "SHFE 镍(NI)", None)) self.child213.setText(0, _translate("MainWindow", "SHFE 锡(SN)", None)) self.child214.setText(0, _translate("MainWindow", "SHFE 上期有色金属指数期货(仿真)(IM)", None)) self.child31 = QTreeWidgetItem(self.root3) self.child32 = QTreeWidgetItem(self.root3) self.child33 = QTreeWidgetItem(self.root3) self.child34 = QTreeWidgetItem(self.root3) self.child35 = QTreeWidgetItem(self.root3) self.child36 = QTreeWidgetItem(self.root3) self.child37 = QTreeWidgetItem(self.root3) self.child38 = QTreeWidgetItem(self.root3) self.child39 = QTreeWidgetItem(self.root3) self.child310 = QTreeWidgetItem(self.root3) self.child311 = QTreeWidgetItem(self.root3) self.child312 = QTreeWidgetItem(self.root3) self.child313 = QTreeWidgetItem(self.root3) self.child314 = QTreeWidgetItem(self.root3) self.child31.setText(0, _translate("MainWindow", "DCE 豆一(A)", None)) self.child32.setText(0, _translate("MainWindow", "DCE 豆粕(M)", None)) self.child33.setText(0, _translate("MainWindow", "DCE 豆油(Y)", None)) self.child34.setText(0, _translate("MainWindow", "DCE 棕榈油(P)", None)) self.child35.setText(0, _translate("MainWindow", "DCE 玉米(C)", None)) self.child36.setText(0, _translate("MainWindow", "DCE 铁矿石(I)", None)) self.child37.setText(0, _translate("MainWindow", "DCE 焦炭(JM)", None)) self.child38.setText(0, _translate("MainWindow", "DCE PVC(V)", None)) self.child39.setText(0, _translate("MainWindow", "DCE 豆二(B)", None)) self.child310.setText(0, _translate("MainWindow", "DCE 鸡蛋(JD)", None)) self.child311.setText(0, _translate("MainWindow", "DCE 纤维板(FB)", None)) self.child312.setText(0, _translate("MainWindow", "DCE 胶合板(BB)", None)) self.child313.setText(0, _translate("MainWindow", "DCE 聚丙烯(PP)", None)) self.child314.setText(0, _translate("MainWindow", "DCE 玉米淀粉(CS)", None)) self.child41 = QTreeWidgetItem(self.root4) self.child42 = QTreeWidgetItem(self.root4) self.child43 = QTreeWidgetItem(self.root4) self.child44 = QTreeWidgetItem(self.root4) self.child45 = QTreeWidgetItem(self.root4) self.child46 = QTreeWidgetItem(self.root4) self.child47 = QTreeWidgetItem(self.root4) self.child48 = QTreeWidgetItem(self.root4) self.child49 = QTreeWidgetItem(self.root4) self.child410 = QTreeWidgetItem(self.root4) self.child411 = QTreeWidgetItem(self.root4) self.child412 = QTreeWidgetItem(self.root4) self.child413 = QTreeWidgetItem(self.root4) self.child414 = QTreeWidgetItem(self.root4) self.child415 = QTreeWidgetItem(self.root4) self.child416 = QTreeWidgetItem(self.root4) self.child41.setText(0, _translate("MainWindow", "CZCE 强麦(WH)", None)) self.child42.setText(0, _translate("MainWindow", "CZCE 菜油(OI)", None)) self.child43.setText(0, _translate("MainWindow", "CZCE 棉花(CF)", None)) self.child44.setText(0, _translate("MainWindow", "CZCE 白糖(SR)", None)) self.child45.setText(0, _translate("MainWindow", "CZCE 早籼稻(RI)", None)) self.child46.setText(0, _translate("MainWindow", "CZCE 动力煤(ZC)", None)) self.child47.setText(0, _translate("MainWindow", "CZCE PTA(TA)", None)) self.child48.setText(0, _translate("MainWindow", "CZCE 玻璃(FG)", None)) self.child49.setText(0, _translate("MainWindow", "CZCE 甲醇(MA)", None)) self.child410.setText(0, _translate("MainWindow", "CZCE 菜籽油(RM)", None)) self.child411.setText(0, _translate("MainWindow", "CZCE 油菜籽(RS)", None)) self.child412.setText(0, _translate("MainWindow", "CZCE 普麦(PM)", None)) self.child413.setText(0, _translate("MainWindow", "CZCE 粳稻(JR)", None)) self.child414.setText(0, _translate("MainWindow", "CZCE 晚籼稻(LR)", None)) self.child415.setText(0, _translate("MainWindow", "CZCE 锰硅(SM)", None)) self.child416.setText(0, _translate("MainWindow", "CZCE 硅铁(LR)", None)) # self.treeWidget.addTopLevelItem(self.root) # self.treeWidget.addTopLevelItem(self.root) self.label_1.setText(_translate("MainWindow", "期货品种", None)) self.label_2.setText(_translate("MainWindow", "起始时间", None)) self.label_3.setText(_translate("MainWindow", "终止时间", None)) self.button1.setText(_translate("MainWindow", "提交", None)) self.button2.setText(_translate("MainWindow", "清除", None)) def keyPressEvent(self, event): keyEvent = QKeyEvent(event) if keyEvent.key() == QtCore.Qt.Key_Enter or keyEvent.key() == QtCore.Qt.Key_Return: self.get_value() if keyEvent.key() == QtCore.Qt.Key_0: self.get_value() # 定义横坐标格式的回调函数 def my_major_formatter(self, x, pos): for i in range(self.num): if (x == i): return self.str_date[i] def get_value(self): code = QtCore.QString(self.lineEdit.text()) start = QtCore.QString(self.dateEdit.text()) end = QtCore.QString(self.dateEdit_2.text()) code = unicode(code) start = datetime.date(int(start.split("/")[0]), int(start.split("/")[1]), int(start.split("/")[2])).isoformat() end = datetime.date(int(end.split("/")[0]), int(end.split("/")[1]), int(end.split("/")[2])).isoformat() self.num, self.kbar, self.str_date, self.ema, self.name= source(code, start, end) self.star_date, self.star_value = star(col, code, start, end) self.update_figure() def update_figure(self): self.fig.clf() self.ax1 = self.fig.add_axes([0.22, 0.1, 0.7, 0.7]) # self.ax2 = self.ax1.twinx() # 创建第二个坐标轴,为同图 # 子图一 WindPy.w.start() self.ax1.set_xticks(range(self.num)) xmajorLocator = MultipleLocator(5) # 将x主刻度标签设置为3的倍数 xminorLocator = MultipleLocator(1) # 将x副刻度标签设置为1的倍数 self.ax1.xaxis.set_major_locator(xmajorLocator) self.ax1.xaxis.set_minor_locator(xminorLocator) self.ax1.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter)) self.ax1.grid() # self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00', width = 0.5,edgecolor = 'black') self.ax1.plot(range(self.num),self.ema,linewidth = 0.5,color = "blue") from matplotlib.font_manager import FontProperties font = FontProperties(size=14) # 设置字体 self.ax1.set_title(self.name) self.ax1.set_ylabel(u'价格') # self.ax2.set_ylabel(u'星数') #极端情况1 # high_1 = self.kbar[0][2] # low_1 = self.kbar[0][3] # ema_1 = self.ema[0] # deviate_1 = max(abs(high_1 - ema_1),abs(low_1 - ema_1)) # high_2 = self.kbar[1][2] # low_2 = self.kbar[1][3] # ema_2 = self.ema[1] # deviate_2 = max(abs(high_2 - ema_2),abs(low_2 - ema_2)) # high_3 = self.kbar[2][2] # low_3 = self.kbar[2][3] # ema_3 = self.ema[2] # deviate_3 = max(abs(high_3 - ema_3),abs(low_3 - ema_3)) # high_4 = self.kbar[3][2] # low_4 = self.kbar[3][3] # ema_4 = self.ema[3] # deviate_4 = max(abs(high_4 - ema_4),abs(low_4 - ema_4)) # high_5 = self.kbar[4][2] # low_5 = self.kbar[4][3] # ema_5 = self.ema[4] # deviate_5 = max(abs(high_5 - ema_5),abs(low_5 - ema_5)) # high_6 = self.kbar[5][2] # low_6 = self.kbar[5][3] # ema_6 = self.ema[5] # deviate_6 = max(abs(high_6 - ema_6),abs(low_6 - ema_6)) # for i in range(6,self.num): # high_7 = self.kbar[i][2] # low_7 = self.kbar[i][3] # ema_7 = self.ema[i] # deviate_7 = max(abs(high_7 - ema_7),abs(low_7 - ema_7)) # condition1 = deviate_5 > deviate_3 > deviate_2 > deviate_1 or deviate_4 > deviate_3 > deviate_2 > deviate_1 # condition2 = ema_5 > ema_4 > ema_3 > ema_2 > ema_1 or ema_1 > ema_2 > ema_3 > ema_4 > ema_5 # condition3 = deviate_5 > deviate_6 > deviate_7 # if condition1 and condition2 and condition3 : # self.ax1.annotate('E', xy=(i, low_7), xytext=(i+ 1, low_7+0.5), arrowprops=dict(arrowstyle="->")) # deviate_1 = deviate_2 # deviate_2 = deviate_3 # deviate_3 = deviate_4 # deviate_4 = deviate_5 # deviate_5 = deviate_6 # deviate_6 = deviate_7 # ema_1 = ema_2 # ema_2 = ema_3 # ema_3 = ema_4 # ema_4 = ema_5 # ema_5 = ema_6 # ema_6 = ema_7 # 极端情况2 high_1 = self.kbar[0][2] low_1 = self.kbar[0][3] ema_1 = self.ema[0] deviate_1 = max(abs(high_1 - ema_1),abs(low_1 - ema_1)) high_2 = self.kbar[1][2] low_2 = self.kbar[1][3] ema_2 = self.ema[1] deviate_2 = max(abs(high_2 - ema_2),abs(low_2 - ema_2)) high_3 = self.kbar[2][2] low_3 = self.kbar[2][3] ema_3 = self.ema[2] deviate_3 = max(abs(high_3 - ema_3),abs(low_3 - ema_3)) high_4 = self.kbar[3][2] low_4 = self.kbar[3][3] ema_4 = self.ema[3] deviate_4 = max(abs(high_4 - ema_4), abs(low_4 - ema_4)) high_5 = self.kbar[3][2] low_5 = self.kbar[3][3] ema_5 = self.ema[3] deviate_5 = max(abs(high_5 - ema_5), abs(low_5 - ema_5)) lim = self.ax1.get_ylim() # distance = 0.3 distance = (lim[1] - lim[0])/9 for i in range(5,self.num): alpha = 1.10 beta = 0.90 high_6 = self.kbar[i][2] low_6 = self.kbar[i][3] ema_6 = self.ema[i] deviate_6 = max(abs(high_6 - ema_6),abs(low_6 - ema_6)) condition1 = deviate_4 > deviate_3 > deviate_2 or deviate_4 > deviate_3 > deviate_1 or deviate_4 > deviate_2 > deviate_1 condition2 = ema_4 > ema_3 > ema_2 or ema_2 > ema_3 > ema_4 condition3 = deviate_4 > deviate_5 * beta and deviate_4 > deviate_6 top = high_4 - ema_4 bottom = ema_4 - low_4 condition4 = (low_4 < low_5 * alpha and low_4 < low_6 and top < bottom) or (high_4 > high_5 * beta and high_4 > high_6 and top > bottom) condition5 = top < bottom condition6 = top > bottom condition7 = high_3 < ema_3 and high_4 < ema_4 and high_5 < ema_5 and high_6 > ema_6 * alpha condition8 = low_3 > ema_3 and low_4 > ema_4 and low_5 > ema_5 and low_6 < ema_6 * beta matplotlib.rcParams.update({'font.size': 9}) if condition1 and condition2 and condition3 and condition4 and condition5 or condition7: self.ax1.annotate(u'多', xy=(i, low_6), xytext=(i-0.5, low_6 - distance), arrowprops=dict(arrowstyle="-")) if condition1 and condition2 and condition3 and condition4 and condition6 or condition8: self.ax1.annotate(u'空', xy=(i, high_6), xytext=(i-0.5, high_6 + distance), arrowprops=dict(arrowstyle="-")) deviate_1 = deviate_2 deviate_2 = deviate_3 deviate_3 = deviate_4 deviate_4 = deviate_5 deviate_5 = deviate_6 ema_1 = ema_2 ema_2 = ema_3 ema_3 = ema_4 ema_4 = ema_5 ema_5 = ema_6 low_1 = low_2 low_2 = low_3 low_3 = low_4 low_4 = low_5 low_5 = low_6 high_1 = high_2 high_2 = high_3 high_3 = high_4 high_4 = high_5 high_5 = high_6 # self.ax1.annotate('extreme', xy=(18, 16.8), xytext=(20, 16), arrowprops=dict(arrowstyle="->")) # self.ax2.set_ylim(0, 80) candlestick_ohlc(self.ax1, self.kbar, width=0.5, colorup='r', colordown='g') # self.ax1.hold(False) # self.ax2.hold(False) lim = self.ax1.get_ylim() self.ax1.set_ylim(lim[0] * 0.95, lim[1]) for tick in self.ax1.xaxis.get_major_ticks(): tick.label1.set_fontsize(8) tick.label1.set_rotation(75) for tick in self.ax1.yaxis.get_major_ticks(): tick.label1.set_fontsize(8) tick.label1.set_rotation(30) # for tick in self.ax2.xaxis.get_major_ticks(): # tick.label1.set_fontsize(8) # tick.label1.set_rotation(75) # for tick in self.ax2.yaxis.get_major_ticks(): # tick.label1.set_fontsize(8) # tick.label1.set_rotation(30) # 子图二 # self.ax2.set_xticks(range(self.num)) # self.ax2.xaxis.set_major_locator(xmajorLocator) # self.ax2.xaxis.set_minor_locator(xminorLocator) # self.ax2.grid() # self.ax2.set_xticklabels(self.str_date, rotation=25, horizontalalignment='right') # self.ax2.bar(range(len(self.star_date)), self.star_value, picker=True, color='#FFFF00') # #self.ax2.xaxis.set_major_locator(xmajorLocator) # self.ax2.xaxis.set_major_formatter(FuncFormatter(self.my_major_formatter)) # for label in self.ax2.get_xticklabels(): # label.set_picker(True) # for tick in self.ax2.xaxis.get_major_ticks(): # tick.label1.set_fontsize(5) # tick.label1.set_rotation(90) # for tick in self.ax2.yaxis.get_major_ticks(): # tick.label1.set_fontsize(5) # tick.label1.set_rotation(30) # self.draw() # self.fig.clf() def clear(self): self.fig.clf() self.ax1 = self.fig.add_axes([0.22, 0.1, 0.7, 0.7]) # self.ax1 = self.fig.add_axes([0.1, 0.35, 0.8, 0.58]) # self.ax2 = self.fig.add_axes([0.1, 0.07, 0.8, 0.2]) self.draw()
class DAyarlar(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(600, 375) self.gridLayout = QGridLayout(self) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.treeWidget = QTreeWidget(self) self.treeWidget.setMaximumSize(200, 1500) self.virux = QTreeWidgetItem(self.treeWidget) self.virux.setExpanded(True) icon = QIcon() icon.addPixmap(QPixmap("data/logo.png"), QIcon.Normal, QIcon.On) self.virux.setIcon(0, icon) item_1 = QTreeWidgetItem(self.virux) item_1 = QTreeWidgetItem(self.virux) self.dialog = QTreeWidgetItem(self.treeWidget) self.dialog.setExpanded(True) item_1 = QTreeWidgetItem(self.dialog) item_1 = QTreeWidgetItem(self.dialog) self.treeWidget.header().setVisible(False) self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1) self.groupBox = QGroupBox(self) self.groupBox.setFlat(True) self.gridLayout_3 = QGridLayout(self.groupBox) self.gridLayout_3.setMargin(0) self.gridLayout_3.setSpacing(0) self.widget = QWidget(self.groupBox) self.gridLayout_4 = QGridLayout(self.widget) self.gridLayout_4.setMargin(0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setMargin(0) spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 0, 0, 1, 1) self.gridLayout_3.addWidget(self.widget, 0, 0, 1, 1) self.gridLayout.addWidget(self.groupBox, 0, 1, 1, 1) self.pButton = QPushButton(self) self.pButton.setText("asd") self.pButton.setDefault(True) self.buttonBox = QDialogButtonBox(self) self.buttonBox.addButton(self.pButton, QDialogButtonBox.AcceptRole) #self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 2) self.setWindowTitle("Virux Ayarlar") self.treeWidget.headerItem().setText(0, "") self.treeWidget.topLevelItem(0).setText(0, u"Virux") self.treeWidget.topLevelItem(0).child(0).setText(0, u"Virux1") self.treeWidget.topLevelItem(0).child(1).setText(0, u"Virux2") self.treeWidget.topLevelItem(1).setText(0, u"Dialog") self.treeWidget.topLevelItem(1).child(0).setText(0, u"Dialog1") self.treeWidget.topLevelItem(1).child(1).setText(0, u"Dialog2") self.groupBox.setTitle(u"GroupBox") self.groupYaz() self.treeWidget.itemPressed.connect(self.lale) def lale(self, item): print item self.groupBox.setTitle(item.text(0)) def groupYaz(self): for option in DOptions: if hasattr(option, "getOption"): #self.gridLayout_3.addWidget(option.getOption(), 0, 0, 1, 1) item = QTreeWidgetItem(self.dialog) a = option.getOption() if hasattr(a, "name"): item.setText(0, a.name) else: item.setText(0, "F**k")
def __init__(self, parent): QSplitter.__init__(self, parent) parent.addPage(self, i18n("Parts")) # The part types overview widget. v = KVBox() self.addWidget(v) QLabel('<b>{0}</b>'.format(i18n("Available parts:")), v) allParts = QTreeWidget(v) addButton = KPushButton(KStandardGuiItem.add(), v) addButton.setToolTip(i18n("Add selected part to your score.")) # The listbox with selected parts v = KVBox() self.addWidget(v) QLabel('<b>{0}</b>'.format(i18n("Score:")), v) score = QListWidget(v) self.score = score # so the partList method can find us h = KHBox(v) removeButton = KPushButton(KStandardGuiItem.remove(), h) upButton = QToolButton(h) upButton.setIcon(KIcon("go-up")) downButton = QToolButton(h) downButton.setIcon(KIcon("go-down")) # The StackedWidget with settings partSettings = QStackedWidget() self.addWidget(partSettings) self.setStretchFactor(0, 1) self.setStretchFactor(1, 1) self.setStretchFactor(2, 1) self.setSizes((100, 100, 100)) allParts.setSelectionMode(QTreeWidget.ExtendedSelection) allParts.setRootIsDecorated(False) allParts.headerItem().setHidden(True) score.setSelectionMode(QListWidget.ExtendedSelection) score.setDragDropMode(QListWidget.InternalMove) class PartItem(QListWidgetItem): """ A part from the score, instantiating a config widget as well. """ def __init__(self, partClass): name = partClass.name() # partClass.name is a ki18n object QListWidgetItem.__init__(self, name, score) self.w = QGroupBox(name) partSettings.addWidget(self.w) self.part = partClass() layout = QVBoxLayout(self.w) self.part.widgets(layout) layout.addStretch(1) if score.count() == 1: score.setCurrentRow(0) self.setSelected(True) parent.enableButton(KPageDialog.Try, True) def showSettingsWidget(self): partSettings.setCurrentWidget(self.w) def remove(self): if score.count() == 1: parent.enableButton(KPageDialog.Try, False) sip.delete(self.w) sip.delete(self) # TODO: check if necessary @allParts.itemDoubleClicked.connect def addPart(item, col): if hasattr(item, "partClass"): PartItem(item.partClass) @allParts.itemClicked.connect def toggleExpand(item, col): item.setExpanded(not item.isExpanded()) @addButton.clicked.connect def addSelectedParts(): for item in allParts.selectedItems(): PartItem(item.partClass) @removeButton.clicked.connect def removeSelectedParts(): for item in score.selectedItems(): item.remove() def keepSel(func): """ Restore the selection and current element after reordering parts. """ def decorator(): selItems = score.selectedItems() curItem = score.currentItem() func() score.setCurrentItem(curItem) for i in selItems: i.setSelected(True) return decorator @upButton.clicked.connect @keepSel def moveUp(): """ Move selected parts up. """ for row in range(1, score.count()): if score.item(row).isSelected(): item = score.takeItem(row) score.insertItem(row - 1, item) @downButton.clicked.connect @keepSel def moveDown(): """ Move selected parts down. """ for row in range(score.count() - 1, -1, -1): if score.item(row).isSelected(): item = score.takeItem(row) score.insertItem(row + 1, item) @score.currentItemChanged.connect def showItem(cur, prev): if cur: cur.showSettingsWidget() from frescobaldi_app.scorewiz.parts import categories for name, parts in categories(): group = QTreeWidgetItem(allParts, [name]) group.setFlags(Qt.ItemIsEnabled) group.setIcon(0, KIcon("inode-directory")) for part in parts: p = QTreeWidgetItem(group, [part.name()]) p.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) p.partClass = part
class PluginWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.pluginMetadata = {} # Main layout self.mainLayout = QVBoxLayout() self.setLayout(self.mainLayout) # Define size used for the underlines self.underlineSize = QSize() self.underlineSize.setHeight(1) # Define font used for headers self.font = QFont() self.font.setPointSize(11) self.font.setBold(True) self.font.setUnderline(True) # Plugins Description self.pluginDescription = QLabel() self.pluginDescription.setText( "Click a plugin to see more information." + " Plugins can be configured from the Recording tab. \n") self.pluginDescription.setWordWrap(True) # Plugins GroupBox self.pluginLayout = QVBoxLayout() self.pluginGroupBox = QGroupBox( "Plugins extend the functionality of Freeseer") self.pluginGroupBox.setLayout(self.pluginLayout) self.pluginLayout.insertWidget(0, self.pluginDescription) self.mainLayout.insertWidget(0, self.pluginGroupBox) # Plugins list self.list = QTreeWidget() self.list.setHeaderHidden(True) self.list.headerItem().setText(0, "1") self.pluginLayout.insertWidget(1, self.list) # Details self.detailPane = QGroupBox() self.detailLayout = QVBoxLayout() self.detailPane.setLayout(self.detailLayout) self.detailPaneDesc = QLabel() self.detailPaneDesc.setWordWrap(True) self.detailLayout.addWidget(self.detailPaneDesc) self.pluginLayout.insertWidget(2, self.detailPane) self.list.itemSelectionChanged.connect(self.treeViewSelect) def treeViewSelect(self): item = self.list.currentItem() key = str(item.text(0)) if key in self.pluginMetadata.keys(): self.showDetails(key) else: self.hideDetails() def showDetails(self, key): self.detailPane.setTitle(key) self.detailPaneDesc.setText(self.pluginMetadata[key]) self.detailPane.show() def hideDetails(self): self.detailPane.hide() def getWidgetPlugin(self, plugin, plugin_category, plugman): plugin_name = plugin.plugin_object.get_name() item = QTreeWidgetItem() # Display Plugin's meta data in a tooltip pluginDetails = """ <table> <tr> <td>Name: </td> <td><b>%(name)s</b></td> </tr> <tr> <td>Version: </td> <td><b>%(version)s</b></td> <tr> <td>Author: </td> <td><b>%(author)s</b></td> </tr> <tr> <td>Website: </td> <td><b>%(website)s</b></td> </tr> <tr> <td>Description: </td> <td><b>%(description)s</b></td> </tr> </table> """ % { "name": plugin.name, "version": plugin.version, "author": plugin.author, "website": plugin.website, "description": plugin.description } # put the details in the hash table self.pluginMetadata[plugin_name] = pluginDetails item.setText(0, plugin_name) return item
class Main(plugin.Plugin): " Main Class " def initialize(self, *args, **kwargs): " Init Main Class " super(Main, self).initialize(*args, **kwargs) self.scriptPath, self.scriptArgs = "", [] self.profilerPath, self.tempPath = profilerPath, tempPath self.output = " ERROR: FAIL: No output ! " self.process = QProcess() self.process.finished.connect(self.on_process_finished) self.process.error.connect(self.on_process_error) self.tabWidget, self.stat = QTabWidget(), QWidget() self.tabWidget.tabCloseRequested.connect(lambda: self.tabWidget.setTabPosition(1) if self.tabWidget.tabPosition() == 0 else self.tabWidget.setTabPosition(0)) self.tabWidget.setStyleSheet('QTabBar{font-weight:bold;}') self.tabWidget.setMovable(True) self.tabWidget.setTabsClosable(True) self.vboxlayout1 = QVBoxLayout(self.stat) self.hboxlayout1 = QHBoxLayout() self.filterTableLabel = QLabel("<b>Type to Search : </b>", self.stat) self.hboxlayout1.addWidget(self.filterTableLabel) self.filterTableLineEdit = QLineEdit(self.stat) self.filterTableLineEdit.setPlaceholderText(' Type to Search . . . ') self.hboxlayout1.addWidget(self.filterTableLineEdit) self.filterHintTableLabel = QLabel(" ? ", self.stat) self.hboxlayout1.addWidget(self.filterHintTableLabel) self.vboxlayout1.addLayout(self.hboxlayout1) self.tableWidget = QTableWidget(self.stat) self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setColumnCount(8) self.tableWidget.setRowCount(2) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(2, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(3, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(4, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(5, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(6, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(7, item) self.tableWidget.itemDoubleClicked.connect( self.on_tableWidget_itemDoubleClicked) self.vboxlayout1.addWidget(self.tableWidget) self.tabWidget.addTab(self.stat, " ? ") self.source = QWidget() self.gridlayout = QGridLayout(self.source) self.scintillaWarningLabel = QLabel( "QScintilla is not installed!. Falling back to basic text edit!.", self.source) self.gridlayout.addWidget(self.scintillaWarningLabel, 1, 0, 1, 2) self.sourceTreeWidget = QTreeWidget(self.source) self.sourceTreeWidget.setAlternatingRowColors(True) self.sourceTreeWidget.itemActivated.connect( self.on_sourceTreeWidget_itemActivated) self.sourceTreeWidget.itemClicked.connect( self.on_sourceTreeWidget_itemClicked) self.sourceTreeWidget.itemDoubleClicked.connect( self.on_sourceTreeWidget_itemClicked) self.gridlayout.addWidget(self.sourceTreeWidget, 0, 0, 1, 1) self.sourceTextEdit = QTextEdit(self.source) self.sourceTextEdit.setReadOnly(True) self.gridlayout.addWidget(self.sourceTextEdit, 0, 1, 1, 1) self.tabWidget.addTab(self.source, " ? ") self.result = QWidget() self.vlayout = QVBoxLayout(self.result) self.globalStatGroupBox = QGroupBox(self.result) self.hboxlayout = QHBoxLayout(self.globalStatGroupBox) self.totalTimeLcdNumber = QLCDNumber(self.globalStatGroupBox) self.totalTimeLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.totalTimeLcdNumber.setNumDigits(7) self.totalTimeLcdNumber.display(1000000) self.totalTimeLcdNumber.setFrameShape(QFrame.StyledPanel) self.totalTimeLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.totalTimeLcdNumber) self.tTimeLabel = QLabel("<b>Total Time (Sec)</b>", self.globalStatGroupBox) self.tTimeLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.tTimeLabel) self.numCallLcdNumber = QLCDNumber(self.globalStatGroupBox) self.numCallLcdNumber.setNumDigits(7) self.numCallLcdNumber.display(1000000) self.numCallLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.numCallLcdNumber.setFrameShape(QFrame.StyledPanel) self.numCallLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.numCallLcdNumber) self.numCallLabel = QLabel("<b>Number of calls</b>", self.globalStatGroupBox) self.numCallLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.numCallLabel) self.primCallLcdNumber = QLCDNumber(self.globalStatGroupBox) self.primCallLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.primCallLcdNumber.setFrameShape(QFrame.StyledPanel) self.primCallLcdNumber.setNumDigits(7) self.primCallLcdNumber.display(1000000) self.primCallLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.primCallLcdNumber) self.primCallLabel = QLabel("<b>Primitive calls (%)</b>", self.globalStatGroupBox) self.primCallLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.primCallLabel) self.vlayout.addWidget(self.globalStatGroupBox) try: from PyKDE4.kdeui import KRatingWidget self.rating = KRatingWidget(self.globalStatGroupBox) self.rating.setToolTip('Profiling Performance Rating') except ImportError: pass self.tabWidget.addTab(self.result, " Get Results ! ") self.resgraph = QWidget() self.vlayout2 = QVBoxLayout(self.result) self.graphz = QGroupBox(self.resgraph) self.hboxlayout2 = QHBoxLayout(self.graphz) try: from PyKDE4.kdeui import KLed KLed(self.graphz) except ImportError: pass self.hboxlayout2.addWidget(QLabel(''' Work in Progress :) Not Ready Yet''')) self.vlayout2.addWidget(self.graphz) self.tabWidget.addTab(self.resgraph, " Graphs and Charts ") self.pathz = QWidget() self.vlayout3 = QVBoxLayout(self.pathz) self.patz = QGroupBox(self.pathz) self.hboxlayout3 = QVBoxLayout(self.patz) self.profilepath = QLineEdit(profilerPath) self.getprofile = QPushButton(QIcon.fromTheme("document-open"), 'Open') self.getprofile.setToolTip('Dont touch if you dont know what are doing') self.getprofile.clicked.connect(lambda: self.profilepath.setText(str( QFileDialog.getOpenFileName(self.patz, ' Open the profile.py file ', path.expanduser("~"), ';;(profile.py)')))) self.hboxlayout3.addWidget(QLabel( '<center><b>Profile.py Python Library Full Path:</b></center>')) self.hboxlayout3.addWidget(self.profilepath) self.hboxlayout3.addWidget(self.getprofile) self.argGroupBox = QGroupBox(self.pathz) self.hbxlayout = QHBoxLayout(self.argGroupBox) self.argLineEdit = QLineEdit(self.argGroupBox) self.argLineEdit.setToolTip('Not touch if you dont know what are doing') self.argLineEdit.setPlaceholderText( 'Dont touch if you dont know what are doing') self.hbxlayout.addWidget(QLabel('<b>Additional Profile Arguments:</b>')) self.hbxlayout.addWidget(self.argLineEdit) self.hboxlayout3.addWidget(self.argGroupBox) self.vlayout3.addWidget(self.patz) self.tabWidget.addTab(self.pathz, " Paths and Configs ") self.outp = QWidget() self.vlayout4 = QVBoxLayout(self.outp) self.outgro = QGroupBox(self.outp) self.outgro.setTitle(" MultiProcessing Output Logs ") self.hboxlayout4 = QVBoxLayout(self.outgro) self.outputlog = QTextEdit() self.outputlog.setText(''' I do not fear computers, I fear the lack of them. -Isaac Asimov ''') self.hboxlayout4.addWidget(self.outputlog) self.vlayout4.addWidget(self.outgro) self.tabWidget.addTab(self.outp, " Logs ") self.actionNew_profiling = QAction(QIcon.fromTheme("document-new"), 'New Profiling', self) self.actionLoad_profile = QAction(QIcon.fromTheme("document-open"), 'Open Profiling', self) self.actionClean = QAction(QIcon.fromTheme("edit-clear"), 'Clean', self) self.actionClean.triggered.connect(lambda: self.clearContent) self.actionAbout = QAction(QIcon.fromTheme("help-about"), 'About', self) self.actionAbout.triggered.connect(lambda: QMessageBox.about(self.dock, __doc__, ', '.join((__doc__, __license__, __author__, __email__)))) self.actionSave_profile = QAction(QIcon.fromTheme("document-save"), 'Save Profiling', self) self.actionManual = QAction(QIcon.fromTheme("help-contents"), 'Help', self) self.actionManual.triggered.connect(lambda: open_new_tab('http://docs.python.org/library/profile.html')) self.tabWidget.setCurrentIndex(2) self.globalStatGroupBox.setTitle("Global Statistics") item = self.tableWidget.horizontalHeaderItem(0) item.setText("Number of Calls") item = self.tableWidget.horizontalHeaderItem(1) item.setText("Total Time") item = self.tableWidget.horizontalHeaderItem(2) item.setText("Per Call") item = self.tableWidget.horizontalHeaderItem(3) item.setText("Cumulative Time") item = self.tableWidget.horizontalHeaderItem(4) item.setText("Per Call") item = self.tableWidget.horizontalHeaderItem(5) item.setText("Filename") item = self.tableWidget.horizontalHeaderItem(6) item.setText("Line") item = self.tableWidget.horizontalHeaderItem(7) item.setText("Function") self.tabWidget.setTabText(self.tabWidget.indexOf(self.stat), "Statistics per Function") self.sourceTreeWidget.headerItem().setText(0, "Source files") self.tabWidget.setTabText(self.tabWidget.indexOf(self.source), "Sources Navigator") ####################################################################### self.scrollable, self.dock = QScrollArea(), QDockWidget() self.scrollable.setWidgetResizable(True) self.scrollable.setWidget(self.tabWidget) self.dock.setWindowTitle(__doc__) self.dock.setStyleSheet('QDockWidget::title{text-align: center;}') self.dock.setWidget(self.scrollable) QToolBar(self.dock).addActions((self.actionNew_profiling, self.actionClean, self.actionSave_profile, self.actionLoad_profile, self.actionManual, self.actionAbout)) self.actionNew_profiling.triggered.connect( self.on_actionNew_profiling_triggered) self.actionLoad_profile.triggered.connect( self.on_actionLoad_profile_triggered) self.actionSave_profile.triggered.connect( self.on_actionSave_profile_triggered) self.locator.get_service('misc').add_widget(self.dock, QIcon.fromTheme("document-open-recent"), __doc__) if QSCI: # Scintilla source editor management self.scintillaWarningLabel.setText(' QScintilla is Ready ! ') layout = self.source.layout() layout.removeWidget(self.sourceTextEdit) self.sourceTextEdit = Qsci.QsciScintilla(self.source) layout.addWidget(self.sourceTextEdit, 0, 1) doc = self.sourceTextEdit doc.setLexer(Qsci.QsciLexerPython(self.sourceTextEdit)) doc.setReadOnly(True) doc.setEdgeMode(Qsci.QsciScintilla.EdgeLine) doc.setEdgeColumn(80) doc.setEdgeColor(QColor("#FF0000")) doc.setFolding(Qsci.QsciScintilla.BoxedTreeFoldStyle) doc.setBraceMatching(Qsci.QsciScintilla.SloppyBraceMatch) doc.setCaretLineVisible(True) doc.setMarginLineNumbers(1, True) doc.setMarginWidth(1, 25) doc.setTabWidth(4) doc.setEolMode(Qsci.QsciScintilla.EolUnix) self.marker = {} for color in COLORS: mnr = doc.markerDefine(Qsci.QsciScintilla.Background) doc.setMarkerBackgroundColor(color, mnr) self.marker[color] = mnr self.currentSourcePath = None # Connect table and tree filter edit signal to unique slot self.filterTableLineEdit.textEdited.connect( self.on_filterLineEdit_textEdited) # Timer to display filter hint message self.filterHintTimer = QTimer(self) self.filterHintTimer.setSingleShot(True) self.filterHintTimer.timeout.connect(self.on_filterHintTimer_timeout) # Timer to start search self.filterSearchTimer = QTimer(self) self.filterSearchTimer.setSingleShot(True) self.filterSearchTimer.timeout.connect( self.on_filterSearchTimer_timeout) self.tabLoaded = {} for i in range(10): self.tabLoaded[i] = False self.backgroundTreeMatchedItems = {} self.resizeWidgetToContent(self.tableWidget) def on_actionNew_profiling_triggered(self): self.clearContent() self.scriptPath = str(QFileDialog.getOpenFileName(self.dock, "Choose your script to profile", path.expanduser("~"), "Python (*.py *.pyw)")) commandLine = [self.profilerPath, "-o", self.tempPath, self.scriptPath] + self.scriptArgs commandLine = " ".join(commandLine) ##if self.termCheckBox.checkState() == Qt.Checked: #termList = ["xterm", "aterm"] #for term in termList: #termPath = which(term) #if termPath: #break #commandLine = """%s -e "%s ; echo 'Press ENTER Exit' ; read" """ \ #% (termPath, commandLine) self.process.start(commandLine) if not self.process.waitForStarted(): print((" ERROR: {} failed!".format(commandLine))) return def on_process_finished(self, exitStatus): ' whan the process end ' print((" INFO: OK: QProcess is %s" % self.process.exitCode())) self.output = self.process.readAll().data() if not self.output: self.output = " ERROR: FAIL: No output ! " self.outputlog.setText(self.output + str(self.process.exitCode())) if path.exists(self.tempPath): self.setStat(self.tempPath) remove(self.tempPath) else: self.outputlog.setText(" ERROR: QProcess FAIL: Profiling failed.") self.tabWidget.setCurrentIndex(2) def on_process_error(self, error): ' when the process fail, I hope you never see this ' print(" ERROR: QProcess FAIL: Profiler Dead, wheres your God now ? ") if error == QProcess.FailedToStart: self.outputlog.setText(" ERROR: FAIL: Profiler execution failed ") elif error == QProcess.Crashed: self.outputlog.setText(" ERROR: FAIL: Profiler execution crashed ") else: self.outputlog.setText(" ERROR: FAIL: Profiler unknown error ") def on_actionLoad_profile_triggered(self): """Load a previous profile sessions""" statPath = str(QFileDialog.getOpenFileName(self.dock, "Open profile dump", path.expanduser("~"), "Profile file (*)")) if statPath: self.clearContent() print(' INFO: OK: Loading profiling from ' + statPath) self.setStat(statPath) def on_actionSave_profile_triggered(self): """Save a profile sessions""" statPath = str(QFileDialog.getSaveFileName(self.dock, "Save profile dump", path.expanduser("~"), "Profile file (*)")) if statPath: #TODO: handle error case and give feelback to user print(' INFO: OK: Saving profiling to ' + statPath) self.stat.save(statPath) #=======================================================================# # Common parts # #=======================================================================# def on_tabWidget_currentChanged(self, index): """slot for tab change""" # Kill search and hint timer if running to avoid cross effect for timer in (self.filterHintTimer, self.filterSearchTimer): if timer.isActive(): timer.stop() if not self.stat: #No stat loaded, nothing to do return self.populateTable() self.populateSource() def on_filterLineEdit_textEdited(self, text): """slot for filter change (table or tree""" if self.filterSearchTimer.isActive(): # Already runnning, stop it self.filterSearchTimer.stop() # Start timer self.filterSearchTimer.start(300) def on_filterHintTimer_timeout(self): """Timeout to warn user about text length""" print("timeout") tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: label = self.filterHintTableLabel label.setText("Type > 2 characters to search") def on_filterSearchTimer_timeout(self): """timeout to start search""" tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: text = self.filterTableLineEdit.text() label = self.filterHintTableLabel edit = self.filterTableLineEdit widget = self.tableWidget else: print("Unknow tab for filterSearch timeout !") print(("do search for %s" % text)) if not len(text): # Empty keyword, just clean all if self.filterHintTimer.isActive(): self.filterHintTimer.stop() label.setText(" ? ") self.warnUSer(True, edit) self.clearSearch() return if len(text) < 2: # Don't filter if text is too short and tell it to user self.filterHintTimer.start(600) return else: if self.filterHintTimer.isActive(): self.filterHintTimer.stop() label.setText(" ? ") # Search self.clearSearch() matchedItems = [] if tab == TAB_FUNCTIONSTAT: # Find items matchedItems = widget.findItems(text, Qt.MatchContains) widget.setSortingEnabled(False) matchedRows = [item.row() for item in matchedItems] # Hide matched items header = widget.verticalHeader() for row in range(widget.rowCount()): if row not in matchedRows: header.hideSection(row) widget.setSortingEnabled(True) else: print(" Unknow tab for filterSearch timeout ! ") print(("got %s members" % len(matchedItems))) self.warnUSer(matchedItems, edit) self.resizeWidgetToContent(widget) def resizeWidgetToContent(self, widget): """Resize all columns according to content""" for i in range(widget.columnCount()): widget.resizeColumnToContents(i) def clearSearch(self): """Clean search result For table, show all items For tree, remove colored items""" tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: header = self.tableWidget.verticalHeader() if header.hiddenSectionCount(): for i in range(header.count()): if header.isSectionHidden(i): header.showSection(i) def clearContent(self): # Clear tabs self.tableWidget.clearContents() self.sourceTreeWidget.clear() # Reset LCD numbers for lcdNumber in (self.totalTimeLcdNumber, self.numCallLcdNumber, self.primCallLcdNumber): lcdNumber.display(1000000) # Reset stat self.pstat = None # Disable save as menu self.actionSave_profile.setEnabled(False) # Mark all tabs as unloaded for i in range(10): self.tabLoaded[i] = False def warnUSer(self, result, inputWidget): palette = inputWidget.palette() if result: palette.setColor(QPalette.Normal, QPalette.Base, QColor(255, 255, 255)) else: palette.setColor(QPalette.Normal, QPalette.Base, QColor(255, 136, 138)) inputWidget.setPalette(palette) inputWidget.update() def setStat(self, statPath): self.stat = Stat(path=statPath) # Global stat update self.totalTimeLcdNumber.display(self.stat.getTotalTime()) self.numCallLcdNumber.display(self.stat.getCallNumber()) self.primCallLcdNumber.display(self.stat.getPrimitiveCallRatio()) # Refresh current tab self.on_tabWidget_currentChanged(self.tabWidget.currentIndex()) # Activate save as menu self.actionSave_profile.setEnabled(True) try: self.rating.setMaxRating(10) self.rating.setRating( int(self.stat.getPrimitiveCallRatio()) / 10 - 1) except: pass #========================================================================# # Statistics table # #=======================================================================# def populateTable(self): row = 0 rowCount = self.stat.getStatNumber() progress = QProgressDialog("Populating statistics table...", "Abort", 0, 2 * rowCount) self.tableWidget.setSortingEnabled(False) self.tableWidget.setRowCount(rowCount) progress.setWindowModality(Qt.WindowModal) for (key, value) in self.stat.getStatItems(): #ncalls item = StatTableWidgetItem(str(value[0])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_NCALLS, item) colorTableItem(item, self.stat.getCallNumber(), value[0]) #total time item = StatTableWidgetItem(str(value[2])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_TTIME, item) colorTableItem(item, self.stat.getTotalTime(), value[2]) #per call (total time) if value[0] != 0: tPerCall = str(value[2] / value[0]) cPerCall = str(value[3] / value[0]) else: tPerCall = "" cPerCall = "" item = StatTableWidgetItem(tPerCall) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_TPERCALL, item) colorTableItem(item, 100.0 * self.stat.getTotalTime() / self.stat.getCallNumber(), tPerCall) #per call (cumulative time) item = StatTableWidgetItem(cPerCall) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_CPERCALL, item) colorTableItem(item, 100.0 * self.stat.getTotalTime() / self.stat.getCallNumber(), cPerCall) #cumulative time item = StatTableWidgetItem(str(value[3])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_CTIME, item) colorTableItem(item, self.stat.getTotalTime(), value[3]) #Filename self.tableWidget.setItem(row, STAT_FILENAME, StatTableWidgetItem(str(key[0]))) #Line item = StatTableWidgetItem(str(key[1])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_LINE, item) #Function name self.tableWidget.setItem(row, STAT_FUNCTION, StatTableWidgetItem(str(key[2]))) row += 1 # Store it in stat hash array self.stat.setStatLink(item, key, TAB_FUNCTIONSTAT) progress.setValue(row) if progress.wasCanceled(): return for i in range(self.tableWidget.rowCount()): progress.setValue(row + i) for j in range(self.tableWidget.columnCount()): item = self.tableWidget.item(i, j) if item: item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setSortingEnabled(True) self.resizeWidgetToContent(self.tableWidget) progress.setValue(2 * rowCount) def on_tableWidget_itemDoubleClicked(self, item): matchedItems = [] filename = str(self.tableWidget.item(item.row(), STAT_FILENAME).text()) if not filename or filename.startswith("<"): # No source code associated, return immediatly return function = self.tableWidget.item(item.row(), STAT_FUNCTION).text() line = self.tableWidget.item(item.row(), STAT_LINE).text() self.on_tabWidget_currentChanged(TAB_SOURCE) # load source tab function = "%s (%s)" % (function, line) fathers = self.sourceTreeWidget.findItems(filename, Qt.MatchContains, SOURCE_FILENAME) print(("find %s father" % len(fathers))) for father in fathers: findItems(father, function, SOURCE_FILENAME, matchedItems) print(("find %s items" % len(matchedItems))) if matchedItems: self.tabWidget.setCurrentIndex(TAB_SOURCE) self.sourceTreeWidget.scrollToItem(matchedItems[0]) self.on_sourceTreeWidget_itemClicked(matchedItems[0], SOURCE_FILENAME) matchedItems[0].setSelected(True) else: print("oups, item found but cannot scroll to it !") #=======================================================================# # Source explorer # #=====================================================================# def populateSource(self): items = {} for stat in self.stat.getStatKeys(): source = stat[0] function = "%s (%s)" % (stat[2], stat[1]) if source in ("", "profile") or source.startswith("<"): continue # Create the function child child = QTreeWidgetItem([function]) # Store it in stat hash array self.stat.setStatLink(child, stat, TAB_SOURCE) if source in items: father = items[source] else: # Create the father father = QTreeWidgetItem([source]) items[source] = father father.addChild(child) self.sourceTreeWidget.setSortingEnabled(False) for value in list(items.values()): self.sourceTreeWidget.addTopLevelItem(value) self.sourceTreeWidget.setSortingEnabled(True) def on_sourceTreeWidget_itemActivated(self, item, column): self.on_sourceTreeWidget_itemClicked(item, column) def on_sourceTreeWidget_itemClicked(self, item, column): line = 0 parent = item.parent() if QSCI: doc = self.sourceTextEdit if parent: pathz = parent.text(column) result = match("(.*) \(([0-9]+)\)", item.text(column)) if result: try: function = str(result.group(1)) line = int(result.group(2)) except ValueError: # We got garbage... falling back to line 0 pass else: pathz = item.text(column) pathz = path.abspath(str(pathz)) if self.currentSourcePath != pathz: # Need to load source self.currentSourcePath == pathz try: if QSCI: doc.clear() doc.insert(file(pathz).read()) else: self.sourceTextEdit.setPlainText(file(pathz).read()) except IOError: QMessageBox.warning(self, "Error", "Source file could not be found", QMessageBox.Ok) return if QSCI: for function, line in [(i[2], i[1] ) for i in self.stat.getStatKeys() if i[0] == pathz]: # expr, regexp, case sensitive, whole word, wrap, forward doc.findFirst("def", False, True, True, False, True, line, 0, True) end, foo = doc.getCursorPosition() time = self.stat.getStatTotalTime((pathz, line, function)) colorSource(doc, self.stat.getTotalTime(), time, line, end, self.marker) if QSCI: doc.ensureLineVisible(line)