def __init__(self, base_url, session, email, password, parent=None): super(volBrainClient, self).__init__(parent) self.session = session self.base_url = base_url self.jobUploadManager = JobUploadManager(base_url, session) self.jobUploadManager.uploaded.connect(self.uploaded) self.spacerItem = QtWidgets.QSpacerItem( 40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.selectFilesButton.clicked.connect(self.chooseFile) self.ui.cleanButton.clicked.connect(self.cleanList) self.ui.showJobsButton.clicked.connect(self.openProcessWindow) self.ui.uploadFilesButton.clicked.connect(self.uploadSelected) if (volbrain.upload_limit_reached(base_url, session)): self.disableUpload() else: self.ui.uploadLimitReachedLabel.hide() self.email = email self.password = password self.fileWidgets = []
class MainWindow: def __init__(self): self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ds = DataStore() self.ui.setupUi(self.main_win) self.ui.stackedWidget.setCurrentWidget(self.ui.home) self.ui.bmr_batton.clicked.connect(self.showBMR) self.ui.bmi_button.clicked.connect(self.showBMI) self.ui.bmr_calculate_button.clicked.connect(self.calcBMR) self.ui.bmi_calculate_button.clicked.connect(self.calcBMI) def show(self): self.main_win.show() def showBMR(self): self.ui.stackedWidget.setCurrentWidget(self.ui.bmr) def showBMI(self): self.ui.stackedWidget.setCurrentWidget(self.ui.bmi) def calcBMR(self): if self.ui.bmr_male_radio.isChecked(): gender = "male" else: gender = "female" height = int(self.ui.bmr_height_input.text()) weight = int(self.ui.bmr_weight_input.text()) age = int(self.ui.bmr_age_input.text()) if self.ui.bmr_sedentary.isChecked(): activity = "sedentary" elif self.ui.bmr_lighthy.isChecked(): activity = "lighthy" elif self.ui.bmr_moderately.isChecked(): activity = "moderately" elif self.ui.bmr_very.isChecked(): activity = "very" else: activity = "extremely" result = self.ds.bmr_calc(gender, height, weight, age, activity) output = "The BMR for a {} year old {}, who is {} cm tall and {} kg heavy with a {} activity level is {} calories.".format( age, gender, height, weight, activity, result) self.ui.bmr_output_label.setText(output) def calcBMI(self): height = int(self.ui.bmi_height_input.text()) weight = int(self.ui.bmi_weight_input.text()) result = self.ds.bmi_calc(height, weight) outpuut = "You entered the following information for BMI: Height {} cm & Weight: {} kg. This meansyourBMI is {}".format( height, weight, result) self.ui.bmi_output_label.setText(outpuut)
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionGet_User_Info.triggered.connect(self.GetUserInfo)
class Main(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) # This is always the samej self.ui=Ui_MainWindow() self.ui.setupUi(self) self.ui.DownloadFolder.setText(QtCore.QDir.homePath() + "/Downloads") self.ui.statusbar.showMessage("Ready") self.ui.BrowseButton.clicked.connect(self.SetDownloadFolder) self.ui.DownloadButton.clicked.connect(self.Download) def SetDownloadFolder(self): dir = QtGui.QFileDialog.getExistingDirectory(self, "Select Downloads Directory", QtCore.QDir.homePath() + "/Downloads", QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks) if(dir != ''): self.ui.DownloadFolder.setText(dir) def Download(self): if (str(self.ui.NhacSoURL.text()).startswith('http://www.nhacso.net') or str(self.ui.NhacSoURL.text()).startswith('http://nhacso.net')) : NhacSoURLParser(unicode(str(self.ui.NhacSoURL.text()), 'utf-8')) for i in range(len(song_name)): self.ui.statusbar.showMessage("Downloading " + song_name[i]) print "Downloading %s" % (song_name[i]) urlretrieve(song_mp3link[i], unicode(self.ui.DownloadFolder.text()) + "/" + unicode(song_name[i]) + " - " + unicode(song_artist[i]) + ".mp3") print "Done: %s" % (song_name[i]) QtGui.QMessageBox.information(self, "Done", "All files is downloaded!") else: QtGui.QMessageBox.critical(self, "Error", "Please enter vaild URL")
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.showFileDialog)
def __init__(self): super(MainWindow, self).__init__() # ui init self.ui = Ui_MainWindow() self.ui.setupUi(self) # MainWindow Title self.setWindowTitle('Youtube2Mp3') # set window icon icon_path = self.resource_path('icon/icon_window.png') self.setWindowIcon(QtGui.QIcon(icon_path)) # save place self.save_dir = '轉換的音樂' os.makedirs(self.save_dir, exist_ok=True) # convert button self.ui.convertButton.clicked.connect(self.convert) # status label self.ui.statusLabel.setText('') # mp4 filepath self.mp4_file_path = ''
def __init__(self, parent=None): QMainWindow.__init__(self, parent) Ui_MainWindow.setupUi(self, self) self.manager = UserManager() self.users = {} self.lineEdit_appid.setText('wxaafc0692eca7f8d6') self.lineEdit_secret.setText('077b4e1bed2b773c1014efa4512cd652') self.progressBar.setValue(0) self.pushButton_get_openids.setEnabled(False) self.pushButton_dump_all_user.setEnabled(False) self.pushButton_connect.clicked.connect(self.onConnect) self.pushButton_get_openids.clicked.connect(self.onGetOpenids) self.listWidget.currentItemChanged.connect(self.onOpenidFocus) self.manager.connected.connect(self.onConnected) self.manager.openidGot.connect(self.onOpenidGot) self.manager.info.connect(self.onInfo) self.manager.error.connect(self.onError) self.manager.onUser.connect(self.onUserInfo) self.manager.progress.connect(self.onProgressUpdate) self.pushButton_dump_all_user.clicked.connect(self.manager.dump_all_users) self.pushButton_statistics.clicked.connect(self.manager.do_statistic) self.pushButton_gender.clicked.connect(self.manager.show_stat_sex) self.pushButton_language.clicked.connect(self.manager.show_stat_language) self.pushButton_city.clicked.connect(self.manager.show_stat_city) self.pushButton_province.clicked.connect(self.manager.show_stat_province) self.pushButton_country.clicked.connect(self.manager.show_stat_country)
def __init__(self): super(MyApp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.set_def_button.clicked.connect(self.set_defaults) self.ui.run_button.clicked.connect(self.run) self.defaults = { "k0": 0.4, "kN": 0.1, "a0": 0.05, "aN": 0.01, "l": 10, "T0": 300, "R": 0.5, "F0": 50, "h": 0.1 } self.data = { "k0": None, "kN": None, "a0": None, "aN": None, "l": None, "T0": None, "R": None, "F0": None, "h": None } self.set_defaults()
def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.wait = Ui_Wait(self) self.downloadsManager = DownloadsManager(self, self.ui.downloadsList) global config self.videosManager = VideosManager(self.ui.downloadsList, self.ui.categoriesList) QObject.connect(self.downloadsManager, SIGNAL("download_terminated(PyQt_PyObject)"), self.add_video) QObject.connect(self, SIGNAL("refresh(PyQt_PyObject)"), self.downloadsManager.refresh_downloads_list) QObject.connect(self.ui.downloadsList, SIGNAL("download(PyQt_PyObject)"), self.downloadsManager.download) QObject.connect(self, SIGNAL("construct_downloads(PyQt_PyObject)"), self.generate_downloads) QObject.connect(self.downloadsManager, SIGNAL("blacklist(PyQt_PyObject)"), self.blacklist) QObject.connect(self.ui.wait, SIGNAL("open()"), self.ui.wait.open) QObject.connect(self.ui.wait, SIGNAL("close()"), self.ui.wait.close)
class MainWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) def onBtn1Clicked(self): print("onBtn1Clicked")
def __init__(self, config): QtGui.QDialog.__init__(self) Ui_MainWindow.__init__(self) self.logic = self.create_logic(config) self.setupUi(self) self.connect(self.btnUpdate, QtCore.SIGNAL("clicked()"), self.do_update) self.config_ui(config) self.init()
def __init__(self, parent=None): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.portManager = PortManager(self.ui, startmonitor=True) self.configHelper = ConfigHelper(self.ui) self.initSignal() self.setupUi_Ex()
class Win(QtGui.QMainWindow): def __init__(self, parent=None): super(Win, self).__init__(parent) self.initUI() def initUI(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show()
def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.cookieJar = PersistenceCookieJar( QSettings("POWERUMC", "GmailTray")) self.onLoad()
def __init__(self): self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ds = DataStore() self.ui.setupUi(self.main_win) self.ui.stackedWidget.setCurrentWidget(self.ui.home) self.ui.bmr_batton.clicked.connect(self.showBMR) self.ui.bmi_button.clicked.connect(self.showBMI) self.ui.bmr_calculate_button.clicked.connect(self.calcBMR) self.ui.bmi_calculate_button.clicked.connect(self.calcBMI)
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.MainWindow = QtWidgets.QMainWindow() self.ui.setupUi(self.MainWindow) self.MainWindow.show() #self.ui.show() self.image_converter = Image_Converter() self.display_layer_counter = 0 self.model_layers = [] self.link_ui()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Tarea 5') self.error = QMessageBox() self.listStudents = [] self.ui.add.clicked.connect(self.addF) self.ui.deleteS.clicked.connect(self.delete_student) self.ui.readS.clicked.connect(self.read_student) self.ui.listWidget.currentRowChanged.connect(self.show_details)
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Status Lights statusGrid = self.ui.groupBoxStatus.layout() statusLightCom = QLedIndicator("COM") # statusLightCom.setIndicatorTitle("COM") statusLightRpi = QLedIndicator("RPi") # statusLightRpi.setIndicatorTitle("RPi") statusLightJoystick = QLedIndicator("Joystick") # statusLightJoystick.setIndicatorTitle("RPi") statusLightLights = QLedIndicator("Lights") statusGrid.addWidget(statusLightCom, 0, 0, 1, 1) statusGrid.addWidget(statusLightRpi, 0, 1, 1, 1) statusGrid.addWidget(statusLightJoystick, 1, 0, 1, 1) statusGrid.addWidget(statusLightLights, 1, 1, 1, 1) # Sensor Readouts self.rov = QRov() if len(self.rov.sensors) > 0: vLayout = QVBoxLayout(self.ui.groupBoxSensorReadouts) i = 0 for sensor in self.rov.sensors: hLayout = QHBoxLayout(self) hLayout.addWidget(sensor.labelName) hLayout.addWidget(sensor.lcd) hLayout.addWidget(sensor.labelUnits) hLayout.setAlignment(hLayout, Qt.AlignHCenter) vLayout.addLayout(hLayout) self.setup_plots(sensor.name, sensor.units, i) i += 1 self.ui.groupBoxSensorReadouts.setLayout(vLayout) if len(self.rov.relays) > 0: for relay in self.rov.relays: self.ui.groupBoxRelayButtons.layout().addWidget(relay.button) self.activityMonitor = QActivityMonitor(self.ui.teLog) self.activityMonitor.display("GUI started...", t.Message.INFO) self.ui.graphWidget.setBackground(self.palette().window().color()) self.ui.graphWidget.ci.layout.setContentsMargins(0, 0, 0, 0) self.ui.graphWidget.ci.layout.setSpacing(20)
def __init__(self): self.app = QtGui.QApplication(sys.argv) jsonpickle.ext.numpy.register_handlers() mw = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(mw) #Obtain DesktopWidget to gain screen sizes dw = QtGui.QDesktopWidget() screen = dw.availableGeometry() #Resize main window to 90% of the screen width/height mw.resize(screen.size() * 0.9) #Recenter main window frame = mw.frameGeometry() frame.moveCenter(screen.center()) mw.move(frame.topLeft()) pw = gl.GLViewWidget(ui.centralwidget) ui.gridLayout.replaceWidget(ui.plotWidget, pw) ui.plotWidget.hide() ui.plotWidget = pw self.ui = ui self.mw = mw self.pw = pw self.tree = None self.paths = None self.seedAmt = None self.state = -1 mw.setWindowTitle("Hierarchical Visualizer") pw.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) axis = gl.GLAxisItem() xText = glt.GLTextItem(GLViewWidget=self.pw, X=1, Y=0, Z=0, text="X") yText = glt.GLTextItem(GLViewWidget=self.pw, X=0, Y=1, Z=0, text="Y") zText = glt.GLTextItem(GLViewWidget=self.pw, X=0, Y=0, Z=1, text="Z") self.pw.addItem(axis) self.pw.addItem(xText) self.pw.addItem(yText) self.pw.addItem(zText) self.connectSlots()
def __init__(self): super(MainWindow, self).__init__() self._ui = Ui_MainWindow() self._ui.setupUi(self) self._provider = ReminderApiProvider('http://localhost:8080') self._collections_model = CollectionsModel(self._provider) self._table_model = None self._ui.comboBox.setModel(self._collections_model) self._ui.comboBox.currentTextChanged.connect(self._set_collection) self._collections_model.update_model() self._set_collection(self._ui.comboBox.currentText())
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Tarea 5') self.error = QMessageBox() self.listStudents = [] self.ui.add.clicked.connect(self.addF) self.ui.deleteS.clicked.connect(self.delete_student) self.ui.readS.clicked.connect(self.read_student) self.ui.listWidget.currentRowChanged.connect(self.show_details) def show_error(self, message): self.error.setText(message) self.error.setIcon(QMessageBox.Warning) self.error.exec_() @Slot() def addF(self): temp = student(self.ui.name.text(), self.ui.email.text(), self.ui.password.text()) self.listStudents.append(temp) student.saveStudentP(self.listStudents) self.ui.listWidget.addItem(temp.getName()) self.ui.name.setText('') self.ui.email.setText('') self.ui.password.setText('') @Slot() def show_details(self): self.ui.textEdit.clear() temp = self.listStudents[self.ui.listWidget.currentRow()] self.ui.textEdit.append(str(temp)) @Slot() def delete_student(self): try: self.listStudents.pop(self.ui.listWidget.currentRow()) self.ui.listWidget.takeItem(self.ui.listWidget.currentRow()) except: self.show_error("No hay estudiantes por borrar") @Slot() def read_student(self): self.listStudents.append(student.readStudentP('studentsP.db')) for i in student.readStudentP('studentsP.db'): self.ui.textEdit.append(str(i))
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # set up ui self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Network Analyzer') # connect signals self.ui.portScan.clicked.connect(self._onPortScanClicked) self.ui.launchServer.clicked.connect(self._onLaunchServerClicked) self.ui.networkScan.clicked.connect(self._onNetworkScanClicked) self.ui.getHostNameButton.clicked.connect(self._onGetHostNameClicked) self.ui.quitButton.clicked.connect(self._onQuitClicked)
def __init__(self): app = QtWidgets.QApplication(sys.argv) self.isPathSelected = False self.selectedPath = "" self.duplicateInformation = [] self.tools = Tools() self.MainWindow = MW() self.MainWindow.closeSignal.connect(self._quit) self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.ui.treeWidget.itemDoubleClicked.connect(self._item_handler) self._connect_signals() self.MainWindow.show() sys.exit(app.exec_())
def __init__(self, *args, **kwds): super().__init__() # QtGui.QMainWindow.__init__(self, *args, **kwds) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.Base_Dir = os.path.dirname(os.path.realpath(__file__)) # wid = loadUi(os.path.join(self.Base_Dir, "Main.ui"), self) self.local_table_model = MediaLibrary.MediaLibrary(self, []) self.remote_table_model = MediaLibrary.MediaLibrary(self, []) self.left_playlist_table = PlaylistTable.PlaylistTable(self, []) self.right_playlist_table = PlaylistTable.PlaylistTable(self, []) self.ui.LocalTableL.setModel(self.local_table_model) self.ui.LocalTableR.setModel(self.local_table_model) self.ui.RemoteTableL.setModel(self.remote_table_model) self.ui.RemoteTableR.setModel(self.remote_table_model) self.ui.LeftPlaylistTable.setModel(self.left_playlist_table) self.ui.RightPlaylistTable.setModel(self.right_playlist_table) self.ui.LocalTableL.setSortingEnabled(True) self.ui.LocalTableR.setSortingEnabled(True) self.ui.RemoteTableL.setSortingEnabled(True) self.ui.RemoteTableR.setSortingEnabled(True) self.ui.RightPlaylistTable.setSortingEnabled(True) self.ui.LeftPlaylistTable.setSortingEnabled(True) self.AlbumList = {} self.sendQueue = queue.Queue() self.Id = 1 self.local_server = None self.local_server_thread = None self.remote_server = None self.remote_server_thread = None self.menu = qtw.QMenu(self) copy_action = qtw.QAction('Copy File', self) copy_action.triggered.connect(self.copy_file) self.menu.addAction(copy_action) add_action = qtw.QAction('Add to Playlist', self) add_action.triggered.connect(self.add_to_playlist) self.menu.addAction(add_action) self.playlistMenu = qtw.QMenu(self) delete_action = qtw.QAction('Remove File', self) delete_action.triggered.connect(self.delete_file) self.menu.addAction(delete_action) self.context_table = None self.present_dest = None PickleHandler.PickleReader(self.Base_Dir, self.local_table_model, self.remote_table_model)
def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.cookieJar = PersistenceCookieJar(QSettings("POWERUMC", "GmailTray")) self.onLoad();
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionGet_User_Info.triggered.connect(self.GetUserInfo) def open(self): print ("Open") def GetUserInfo(self): wd = InfoDialog(self).GetResult() if wd : print (wd) def closeEvent(self,event): print ("CloseEvent")
def __init__(self, app): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.app = app self.dir = os.path.expanduser("~") self.filepathShiftIn = "" self.filepathConcatIn1 = "" self.filepathConcatIn2 = "" self.filepathConcatOut = "" self.filepathSplitIn = "" self.filepathSplitOut1 = "" self.filepathSplitOut2 = "" self.ui.lineEditFormat.setText(REGEXP) self.current_action = self.ui.tabs.currentIndex() self.ui.lineEditPathShiftIn.setText(self.filepathShiftIn) self.ui.lineEditPathConcatIn1.setText(self.filepathConcatIn1) self.ui.lineEditPathConcatIn2.setText(self.filepathConcatIn2) self.ui.lineEditPathSplitIn.setText(self.filepathSplitIn)
def __init__(self): QtGui.QMainWindow.__init__(self) # This is always the samej self.ui=Ui_MainWindow() self.ui.setupUi(self) self.ui.DownloadFolder.setText(QtCore.QDir.homePath() + "/Downloads") self.ui.statusbar.showMessage("Ready") self.ui.BrowseButton.clicked.connect(self.SetDownloadFolder) self.ui.DownloadButton.clicked.connect(self.Download)
def __init__(self): super(Client, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.url = config.get('url', None) self.upload_url = config.get('upload_url', None) self.username = config.get('username', None) self.password = config.get('password', None) self.headers = {'Content-Type': 'application/json'} self.payload = {'username': self.username, 'password': self.password} self.pkiFile = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'token.pki') self.file_to_upload = "" # signal slot binding self.ui.btnUpload.clicked.connect(self.upload) self.ui.btnSelect.clicked.connect(self.select_file) self.ui.btnCopy.clicked.connect(self.copy_to_clipboard)
def __init__(self, c1, c2, parent=None): QMainWindow.__init__(self, parent) ui = Ui_MainWindow() ui.setupUi(self) colKeys = sorted(list(set(c1.keys).intersection(c2.keys))) self._mdl = TableModel(c1, c2, colKeys[0], self) ui.tableView.setModel(self._mdl) self._ui = ui ui.columnCombo.addItems(colKeys) ui.columnCombo.currentTextChanged.connect(self.updateCols) ui.columnCombo.setCurrentText(colKeys[0]) ui.refCombo.addItems(colKeys) ui.refCombo.currentTextChanged.connect(self.updateCols) ui.refCombo.addItems(colKeys) self.updateCols()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.itemBasePrice.setValidator(QtGui.QDoubleValidator()) self.ui.modifierEdit.setValidator(QtGui.QDoubleValidator()) # items self.ui.newItem.clicked.connect(self.newItemClicked) self.ui.deleteItem.clicked.connect(self.deleteItemClicked) self.ui.itemNameEdit.editingFinished.connect(self.saveItem) self.ui.itemBasePrice.editingFinished.connect(self.saveItem) self.ui.itemGroupSelect.itemClicked.connect(self.saveItem) self.ui.itemEditView.currentItemChanged.connect(self.itemEditViewSelectionChanged) self.ui.tabWidget.currentChanged.connect(self.refreshGroupsForItems) # groups self.ui.groupNameEdit.editingFinished.connect(self.saveGroup) self.ui.deleteGroup.clicked.connect(self.deleteGroupClicked) self.ui.newGroup.clicked.connect(self.newGroupClicked) self.ui.groupEditView.currentItemChanged.connect(self.groupEditViewSelectionChanged) # locations self.ui.newLocation.clicked.connect(self.newLocation) self.ui.deleteLocation.clicked.connect(self.deleteLocation) self.ui.locationNameEdit.editingFinished.connect(self.saveLocation) self.ui.locationSelection.currentItemChanged.connect(self.locationViewSelectionChanged) self.ui.tabWidget.currentChanged.connect(self.refreshModifiersForLocations) # modifiers self.ui.locationModifierSelection.currentItemChanged.connect(self.refreshModifiers) self.ui.locationSelection.currentItemChanged.connect(self.refreshModifiers) self.ui.saveModifier.clicked.connect(self.saveModifier) self.ui.modifierEdit.editingFinished.connect(self.saveModifier) self.ui.modifierTypeSelect.currentIndexChanged.connect(self.refreshModifiersForLocations) # Final view self.ui.tabWidget.currentChanged.connect(self.refreshFinalLocationsView) self.ui.locationsFinalView.currentItemChanged.connect(self.refreshFinalItemsView) self.ui.finalItemsView.setColumnCount(2) # menubar self.ui.actionNew.triggered.connect(self.newFile) self.ui.actionOpen.triggered.connect(self.openFile) self.ui.actionSave.triggered.connect(self.saveFile) # vars self.items = [] self.groups = [] self.locations = []
def __init__(self): self.lineEdit = QMainWindow() self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.main_win) self.ui.Enter_Button.clicked.connect(self.showpage1) self.ui.pushButton.clicked.connect(self.showpage0) self.ui.Exit_Button.clicked.connect(self.Exit) self.ui.Exit2_butt.clicked.connect(self.Exit) self.ui.Load_Data.clicked.connect(self.getCSV) self.ui.Display_Graph_1.clicked.connect(self.Display_1) self.ui.calendarWidget.clicked[QDate].connect(self.show_Probabilty) self.ui.checkBox_1.stateChanged.connect(self.Uncheck23) self.ui.checkBox_2.stateChanged.connect(self.Uncheck13) self.ui.checkBox_3.stateChanged.connect(self.Uncheck12)
def show(label_classes: [str], labelFormatter: LabelFormatterInterface, src: str, des: str, bak: str = None): """ Initialize and start app. :param src: source directory from which images are to be taken; subdirectories included. :param des: destination directory where labeled images are stored. :param bak: directory to store images that were left unlabeled. Leaving this option None will add a label to the image as per the label formatter used. :param label_classes: A list of class names. :return: """ app = QtWidgets.QApplication(sys.argv) ui = Ui_MainWindow(label_classes=label_classes, src=src, des=des, bak=bak, labelFormatter=labelFormatter) ui.show() sys.exit(app.exec_())
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) self.__windowlist = [] self.__windowindex = 0 self.__ui.tmpTextEdit.hide() self.__ui.tmpTextEdit.setLineWrapMode(QtGui.QTextEdit.WidgetWidth) self.minibuffer().hide() self.setObjectName(str(self)) self.completionswidget = CompletionsWidget(self.__ui.miniBuffer)
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.showFileDialog) def showFileDialog(self): fname = QFileDialog.getOpenFileName(self.ui.centralwidget, 'Open file')[0] if fname: f = open(fname, 'r') self.openDetectWindow(str(f.name)) f.close() def openDetectWindow(self, file_name): dialog = DetectObjectWindow(self, file_name) dialog.show()
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # set up ui self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Network Analyzer') # connect signals self.ui.portScan.clicked.connect(self._onPortScanClicked) self.ui.launchServer.clicked.connect(self._onLaunchServerClicked) self.ui.networkScan.clicked.connect(self._onNetworkScanClicked) self.ui.getHostNameButton.clicked.connect(self._onGetHostNameClicked) self.ui.quitButton.clicked.connect(self._onQuitClicked) def _onPortScanClicked(self): portScanWindow = PortScanWindow(self) portScanWindow.show() def _onLaunchServerClicked(self): launchWindow = LaunchServer(self) launchWindow.show() def _onNetworkScanClicked(self): networkScanWindow = NetworkScanDisplay(self) networkScanWindow.show() networkScanWindow.scan() def _onGetHostNameClicked(self): getHostNameWindow = GetHostNameWindow(self) getHostNameWindow.show() def _onQuitClicked(self): self.close()
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) self.setInstrumentInputs() ##defaults self.flightpath=-1.0 self.Theta=-1.0 self.stage1output=0.0 self.stage2output=0.0
def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setCentralWidget(self.ui.mangaTableView) self.newMangaDialog = NewMangaDialog() self.mangaDownloadDialog = MangaDownloadDialog() self.mangaTableModel = QStandardItemModel(0, 3, self) self.mangaTableModel.setHorizontalHeaderItem(0, QStandardItem(QString("Manga"))) self.mangaTableModel.setHorizontalHeaderItem(1, QStandardItem(QString("Latest Chapter"))) self.mangaTableModel.setHorizontalHeaderItem(2, QStandardItem(QString("Status"))) self.ui.mangaTableView.setModel(self.mangaTableModel) newMangaAction = QAction(QIcon("./icon/add.ico"),'New Manga', self) newMangaAction.setShortcut('Ctrl+N') newMangaAction.triggered.connect(self.newMangaDialog.show) removeMangaAction = QAction(QIcon("./icon/delete.ico"),'Remove Manga', self) removeMangaAction.setShortcut('Delete') preferencesAction = QAction(QIcon("./icon/preferences.ico"),'Preferences', self) aboutAction = QAction(QIcon("./icon/about.ico"),'About', self) self.ui.toolBar.addAction(newMangaAction) self.ui.toolBar.addAction(removeMangaAction) self.ui.toolBar.addSeparator() self.ui.toolBar.addAction(preferencesAction) self.ui.toolBar.addSeparator() self.ui.toolBar.addAction(aboutAction) self.progressBar = QProgressBar(self.ui.statusbar) self.ui.statusbar.addPermanentWidget(self.progressBar) self.progressBar.hide()
def __init__(self,path=''): super(MainWindow, self).__init__() self.ui=Ui_MainWindow() self.ui.setupUi(self) self.refreshTimer=None self.frameSkippingCounter=0 self.ui.graphicsView.setOptimizationFlags( QGraphicsView.DontAdjustForAntialiasing | QGraphicsView.DontClipPainter | QGraphicsView.DontSavePainterState) #self.ui.graphics.setResizeAnchor(self.ui.graphics.NoAnchor) #self.on_tab_currentChanged(self.ui.tab.currentIndex()) #self.showMaximized() self.simulationFramerate=10 # mouse event handlers for painting on simulation map: self.lastMousePosOnMap = None self.drawOnMap = anthill.Painter.drawObstacles # current painting function self.drawingStuff = False # flag for moving the camera around self.draggingCamera = False self.lastMousePosGlobal = None def handleMousePress(event): if event.button() == QtCore.Qt.LeftButton: self.drawingStuff = True self.lastMousePosOnMap = None self.handlePainterOption() self.ui.graphicsView.setMouseTracking(True) elif event.button() == QtCore.Qt.RightButton: self.draggingCamera = True self.lastMousePosGlobal = None self.ui.graphicsView.setDragMode( self.ui.graphicsView.ScrollHandDrag) self.ui.graphicsView.setMouseTracking(True) def handleMouseRelease(event): self.lastMousePosOnMap = None self.drawingStuff = False self.lastMousePosGlobal = None self.draggingCamera = False self.ui.graphicsView.setMouseTracking(False) self.ui.graphicsView.setDragMode(self.ui.graphicsView.NoDrag) def handleMouseMove(event): if self.drawingStuff: mouse_in_map_coords = ( self.ui.graphicsView.mapToScene( self.ui.graphicsView.mapFromGlobal(QCursor.pos()))) coords = list( map(lambda p: int(p), [mouse_in_map_coords.x(), mouse_in_map_coords.y()])) coords[1] -= 1 # fix misalignment if self.lastMousePosOnMap is None: self.lastMousePosOnMap = coords self.drawOnMap(self.world, self.lastMousePosOnMap[0], self.lastMousePosOnMap[1], coords[0], coords[1], self.ui.painterRadius.value(), self.ui.painterIntensity.value() * 0.01 *\ anthill.WorldGenerator.default_pheromone_params.scale) self.lastMousePosOnMap = coords if self.draggingCamera: if self.lastMousePosGlobal is None: self.lastMousePosGlobal = QCursor.pos() delta = QCursor.pos() - self.lastMousePosGlobal self.ui.graphicsView.setTransformationAnchor( self.ui.graphicsView.NoAnchor) self.ui.graphicsView.translate(delta.x(), delta.y()) self.lastMousePosGlobal = QCursor.pos() self.ui.graphicsView.mousePressEvent = handleMousePress self.ui.graphicsView.mouseReleaseEvent = handleMouseRelease self.ui.graphicsView.mouseMoveEvent = handleMouseMove def handleWheelEvent(event): self.ui.graphicsView.setTransformationAnchor( self.ui.graphicsView.AnchorViewCenter) scaleFactor = 1.15 if event.angleDelta().y() < 0: scaleFactor = 1.0 / scaleFactor self.ui.graphicsView.scale(scaleFactor, scaleFactor) self.ui.graphicsView.wheelEvent = handleWheelEvent # configure world self.world = anthill.World(); self.paused = True self.statistics = Statistics(self.ui.stats_label, self.ui.gridLayout_3)
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self)
import roslib roslib.load_manifest('cob_script_server') import rospy from std_msgs.msg import String import threading from simple_script_server import simple_script_server from cob_srvs.srv import Trigger import sys, os from PyQt4.QtCore import QThread, pyqtSignal from PyQt4.QtGui import QApplication, QMainWindow from Ui_MainWindow import Ui_MainWindow app = QApplication(sys.argv) window = QMainWindow() ui = Ui_MainWindow() ui.setupUi(window) # ROS - Worker Thread class RosThread(QThread): add = pyqtSignal(str) rem = pyqtSignal(str) name_gripper="3-Finger-Hand" name_vacuum ="Vacuum-Cleaner" def __init__(self, ui, parent = None): QThread.__init__(self, parent) self.ui = ui self.mode="linear" self.add[str].connect(self.onAdd)
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setCentralWidget(self.ui.mangaTableView) self.newMangaDialog = NewMangaDialog() self.mangaDownloadDialog = MangaDownloadDialog() self.mangaTableModel = QStandardItemModel(0, 3, self) self.mangaTableModel.setHorizontalHeaderItem(0, QStandardItem(QString("Manga"))) self.mangaTableModel.setHorizontalHeaderItem(1, QStandardItem(QString("Latest Chapter"))) self.mangaTableModel.setHorizontalHeaderItem(2, QStandardItem(QString("Status"))) self.ui.mangaTableView.setModel(self.mangaTableModel) newMangaAction = QAction(QIcon("./icon/add.ico"),'New Manga', self) newMangaAction.setShortcut('Ctrl+N') newMangaAction.triggered.connect(self.newMangaDialog.show) removeMangaAction = QAction(QIcon("./icon/delete.ico"),'Remove Manga', self) removeMangaAction.setShortcut('Delete') preferencesAction = QAction(QIcon("./icon/preferences.ico"),'Preferences', self) aboutAction = QAction(QIcon("./icon/about.ico"),'About', self) self.ui.toolBar.addAction(newMangaAction) self.ui.toolBar.addAction(removeMangaAction) self.ui.toolBar.addSeparator() self.ui.toolBar.addAction(preferencesAction) self.ui.toolBar.addSeparator() self.ui.toolBar.addAction(aboutAction) self.progressBar = QProgressBar(self.ui.statusbar) self.ui.statusbar.addPermanentWidget(self.progressBar) self.progressBar.hide() def closeEvent(self, QCloseEvent): mangaList = [] for i in range(self.mangaTableModel.rowCount()): mangaList.append({ "name" : str(self.mangaTableModel.item(i, 0).text()), "latestChapter" : str(self.mangaTableModel.item(i, 1).text()), "status" : "Updated", "link" : "/trial.html" }) self.emit(SIGNAL("applicationClosed"),mangaList) def initializeProgressBar(self, size): self.progressBar.setRange(0, size) self.progressBar.setValue(0) self.progressBar.show() def updateProgressBar(self, value): self.progressBar.setValue(value) def updateStatusBar(self, msg): self.ui.statusbar.showMessage(msg) def updateMangaTable(self, chapter): isFound = False for i in range(self.mangaTableModel.rowCount()): mangaItem = self.mangaTableModel.item(i) if mangaItem.text() == chapter["name"]: self.mangaTableModel.item(i, 1).setText(chapter["latestChapter"]) self.mangaTableModel.item(i, 2).setText(chapter["status"]) isFound = True break if not isFound: self.addRowToMangaTable(chapter) def addMangaListToMangaTable(self, mangaList): for i in range(len(mangaList)): self.addRowToMangaTable(mangaList[i]) def addRowToMangaTable(self, manga): i = self.mangaTableModel.rowCount() mangaItem = QStandardItem(QString(manga["name"])) latestChapterItem = QStandardItem(QString(manga["latestChapter"])) statusItem = QStandardItem(QString(manga["status"])) brush = QBrush(QColor(255, 255, 255)) if i%2==0 else QBrush(QColor(200, 200, 200)) mangaItem.setBackground(brush) latestChapterItem.setBackground(brush) statusItem.setBackground(brush) self.mangaTableModel.setItem(i, 0, mangaItem) self.mangaTableModel.setItem(i, 1, latestChapterItem) self.mangaTableModel.setItem(i, 2, statusItem)
def __init__(self, parent=None): """ Intialization and set up """ # Base class QtGui.QMainWindow.__init__(self,parent) # Mantid configuration config = ConfigService.Instance() self._instrument = config["default.instrument"] # Central widget self.centralwidget = QtGui.QWidget(self) # UI Window (from Qt Designer) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Do initialize plotting vecx, vecy, xlim, ylim = self.computeMock() self.mainline = self.ui.mainplot.plot(vecx, vecy, 'r-') leftx = [xlim[0], xlim[0]] lefty = [ylim[0], ylim[1]] self.leftslideline = self.ui.mainplot.plot(leftx, lefty, 'b--') rightx = [xlim[1], xlim[1]] righty = [ylim[0], ylim[1]] self.rightslideline = self.ui.mainplot.plot(rightx, righty, 'g--') upperx = [xlim[0], xlim[1]] uppery = [ylim[1], ylim[1]] self.upperslideline = self.ui.mainplot.plot(upperx, uppery, 'b--') lowerx = [xlim[0], xlim[1]] lowery = [ylim[0], ylim[0]] self.lowerslideline = self.ui.mainplot.plot(lowerx, lowery, 'g--') self.ui.graphicsView.mpl_connect('button_press_event', self.on_mouseDownEvent) # Set up horizontal slide (integer) and string value self._leftSlideValue = 0 self._rightSlideValue = 99 self.ui.horizontalSlider.setRange(0, 100) self.ui.horizontalSlider.setValue(self._leftSlideValue) self.ui.horizontalSlider.setTracking(True) self.ui.horizontalSlider.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider, SIGNAL('valueChanged(int)'), self.move_leftSlider) self.ui.horizontalSlider_2.setRange(0, 100) self.ui.horizontalSlider_2.setValue(self._rightSlideValue) self.ui.horizontalSlider_2.setTracking(True) self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider_2, SIGNAL('valueChanged(int)'), self.move_rightSlider) # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), # self.set_startTime) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"), self.set_startTime) # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), # self.set_stopTime) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) self.connect(self.ui.pushButton_setTf, QtCore.SIGNAL("clicked()"), self.set_stopTime) # File loader self.scanEventWorkspaces() self.connect(self.ui.pushButton_refreshWS, SIGNAL('clicked()'), self.scanEventWorkspaces) self.connect(self.ui.pushButton_browse, SIGNAL('clicked()'), self.browse_File) self.connect(self.ui.pushButton_load, SIGNAL('clicked()'), self.load_File) self.connect(self.ui.pushButton_3, SIGNAL('clicked()'), self.use_existWS) # Set up time self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) # Filter by time self.connect(self.ui.pushButton_filterTime, SIGNAL('clicked()'), self.filterByTime) # Filter by log value self.ui.lineEdit_5.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_5)) self.ui.lineEdit_6.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_6)) self.ui.lineEdit_7.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_7)) self.ui.lineEdit_8.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_8)) self.ui.lineEdit_9.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_9)) self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"), self.set_minLogValue) self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"), self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] self.ui.comboBox_4.addItems(dirchangeops) logboundops = ["Centre", "Left"] self.ui.comboBox_5.addItems(logboundops) self.connect(self.ui.pushButton_4, SIGNAL('clicked()'), self.plotLogValue) self.connect(self.ui.pushButton_filterLog, SIGNAL('clicked()'), self.filterByLogValue) # Set up vertical slide self._upperSlideValue = 99 self._lowerSlideValue = 0 self.ui.verticalSlider.setRange(0, 100) self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.verticalSlider.setTracking(True) self.connect(self.ui.verticalSlider, SIGNAL('valueChanged(int)'), self.move_upperSlider) self.ui.verticalSlider_2.setRange(0, 100) self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.verticalSlider_2.setTracking(True) self.connect(self.ui.verticalSlider_2, SIGNAL('valueChanged(int)'), self.move_lowerSlider) # Set up for filtering (advanced setup) self._tofcorrection = False self.ui.checkBox_filterByPulse.setChecked(False) self.ui.checkBox_from1.setChecked(False) self.ui.checkBox_groupWS.setChecked(True) self.connect(self.ui.comboBox_tofCorr, SIGNAL('currentIndexChanged(int)'), self.showHideEi) self.connect(self.ui.pushButton_refreshCorrWSList, SIGNAL('clicked()'), self._searchTableWorkspaces) self.ui.lineEdit_Ei.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_Ei)) self.ui.label_Ei.hide() self.ui.lineEdit_Ei.hide() self.ui.label_Ei_2.hide() self.ui.comboBox_corrWS.hide() self.ui.pushButton_refreshCorrWSList.hide() # Error message # self.connect(self.ui.pushButton_clearerror, SIGNAL('clicked()'), self._clearErrorMsg) # self.ui.plainTextEdit_ErrorMsg.setReadOnly(True) # self.ui.label_error.hide() # Set up for workspaces self._dataWS = None self._sampleLogNames = [] self._sampleLog = None # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() self.ui.label_avg.hide() self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() self.ui.label_logname.hide() self.ui.label_lognamevalue.hide() self.ui.label_logsize.hide() self.ui.label_logsizevalue.hide() # Default self._defaultdir = os.getcwd() # self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) # QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) # QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # self.setInstrumentInputs() ##defaults return
class MainWindow(QtGui.QMainWindow): needsThetaInputList = ['Momentum transfer (Q Angstroms^-1)', 'd-Spacing (Angstroms)'] needsThetaOutputList = ['Momentum transfer (Q Angstroms^-1)', 'd-Spacing (Angstroms)'] needsFlightPathInputList = ['Time of flight (microseconds)'] needsFlightPathOutputList = ['Time of flight (microseconds)'] def thetaEnable (self, enabled): self.ui.lineEdit_4.setEnabled(enabled) if enabled == False: self.ui.lineEdit_4.clear() def flightPathEnable (self, enabled): self.ui.lineEdit_3.setEnabled(enabled) if enabled == False: self.ui.lineEdit_3.clear() def setInstrumentInputs (self): #disable both self.thetaEnable(False) self.flightPathEnable(False) #get the values of the two unit strings inOption=self.ui.inputUnits.currentText() outOption=self.ui.outputUnits.currentText() #for theta: enable if input or output unit requires it if inOption in self.needsThetaInputList: self.thetaEnable(True) if outOption in self.needsThetaOutputList: self.thetaEnable(True) #for flightpath: enable if input or output unit requires it if inOption in self.needsFlightPathInputList: self.flightPathEnable(True) if outOption in self.needsFlightPathOutputList: self.flightPathEnable(True) def __init__(self, parent=None): QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) self.setInstrumentInputs() ##defaults self.flightpath=-1.0 self.Theta=-1.0 self.stage1output=0.0 self.stage2output=0.0 def convert(self): if self.ui.InputVal.text() == "": return try: inOption=self.ui.inputUnits.currentText() outOption=self.ui.outputUnits.currentText() if self.ui.lineEdit_3.text() !='': self.flightpath = float(self.ui.lineEdit_3.text()) else: self.flightpath = -1.0 if self.ui.lineEdit_4.text() !='': self.Theta = ((float(self.ui.lineEdit_4.text()) * 3.14159265358979323846264) / 360.0) self.Theta = -1.0 self.stage1output= self.input2energy(float(self.ui.InputVal.text()),inOption) self.stage2output= self.energy2output(self.stage1output,outOption) self.ui.lineEdit_2.clear() self.ui.lineEdit_2.insert(str(self.stage2output)) except Exception, e: QtGui.QMessageBox.warning(self, "TofConverter", str(e)) return
class Frame(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) self.__windowlist = [] self.__windowindex = 0 self.__ui.tmpTextEdit.hide() self.__ui.tmpTextEdit.setLineWrapMode(QtGui.QTextEdit.WidgetWidth) self.minibuffer().hide() self.setObjectName(str(self)) self.completionswidget = CompletionsWidget(self.__ui.miniBuffer) def set_active(self): log.debug("Frame gets active") def closeEvent(self, closeevent): log.debug("Close event") def set_minibuffer(self, txt): self.__ui.miniBuffer.set(txt) def append_minibuffer(self, txt): self.__ui.miniBuffer.append(txt) def focus_minibuffer(self): self.__ui.miniBuffer.setFocus() def keyPressEvent(self, ke): log.debug("FRAME keyPressEvent") QtGui.QMainWindow.keyPressEvent(self, ke) def minibuffer(self): return self.__ui.miniBuffer def append_status(self, what): sb = self.statusBar() sb.showMessage(str(sb.currentMessage()) + what) def set_status(self, what, duration=0): log.debug("set_status %s", what) self.statusBar().showMessage(what, duration) def set_completion(self, what): self.set_minibuffer(what) def show_completions(self, completions): self.completionswidget.show_completions(completions, self) def next_completion(self): return self.completionswidget.next() def prev_completion(self): return self.completionswidget.prev() def unshow_completions(self): log.debug("unshow completions") self.completionswidget.hide() def set_prompt(self, what): self.__ui.promptLabel.show() self.__ui.promptLabel.setText(what) def new_dock_widget(self, buffername="*scratch*"): ndw = DockWidget(self) self.addDockWidget(QtCore.Qt.DockWidgetArea(4),ndw) self.__windowlist.append(ndw) return ndw def dockwidgets(self): return self.__windowlist def remove(self, window): log.debug("remove %s", window) assert window in self.__windowlist self.__windowlist.remove(window) window.close() def other_window(self): self.focusNextChild() def keyboard_quit(self): self.minibuffer().keyboard_quit() self.set_status("Quit") self.unshow_completions() def focusInEvent(self, focusevent): log.debug("Gets focus, parent is %s", self.parent()) QtGui.QMainWindow.focusInEvent(self, focusevent) def focusOutEvent(self, focusevent): log.debug("loses focus, parent is %s", self.parent()) QtGui.QMainWindow.focusOutEvent(self, focusevent)
class GmailWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.cookieJar = PersistenceCookieJar(QSettings("POWERUMC", "GmailTray")) self.onLoad(); def onLoad(self): self.menuBar().hide() self.menuBar().close() self.resize(500, 600) # SSL 구 sslcfg = QSslConfiguration.defaultConfiguration() ca_list = sslcfg.caCertificates() ca_new = QSslCertificate.fromData('CaCertificates') ca_list += ca_new sslcfg.setCaCertificates(ca_list) sslcfg.setProtocol(QSsl.AnyProtocol) QSslConfiguration.setDefaultConfiguration(sslcfg) # WebView 구성 QNetworkProxyFactory.setUseSystemConfiguration(True) set = self.ui.webView.settings().globalSettings() set.setAttribute(QWebSettings.PluginsEnabled, True) set.setAttribute(QWebSettings.AutoLoadImages, True) set.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True) set.setAttribute(QWebSettings.JavascriptEnabled, True) set.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) set.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) # 툴바 구성 toolbar = QToolBar('Command Toolbar', self) toolbar.addActions(self.ui.menuCommand.actions()) toolbar.addSeparator() toolbar.addActions(self.ui.menuCommand.actions()) self.addToolBar(toolbar) self.ui.actionGo_Home.triggered.connect(lambda: ()) self.ui.actionRefresh.triggered.connect(lambda: ()) self.ui.actionNext.triggered.connect(lambda: ()) self.ui.actionPrevious.triggered.connect(lambda: ()) self.ui.actionHelp.triggered.connect(lambda: ()) self.ui.actionPreferences.triggered.connect(lambda: ()) self.ui.actionHelp.setEnabled(False) self.ui.actionPreferences.setEnabled(False) # 트레이 아이콘 설 traymenu = QMenu('TRAY MENU', self) if sys.platform == 'darwin': action_open = QAction('O&pen', self) action_open.triggered.connect(lambda: ()) traymenu.addAction(action_open) traymenu.addSeparator() action_quit = QAction('Q&uit', self) action_quit.triggered.connect(lambda : ()) traymenu.addAction(action_quit) tray = HostSystemCounterTrayIcon(QImage('facebook.jpg')) tray.setContextMenu(traymenu) tray.setIcon(QIcon('facebook.jpg')) tray.show() tray.activated.connect(lambda reason:()) tray.messageClicked.connect(lambda: ()) # SSL 설정 manager = SslNetworkAccessManager(self) manager.setCookieJar(self.cookieJar)
class CDL(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.wait = Ui_Wait(self) self.downloadsManager = DownloadsManager(self, self.ui.downloadsList) global config self.videosManager = VideosManager(self.ui.downloadsList, self.ui.categoriesList) QObject.connect(self.downloadsManager, SIGNAL("download_terminated(PyQt_PyObject)"), self.add_video) QObject.connect(self, SIGNAL("refresh(PyQt_PyObject)"), self.downloadsManager.refresh_downloads_list) QObject.connect(self.ui.downloadsList, SIGNAL("download(PyQt_PyObject)"), self.downloadsManager.download) QObject.connect(self, SIGNAL("construct_downloads(PyQt_PyObject)"), self.generate_downloads) QObject.connect(self.downloadsManager, SIGNAL("blacklist(PyQt_PyObject)"), self.blacklist) QObject.connect(self.ui.wait, SIGNAL("open()"), self.ui.wait.open) QObject.connect(self.ui.wait, SIGNAL("close()"), self.ui.wait.close) def showPreferences(self): self.pref = Preferences(self) QObject.connect(self.pref, SIGNAL("configChanged(PyQt_PyObject)"), self.videosManager.refresh_categoriesList) self.pref.show() def blacklist(self, download): config.blacklist.append(download) DAO.commit() def generate_downloads(self, list_data): downloads = [] for d in list_data: download = DAO.download(d['url'], d['category'], d['description'], d['name']) downloads.append(download) self.emit(SIGNAL("refresh(PyQt_PyObject)"), downloads) def add_video(self, download): new_video = Video(download.url, download.category, download.name, download.date, download.description) self.videosManager.add_new_video(new_video) def refresh_downloads_list(self): def threadListNewVideos(self): self.ui.wait.emit(SIGNAL("open()")) list_data = [] for c in config.categories: list_data.extend(c.find_new_videos_availables(config.blacklist)) self.emit(SIGNAL("construct_downloads(PyQt_PyObject)"), list_data) self.ui.wait.emit(SIGNAL("close()")) if self.downloadsManager.nb_downloads_in_progress != 0: r = QMessageBox.critical(self, "Veuillez patienter !", u"Tous les téléchargements ne sont pas terminés, veuillez patienter quelques instants avant de raffraichir cette liste") return config.blacklist config.categories = [DAO.merge(x) for x in config.categories] threading.Thread(target=threadListNewVideos, args=[self]).start() def quit(self): if hasattr(self, 'pref'): self.pref.close() if hasattr(self, 'downloadsManager'): self.downloadsManager.ui_download.close() self.close() def closeEvent(self, closeEvent): self.quit() @pyqtSlot() def on_pushButtonRefresh_clicked(self): self.refresh_downloads_list() @pyqtSlot() def on_pushButtonDownload_clicked(self): self.downloadsManager.download_selected() @pyqtSlot() def on_pushButtonPlay_clicked(self): self.videosManager.play_selected() @pyqtSlot() def on_pushButtonBlacklist_clicked(self): try: self.downloadsManager.blacklist_selected() except Exception, e: print "error while blacklisting video" print traceback.format_exc(e)
class MainWindow(QMainWindow): def __init__(self, app): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.app = app self.dir = os.path.expanduser("~") self.filepathShiftIn = "" self.filepathConcatIn1 = "" self.filepathConcatIn2 = "" self.filepathConcatOut = "" self.filepathSplitIn = "" self.filepathSplitOut1 = "" self.filepathSplitOut2 = "" self.ui.lineEditFormat.setText(REGEXP) self.current_action = self.ui.tabs.currentIndex() self.ui.lineEditPathShiftIn.setText(self.filepathShiftIn) self.ui.lineEditPathConcatIn1.setText(self.filepathConcatIn1) self.ui.lineEditPathConcatIn2.setText(self.filepathConcatIn2) self.ui.lineEditPathSplitIn.setText(self.filepathSplitIn) def browse(self, lineEdit): filepath = QFileDialog.getOpenFileName(self, QApplication.translate("Main", "Ouvrir", None, QApplication.UnicodeUTF8), self.dir, "Sous-titres .srt (*.srt)") if not filepath: return self.dir = os.path.dirname(str(filepath)) lineEdit.setText(filepath) return filepath def launch_shift(self): self.ui.textEditShiftOut.clear() sign = self.ui.comboBoxSignShift.itemText(self.ui.comboBoxSignShift.currentIndex()) h = self.ui.spinBoxShiftH.value() m = self.ui.spinBoxShiftM.value() s = self.ui.spinBoxShiftS.value() ms = self.ui.spinBoxShiftMS.value() format_ = str(self.ui.lineEditFormat.text()) filepath = str(self.ui.lineEditPathShiftIn.text()) if not filepath: return if self.ui.radioButtonBeginAt.isChecked(): delta = get_delta(h, m, s, ms, "+") first = get_first_time(filepath, format_) delta = delta - first else: delta = get_delta(h, m, s, ms, sign) new_lines = convert(filepath, delta, format_) new_lines = "\n".join(line.replace("\r\n", "").replace("\n", "") for line in new_lines) self.ui.textEditShiftOut.appendPlainText(new_lines) cursor = self.ui.textEditShiftOut.cursorForPosition(QPoint(0,0)) cursor.setPosition(QTextCursor.Start); self.ui.textEditShiftOut.setTextCursor(cursor); vScrollBar = self.ui.textEditShiftOut.verticalScrollBar() vScrollBar.setSliderPosition(0) def launch_concat(self): self.ui.textEditConcatOut.clear() sign = self.ui.comboBoxSignConcat.itemText(self.ui.comboBoxSignConcat.currentIndex()) decal_h = self.ui.spinBoxConcatH.value() decal_m = self.ui.spinBoxConcatM.value() decal_s = self.ui.spinBoxConcatS.value() decal_ms = self.ui.spinBoxConcatMS.value() format_ = str(self.ui.lineEditFormat.text()) filepathIn1 = str(self.ui.lineEditPathConcatIn1.text()) filepathIn2 = str(self.ui.lineEditPathConcatIn2.text()) if not filepathIn1 or not filepathIn2: return input_delta = get_delta(decal_h, decal_m, decal_s, decal_ms, sign) fd = open(filepathIn1, 'r') lines = fd.readlines() fd.close() last_lines = lines[len(lines)-10:len(lines)] for l in lines: self.ui.textEditConcatOut.appendPlainText(l.replace("\r\n", "").replace("\n", "")) last_delta = None for l in last_lines: matches = re.compile(format_).findall(l) if len(matches) != 0: e_h = int(matches[0][4]) e_m = int(matches[0][5]) e_s = int(matches[0][6]) e_ms = int(matches[0][7]) last_delta = get_delta(e_h, e_m, e_s, e_ms) total_delta = last_delta + input_delta new_lines2 = convert(filepathIn2, total_delta, format_) for l in new_lines2: self.ui.textEditConcatOut.appendPlainText(l.replace("\r\n", "").replace("\n", "")) vScrollBar = self.ui.textEditConcatOut.verticalScrollBar() vScrollBar.setSliderPosition(0) def launch_split(self): self.ui.textEditSplitOut1.clear() self.ui.textEditSplitOut2.clear() decal_h = self.ui.spinBoxSplitH.value() decal_m = self.ui.spinBoxSplitM.value() decal_s = self.ui.spinBoxSplitS.value() decal_ms = self.ui.spinBoxSplitMS.value() format_ = str(self.ui.lineEditFormat.text()) filepathIn = str(self.ui.lineEditPathSplitIn.text()) if not filepathIn: return split_delta = get_delta(decal_h, decal_m, decal_s, decal_ms) fd = open(filepathIn, 'r') lines = fd.readlines() fd.close() output = self.ui.textEditSplitOut1 last_delta = get_delta(0, 0, 0, 0) for l in lines: matches = re.compile(format_).findall(l) new_line = l new_b_dt = 0 new_e_dt = 0 if len(matches) != 0: b_h = int(matches[0][0]) b_m = int(matches[0][1]) b_s = int(matches[0][2]) b_ms = int(matches[0][3]) e_h = int(matches[0][4]) e_m = int(matches[0][5]) e_s = int(matches[0][6]) e_ms = int(matches[0][7]) b_dt = datetime.time(hour=b_h, minute=b_m, second=b_s, microsecond=b_ms) e_dt = datetime.time(hour=e_h, minute=e_m, second=e_s, microsecond=e_ms) current_delta = get_delta(b_h, b_m, b_s, b_ms) zero_delta = get_delta(0, 0, 0, 0) if split_delta - current_delta > zero_delta: new_b_delta = get_delta(b_h, b_m, b_s, b_ms) new_e_delta = get_delta(e_h, e_m, e_s, e_ms) last_delta = new_b_delta new_line = "%s --> %s" % ( format_delta(new_b_delta), format_delta(new_e_delta) ) else: output = self.ui.textEditSplitOut2 new_b_delta = get_delta(b_h, b_m, b_s, b_ms) - last_delta new_e_delta = get_delta(e_h, e_m, e_s, e_ms) - last_delta new_line = "%s --> %s" % ( format_delta(new_b_delta), format_delta(new_e_delta) ) output.appendPlainText(new_line.replace("\r\n", "\n").replace("\n", "")) output1 = self.ui.textEditSplitOut1.toPlainText() output2 = self.ui.textEditSplitOut2.toPlainText() # Récupération de la dernière ligne (correspondant au numéro) # pour la rajouter en début de 2è fichier cur1 = self.ui.textEditSplitOut1.cursorForPosition(QPoint(0,0)) cur2 = self.ui.textEditSplitOut2.cursorForPosition(QPoint(0,0)) cur1.movePosition(QTextCursor.End) cur2.movePosition(QTextCursor.Start) cur1.select(QTextCursor.LineUnderCursor) last1 = cur1.selectedText() + "\n" cur1.removeSelectedText() cur2.insertText(last1) vScrollBar2 = self.ui.textEditSplitOut2.verticalScrollBar() vScrollBar2.setSliderPosition(0) @pyqtSlot(str) def on_lineEditPathConcatIn1_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditConcatIn1.appendPlainText(l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathConcatIn2_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditConcatIn2.appendPlainText(l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathConcatOut_textChanged(self, path): self.filepathConcatOut = path @pyqtSlot(str) def on_lineEditPathSplitIn_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditSplitIn.appendPlainText(l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathSplitOut1_textChanged(self, path): self.filepathSplitOut1 = path @pyqtSlot(str) def on_lineEditPathSplitOut2_textChanged(self, path): self.filepathSplitOut2 = path @pyqtSlot() def on_pushButtonBrowseShiftIn_clicked(self): self.filepathShiftIn = self.browse(self.ui.lineEditPathShiftIn) @pyqtSlot() def on_pushButtonBrowseConcatIn1_clicked(self): self.filepathConcatIn1 = self.browse(self.ui.lineEditPathConcatIn1) @pyqtSlot() def on_pushButtonBrowseConcatIn2_clicked(self): self.filepathConcatIn2 = self.browse(self.ui.lineEditPathConcatIn2) @pyqtSlot() def on_pushButtonBrowseConcatOut_clicked(self): self.filepathConcatOut = self.browse(self.ui.lineEditPathConcatOut) @pyqtSlot() def on_pushButtonBrowseSplitIn_clicked(self): self.filepathSplitIn = self.browse(self.ui.lineEditPathSplitIn) @pyqtSlot() def on_pushButtonBrowseSplitOut1_clicked(self): self.filepathSplitOut1 = self.browse(self.ui.lineEditPathSplitOut1) @pyqtSlot() def on_pushButtonBrowseSplitOut2_clicked(self): self.filepathSplitOut2 = self.browse(self.ui.lineEditPathSplitOut2) @pyqtSlot() def on_pushButtonLaunch_clicked(self): if self.current_action == ACTION_SHIFT: self.launch_shift() elif self.current_action == ACTION_CONCAT: self.launch_concat() elif self.current_action == ACTION_SPLIT: self.launch_split() else: print "Pas d'action correspondante pour %s" % self.current_action @pyqtSlot(int) def on_tabs_currentChanged(self, num): self.current_action = num @pyqtSlot() def on_pushButtonCopy_clicked(self): if self.current_action == ACTION_SHIFT: self.app.clipboard().clear() self.ui.textEditShiftOut.selectAll() self.app.clipboard().setText(self.ui.textEditShiftOut.toPlainText()) elif self.current_action == ACTION_CONCAT: self.app.clipboard().clear() self.ui.textEditConcatOut.selectAll() self.app.clipboard().setText(self.ui.textEditConcatOut.toPlainText()) elif self.current_action == ACTION_SPLIT: self.app.clipboard().clear() self.ui.textEditSplitOut1.selectAll() self.ui.textEditSplitOut2.selectAll() self.app.clipboard().setText( self.ui.textEditSplitOut1.toPlainText() + self.ui.textEditSplitOut2.toPlainText() ) else: print "Pas d'action correspondante pour %s" % self.current_action @pyqtSlot() def on_pushButtonOverwrite_clicked(self): try: if self.current_action == ACTION_SHIFT: if not self.filepathShiftIn: return os.rename(self.filepathShiftIn, self.filepathShiftIn+'.org') fd = open(self.filepathShiftIn, 'w') fd.write(self.ui.textEditShiftOut.toPlainText()) fd.close() self.ui.statusbar.showMessage(u"Le fichier a bien été écrasé. Une sauvegarde a été effectuée") elif self.current_action == ACTION_CONCAT: if not self.filepathConcatOut: return fd = open(self.filepathConcatOut, 'w') fd.write(self.ui.textEditConcatOut.toPlainText()) fd.close() self.ui.statusbar.showMessage(u"Le fichier a bien été écrit.") elif self.current_action == ACTION_SPLIT: if not self.filepathSplitOut1 or not self.filepathSplitOut2: return fd = open(self.filepathSplitOut1, 'w') fd.write(self.ui.textEditSplitOut1.toPlainText()) fd.close() fd = open(self.filepathSplitOut2, 'w') fd.write(self.ui.textEditSplitOut2.toPlainText()) fd.close() self.ui.statusbar.showMessage(u"Les fichiers ont bien été écrit.") else: print "Pas d'action correspondante pour %s" % self.current_action except Exception, e: print e self.ui.statusbar.showMessage(u"Le fichier n'a pas été bien généré. Voir la sortie d'erreur")
class MainWindow(QMainWindow): def __init__(self,path=''): super(MainWindow, self).__init__() self.ui=Ui_MainWindow() self.ui.setupUi(self) self.refreshTimer=None self.frameSkippingCounter=0 self.ui.graphicsView.setOptimizationFlags( QGraphicsView.DontAdjustForAntialiasing | QGraphicsView.DontClipPainter | QGraphicsView.DontSavePainterState) #self.ui.graphics.setResizeAnchor(self.ui.graphics.NoAnchor) #self.on_tab_currentChanged(self.ui.tab.currentIndex()) #self.showMaximized() self.simulationFramerate=10 # mouse event handlers for painting on simulation map: self.lastMousePosOnMap = None self.drawOnMap = anthill.Painter.drawObstacles # current painting function self.drawingStuff = False # flag for moving the camera around self.draggingCamera = False self.lastMousePosGlobal = None def handleMousePress(event): if event.button() == QtCore.Qt.LeftButton: self.drawingStuff = True self.lastMousePosOnMap = None self.handlePainterOption() self.ui.graphicsView.setMouseTracking(True) elif event.button() == QtCore.Qt.RightButton: self.draggingCamera = True self.lastMousePosGlobal = None self.ui.graphicsView.setDragMode( self.ui.graphicsView.ScrollHandDrag) self.ui.graphicsView.setMouseTracking(True) def handleMouseRelease(event): self.lastMousePosOnMap = None self.drawingStuff = False self.lastMousePosGlobal = None self.draggingCamera = False self.ui.graphicsView.setMouseTracking(False) self.ui.graphicsView.setDragMode(self.ui.graphicsView.NoDrag) def handleMouseMove(event): if self.drawingStuff: mouse_in_map_coords = ( self.ui.graphicsView.mapToScene( self.ui.graphicsView.mapFromGlobal(QCursor.pos()))) coords = list( map(lambda p: int(p), [mouse_in_map_coords.x(), mouse_in_map_coords.y()])) coords[1] -= 1 # fix misalignment if self.lastMousePosOnMap is None: self.lastMousePosOnMap = coords self.drawOnMap(self.world, self.lastMousePosOnMap[0], self.lastMousePosOnMap[1], coords[0], coords[1], self.ui.painterRadius.value(), self.ui.painterIntensity.value() * 0.01 *\ anthill.WorldGenerator.default_pheromone_params.scale) self.lastMousePosOnMap = coords if self.draggingCamera: if self.lastMousePosGlobal is None: self.lastMousePosGlobal = QCursor.pos() delta = QCursor.pos() - self.lastMousePosGlobal self.ui.graphicsView.setTransformationAnchor( self.ui.graphicsView.NoAnchor) self.ui.graphicsView.translate(delta.x(), delta.y()) self.lastMousePosGlobal = QCursor.pos() self.ui.graphicsView.mousePressEvent = handleMousePress self.ui.graphicsView.mouseReleaseEvent = handleMouseRelease self.ui.graphicsView.mouseMoveEvent = handleMouseMove def handleWheelEvent(event): self.ui.graphicsView.setTransformationAnchor( self.ui.graphicsView.AnchorViewCenter) scaleFactor = 1.15 if event.angleDelta().y() < 0: scaleFactor = 1.0 / scaleFactor self.ui.graphicsView.scale(scaleFactor, scaleFactor) self.ui.graphicsView.wheelEvent = handleWheelEvent # configure world self.world = anthill.World(); self.paused = True self.statistics = Statistics(self.ui.stats_label, self.ui.gridLayout_3) def __exit__(self): self.refreshTimer.stop() def drawPheromoneMap(self,map, baseRGB=(50,30,100), baseRGB2=(10,10,10) ): data=map.getMap() data=list(data) scene=self.ui.graphicsView.scene() for x,a in enumerate(data): if(x > self.world.getDimensions().posX()): break for y,b in enumerate(a): if(y > self.world.getDimensions().posY()): break if(b<0.1): # too weak to be sensed continue alpha=30+b*8 if(alpha>100): # clamp alpha=100 pbrush=QBrush(QColor(baseRGB[0],baseRGB[1],baseRGB[2], alpha)) ppen=QPen(QBrush(QColor(baseRGB2[0],baseRGB2[1],baseRGB2[2], alpha)),0) scene.addRect(x,y,1,1,pen=ppen,brush=pbrush) def drawEntities(self,ents,qpen,qbrush,ellipse=False,drawRange=None): ents=[ents[a] for a in range(len(ents))] scene=self.ui.graphicsView.scene() for ent in ents: x=ent.getPos().posX() y=ent.getPos().posY() if(ellipse): scene.addEllipse(x,y,1,1,pen=qpen,brush=qbrush) else: scene.addRect(x,y,1,1,pen=qpen,brush=qbrush) if(drawRange!=None): rangepen=QPen(QBrush(QColor(0,0,0,30)),0) rangeBrush=QBrush(QColor(255,255,255,10)) scene.addEllipse((x-drawRange), (y-drawRange), drawRange*2,drawRange*2, brush=rangeBrush, pen=rangepen) def handlePainterOption(self): # we're checking against button text which is bad but it's the easiest # way I think... if self.ui.painterButtonGroup.checkedButton().text() == \ "Foods": self.drawOnMap = anthill.Painter.drawFoods elif self.ui.painterButtonGroup.checkedButton().text() == \ "Obstacles": self.drawOnMap = anthill.Painter.drawObstacles elif self.ui.painterButtonGroup.checkedButton().text() == \ "Pheromone (to food)": self.drawOnMap = anthill.Painter.drawPheromoneToFood elif self.ui.painterButtonGroup.checkedButton().text() == \ "Pheromone (from food)": self.drawOnMap = anthill.Painter.drawPheromoneFromFood @pyqtSlot() def refresh(self): if self.paused: return w = self.world.getDimensions().posX() h = self.world.getDimensions().posY() self.world.setMultithreaded(self.ui.multithreaded.isChecked()) self.world.simulationStep() # update statistics stats = self.world.getStatistics(); if self.ui.tabWidget.currentWidget().objectName() == "StatsTab": self.world.setStatisticsEnabled(True) self.statistics.refresh(stats) if self.ui.disableGraphics.isChecked(): return self.frameSkippingCounter+=1 if self.frameSkippingCounter > self.ui.frameSkipping.value(): self.frameSkippingCounter=0 if self.ui.graphicsView.scene() is None: self.ui.graphicsView.setScene(QGraphicsScene(0,0,w,h)) scene = self.ui.graphicsView.scene() scene.clear() bgBrush=QBrush(QColor(50,120,50,255)) bgPen=QPen(QBrush(QColor()),0) scene.addRect(0,0,w,h,pen=bgPen,brush=bgBrush) # draw pheromone map pMaps=self.world.getPheromoneMaps() pMaps=[pMaps[p] for p in range(len(pMaps))] pheromoneColors=[ (50,50,155), (255,50,50), (0,255,0)] displayPheromones= [self.ui.displayPheromones1.isChecked(), self.ui.displayPheromones2.isChecked(), self.ui.displayPheromones3.isChecked()] for i,m in enumerate(pMaps): if(displayPheromones[i]): self.drawPheromoneMap(m,baseRGB=(pheromoneColors[i])) # draw obstacles obstacles=self.world.getObstacles() obstaclePen=QPen(QBrush(QColor()),0) obstacleBrush=QBrush(QColor(50,50,50,255)) self.drawEntities(obstacles,obstaclePen,obstacleBrush) # draw foods foods=self.world.getFoods() foodPen=QPen(QBrush(QColor()),0) foodBrush=QBrush(QColor(200,200,200,70)) self.drawEntities(foods,foodPen,foodBrush) # draw creatures creatures=self.world.getCreatures() creaturePen=QPen(QBrush(QColor()),0) creatureBrush=QBrush(QColor(100,100,50,200)) if(self.ui.displayRanges.isChecked()): self.drawEntities(creatures,creaturePen,creatureBrush,True,7) else: self.drawEntities(creatures,creaturePen,creatureBrush,True) # draw anthills anthills=self.world.getAnthills() anthillPen=QPen(QBrush(QColor()),0) anthillBrush=QBrush(QColor(200,20,20,150)) self.drawEntities(anthills,anthillPen,anthillBrush) def restartTimer(self): self.refresh() if self.refreshTimer: self.refreshTimer.stop() self.refreshTimer=QTimer(self) self.refreshTimer.timeout.connect(self.refresh) self.refreshTimer.start(1000/self.simulationFramerate) def on_startSimulationButton_released(self): _translate = QtCore.QCoreApplication.translate if self.paused: if self.refreshTimer is None: self.restartTimer() # ask user for world generation params dialog = WorldGeneratorParamsDialog(self) if not dialog.exec_(): # if user clicked CANCEL return dialog.processResults() self.world.setDimensions(dialog.worldWidth, dialog.worldHeight) try: anthill.WorldGenerator.placeObstacles(self.world, dialog.obstaclesParams) anthill.WorldGenerator.placeFoods(self.world, dialog.foodsParams) anthill.WorldGenerator.placeAnthill(self.world, dialog.anthillParams) anthill.WorldGenerator.placeAnts(self.world, dialog.antsParams) anthill.WorldGenerator.initPheromoneMaps(self.world, dialog.pheromoneParams) except: pass self.statistics.reset() self.world.startSimulation() self.ui.startSimulationButton.setText(_translate( "MainWindow", "Pause Simulation")) self.paused = False else: self.ui.startSimulationButton.setText(_translate( "MainWindow", "Start Simulation")) self.paused = True def on_stopSimulationButton_released(self): if self.refreshTimer: _translate = QtCore.QCoreApplication.translate self.ui.startSimulationButton.setText(_translate( "MainWindow", "Start Simulation")) self.paused = True self.refresh() self.refreshTimer.stop() self.refreshTimer=None self.world.stopSimulation() def on_saveStateButton_released(self): self.paused = True path=QFileDialog.getSaveFileName(self, "Save File", ".", "All Files (*)") path=path[0] if(path and path!=''): print("Saving state to: ",path) self.paused = False self.world.saveState(path) self.restartTimer() self.paused = False def on_loadStateButton_released(self): self.paused = True path=QFileDialog.getOpenFileName(self, "Open File", ".", "All Files (*)") path=path[0] if(path and path!=''): self.world.loadState(path) self.world.startSimulation() self.restartTimer() self.paused = False def on_framerateBox_valueChanged(self): self.simulationFramerate=max(self.ui.framerateBox.value(),1) if(self.refreshTimer): self.refreshTimer.stop() self.refreshTimer.start(1000/self.simulationFramerate) def on_actionExit_triggered(self): self.close() def on_actionAbout_triggered(self): print("Anthill simulator version 0. ")
class ArduloaderWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.portManager = PortManager(self.ui, startmonitor=True) self.configHelper = ConfigHelper(self.ui) self.initSignal() self.setupUi_Ex() def setupUi_Ex(self): self.setWindowTitle(const.windowtitle) self.ui.textEdit.append(const.aboutinfo) self.ui.headLabel.setPixmap(QPixmap(":/main/icons/main/arduloader.png")) self.setWindowIcon(QtGui.QIcon(":/main/icons/main/logo.png")) self.setBoards() self.configHelper.updateUiByConfig() def setBoards(self): ret, self.__boardsinfodict = BoardHelper.getBoardsInfo() if not ret: self.__boardsinfodict = {} return for boardname in self.__boardsinfodict.keys(): self.ui.mcuCombox.addItem(boardname) def onUploadFinish(self, ret, text): self.timer.stop() try: res = ret == 0 and "Upload SUCCESS:)" or ("%s\nUpload FAILED:(" % text) except IOError: res = "Read tmp file error" except: res = "Unknown error" self.ui.textEdit.append(res) def onUploading(self): prev_cursor = self.ui.textEdit.textCursor() self.ui.textEdit.moveCursor(QtGui.QTextCursor.End) self.ui.textEdit.insertPlainText (".") self.ui.textEdit.setTextCursor(prev_cursor) def getUploadArgs(self): infodict = self.__boardsinfodict.get(tostr(self.ui.mcuCombox.currentText())) if not infodict: return mcu = infodict["mcu"] speed = infodict["speed"] protocol = infodict["protocol"] maximum_size = infodict["maximum_size"] comport = tostr(self.ui.portCombox.currentText()) flash_bin = togbk(self.ui.hexfileCombox.currentText()) return {"mcu": mcu, "speed": speed, "protocol": protocol, "maximum_size": maximum_size, "comport": comport, "flash_bin": flash_bin } def checkUploadArgs(self, argsdict): if not argsdict: self.ui.textEdit.append("Get chip data error") return False if not OSPath.exists(argsdict.get("flash_bin", "")): self.ui.textEdit.append("Hex file not exists") return False # TODO: 检查文件大小是否超多当前芯片允许的最大值 return True def startUpload(self): argsdict = self.getUploadArgs() if not self.checkUploadArgs(argsdict): return self.uploader = Uploader() self.connect(self.uploader.qobj, QtCore.SIGNAL(const.finish_sig), self.onUploadFinish) self.uploader.resetUploadArgs(argsdict) self.ui.textEdit.clear() self.ui.textEdit.append("Start uploading\n") self.timer = QtCore.QTimer() self.timer.timeout.connect(self.onUploading) self.uploader.start() self.timer.start(const.process_interval) def onOpenHexFile(self): filename = QtGui.QFileDialog.getOpenFileName(self, "Choose a HEX file", ".", "HEX (*.hex)") if filename == "": return index = self.ui.hexfileCombox.findText(filename) if index < 0: self.ui.hexfileCombox.insertItem(0, filename) index = 0 self.ui.hexfileCombox.setCurrentIndex(index) def closeEvent(self, e): hex = tostr(self.ui.hexfileCombox.currentText()) com = tostr(self.ui.portCombox.currentText()) board = tostr(self.ui.mcuCombox.currentText()) self.configHelper.updateConfig(hex, com, board) e.accept() def initSignal(self): self.ui.exitButton.clicked.connect(self.close) self.ui.uploadButton.clicked.connect(self.startUpload) self.ui.openHexButton.clicked.connect(self.onOpenHexFile)
class MainWindow(QtGui.QMainWindow): """ Class of Main Window (top) Copy to ui.setupUI # Version 3.0 + Import for Ui_MainWindow.py from MplFigureCanvas import Qt4MplCanvas # Replace 'self.graphicsView = QtGui.QtGraphicsView' with the following self.graphicsView = Qt4MplCanvas(self.centralwidget) self.mainplot = self.graphicsView.getPlot() # Version 2.0 + Import import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from matplotlib.figure import Figure self.figure = Figure((4.0, 3.0), dpi=100) self.mainplot = self.figure.add_subplot(111) self.graphicsView = FigureCanvas(self.figure) self.graphicsView.setParent(self.centralwidget) self.graphicsView.setGeometry(QtCore.QRect(20, 150, 741, 411)) self.graphicsView.setObjectName(_fromUtf8("graphicsView")) # Version 1.0 Replacement is not a valid approach as the UI is setup at the end of self.ui.setupUI self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.figure = Figure((4.0, 3.0), dpi=100) self.mainplot = self.figure.add_subplot(111) self.ui.graphicsView = FigureCanvas(self.figure) self.ui.graphicsView.setParent(self.centralwidget) self.ui.graphicsView.setGeometry(QtCore.QRect(40, 230, 821, 411)) self.ui.graphicsView.setObjectName(_fromUtf8("graphicsView")) """ def __init__(self, parent=None): """ Intialization and set up """ # Base class QtGui.QMainWindow.__init__(self,parent) # Mantid configuration config = ConfigService.Instance() self._instrument = config["default.instrument"] # Central widget self.centralwidget = QtGui.QWidget(self) # UI Window (from Qt Designer) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Do initialize plotting vecx, vecy, xlim, ylim = self.computeMock() self.mainline = self.ui.mainplot.plot(vecx, vecy, 'r-') leftx = [xlim[0], xlim[0]] lefty = [ylim[0], ylim[1]] self.leftslideline = self.ui.mainplot.plot(leftx, lefty, 'b--') rightx = [xlim[1], xlim[1]] righty = [ylim[0], ylim[1]] self.rightslideline = self.ui.mainplot.plot(rightx, righty, 'g--') upperx = [xlim[0], xlim[1]] uppery = [ylim[1], ylim[1]] self.upperslideline = self.ui.mainplot.plot(upperx, uppery, 'b--') lowerx = [xlim[0], xlim[1]] lowery = [ylim[0], ylim[0]] self.lowerslideline = self.ui.mainplot.plot(lowerx, lowery, 'g--') self.ui.graphicsView.mpl_connect('button_press_event', self.on_mouseDownEvent) # Set up horizontal slide (integer) and string value self._leftSlideValue = 0 self._rightSlideValue = 99 self.ui.horizontalSlider.setRange(0, 100) self.ui.horizontalSlider.setValue(self._leftSlideValue) self.ui.horizontalSlider.setTracking(True) self.ui.horizontalSlider.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider, SIGNAL('valueChanged(int)'), self.move_leftSlider) self.ui.horizontalSlider_2.setRange(0, 100) self.ui.horizontalSlider_2.setValue(self._rightSlideValue) self.ui.horizontalSlider_2.setTracking(True) self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider_2, SIGNAL('valueChanged(int)'), self.move_rightSlider) # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), # self.set_startTime) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"), self.set_startTime) # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), # self.set_stopTime) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) self.connect(self.ui.pushButton_setTf, QtCore.SIGNAL("clicked()"), self.set_stopTime) # File loader self.scanEventWorkspaces() self.connect(self.ui.pushButton_refreshWS, SIGNAL('clicked()'), self.scanEventWorkspaces) self.connect(self.ui.pushButton_browse, SIGNAL('clicked()'), self.browse_File) self.connect(self.ui.pushButton_load, SIGNAL('clicked()'), self.load_File) self.connect(self.ui.pushButton_3, SIGNAL('clicked()'), self.use_existWS) # Set up time self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) # Filter by time self.connect(self.ui.pushButton_filterTime, SIGNAL('clicked()'), self.filterByTime) # Filter by log value self.ui.lineEdit_5.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_5)) self.ui.lineEdit_6.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_6)) self.ui.lineEdit_7.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_7)) self.ui.lineEdit_8.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_8)) self.ui.lineEdit_9.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_9)) self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"), self.set_minLogValue) self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"), self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] self.ui.comboBox_4.addItems(dirchangeops) logboundops = ["Centre", "Left"] self.ui.comboBox_5.addItems(logboundops) self.connect(self.ui.pushButton_4, SIGNAL('clicked()'), self.plotLogValue) self.connect(self.ui.pushButton_filterLog, SIGNAL('clicked()'), self.filterByLogValue) # Set up vertical slide self._upperSlideValue = 99 self._lowerSlideValue = 0 self.ui.verticalSlider.setRange(0, 100) self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.verticalSlider.setTracking(True) self.connect(self.ui.verticalSlider, SIGNAL('valueChanged(int)'), self.move_upperSlider) self.ui.verticalSlider_2.setRange(0, 100) self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.verticalSlider_2.setTracking(True) self.connect(self.ui.verticalSlider_2, SIGNAL('valueChanged(int)'), self.move_lowerSlider) # Set up for filtering (advanced setup) self._tofcorrection = False self.ui.checkBox_filterByPulse.setChecked(False) self.ui.checkBox_from1.setChecked(False) self.ui.checkBox_groupWS.setChecked(True) self.connect(self.ui.comboBox_tofCorr, SIGNAL('currentIndexChanged(int)'), self.showHideEi) self.connect(self.ui.pushButton_refreshCorrWSList, SIGNAL('clicked()'), self._searchTableWorkspaces) self.ui.lineEdit_Ei.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_Ei)) self.ui.label_Ei.hide() self.ui.lineEdit_Ei.hide() self.ui.label_Ei_2.hide() self.ui.comboBox_corrWS.hide() self.ui.pushButton_refreshCorrWSList.hide() # Error message # self.connect(self.ui.pushButton_clearerror, SIGNAL('clicked()'), self._clearErrorMsg) # self.ui.plainTextEdit_ErrorMsg.setReadOnly(True) # self.ui.label_error.hide() # Set up for workspaces self._dataWS = None self._sampleLogNames = [] self._sampleLog = None # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() self.ui.label_avg.hide() self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() self.ui.label_logname.hide() self.ui.label_lognamevalue.hide() self.ui.label_logsize.hide() self.ui.label_logsizevalue.hide() # Default self._defaultdir = os.getcwd() # self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) # QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) # QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # self.setInstrumentInputs() ##defaults return def on_mouseDownEvent(self, event): """ Respond to pick up a value with mouse down event """ x = event.xdata y = event.ydata if x is not None and y is not None: msg = "You've clicked on a bar with coords:\n %f, %f" % (x, y) QMessageBox.information(self, "Click!", msg) return def computeMock(self): """ Compute vecx and vecy as mocking """ import random, math x0 = 0. xf = 1. dx = 0.1 vecx = [] vecy = [] x = x0 while x < xf: y = 0.0 vecx.append(x) vecy.append(y) x += dx xlim = [x0, xf] ylim = [-1., 1] return (vecx, vecy, xlim, ylim) def move_leftSlider(self): """ Re-setup left range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ newx = self.ui.horizontalSlider.value() if newx <= self._rightSlideValue and newx != self._leftSlideValue: # Allowed value: move the value bar self._leftSlideValue = newx # Move the vertical line xlim = self.ui.mainplot.get_xlim() newx = xlim[0] + newx*(xlim[1] - xlim[0])*0.01 leftx = [newx, newx] lefty = self.ui.mainplot.get_ylim() setp(self.leftslideline, xdata=leftx, ydata=lefty) self.ui.graphicsView.draw() # Change value self.ui.lineEdit_3.setText(str(newx)) else: # Reset the value to original value self.ui.horizontalSlider.setValue(self._leftSlideValue) return def set_startTime(self): """ Set the starting time and left slide bar """ inps = str(self.ui.lineEdit_3.text()) print "Starting time = %s" % (inps) xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtime0 = xlim[0] else: newtime0 = float(inps) # Convert to integer slide value ileftvalue = int( (newtime0-xlim[0])/(xlim[1] - xlim[0])*100 ) print "iLeftSlide = %d" % (ileftvalue) # Skip if same as origina if ileftvalue == self._leftSlideValue: return # Set the value if out of range resetT = True if ileftvalue < 0: # Minimum value as 0 ileftvalue = 0 elif ileftvalue > self._rightSlideValue: # Maximum value as right slide value ileftvalue = self._rightSlideValue else: resetT = False if resetT is True: newtime0 = xlim[0] + ileftvalue*(xlim[1]-xlim[0])*0.01 print "Corrected iLeftSlide = %d (vs. right = %d)" % (ileftvalue, self._rightSlideValue) # Move the slide bar (left) self._leftSlideValue = ileftvalue # Move the vertical line leftx = [newtime0, newtime0] lefty = self.ui.mainplot.get_ylim() setp(self.leftslideline, xdata=leftx, ydata=lefty) self.ui.graphicsView.draw() # Set the value to left slider self.ui.horizontalSlider.setValue(self._leftSlideValue) # Reset the value of line edit if resetT is True: self.ui.lineEdit_3.setText(str(newtime0)) return def move_rightSlider(self): """ Re-setup left range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ newx = self.ui.horizontalSlider_2.value() if newx >= self._leftSlideValue and newx != self._rightSlideValue: # Allowed value: move the value bar self._rightSlideValue = newx xlim = self.ui.mainplot.get_xlim() newx = xlim[0] + newx*(xlim[1] - xlim[0])*0.01 leftx = [newx, newx] lefty = self.ui.mainplot.get_ylim() setp(self.rightslideline, xdata=leftx, ydata=lefty) self.ui.graphicsView.draw() # Change value self.ui.lineEdit_4.setText(str(newx)) else: # Reset the value self.ui.horizontalSlider_2.setValue(self._rightSlideValue) return def set_stopTime(self): """ Set the starting time and left slide bar """ inps = str(self.ui.lineEdit_4.text()) print "Stopping time = %s" % (inps) xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtimef = xlim[1] else: # Parse newtimef = float(inps) # Convert to integer slide value irightvalue = int( (newtimef-xlim[0])/(xlim[1] - xlim[0])*100 ) print "iRightSlide = %d" % (irightvalue) # Return if no change if irightvalue == self._rightSlideValue: return # Correct value resetT = True if irightvalue >= 100: irightvalue == 100 elif irightvalue < self._leftSlideValue: irightvalue = self._leftSlideValue else: resetT = False if resetT is True: newtimef = xlim[0] + irightvalue*(xlim[1]-xlim[0])*0.01 # Move the slide bar (right) self._rightSlideValue = irightvalue # Move the vertical line rightx = [newtimef, newtimef] righty = self.ui.mainplot.get_ylim() setp(self.rightslideline, xdata=rightx, ydata=righty) self.ui.graphicsView.draw() # Set the value to left slider self.ui.horizontalSlider_2.setValue(self._rightSlideValue) # Reset to line edit if resetT: self.ui.lineEdit_4.setText(str(newtimef)) return def move_lowerSlider(self): """ Re-setup upper range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ inewy = self.ui.verticalSlider_2.value() print "LowerSlider is set with value %d vs. class variable %d" % (inewy, self._lowerSlideValue) # Return with no change if inewy == self._lowerSlideValue: # No change return if inewy >= self._upperSlideValue: # Out of upper range inewy = self._upperSlideValue - 1 if inewy == 0 and self._lowerSlideValue < 0: setLineEdit = False else: setLineEdit = True # Move the lower vertical bar ylim = self.ui.mainplot.get_ylim() newy = ylim[0] + inewy*(ylim[1] - ylim[0])*0.01 lowerx = self.ui.mainplot.get_xlim() lowery = [newy, newy] setp(self.lowerslideline, xdata=lowerx, ydata=lowery) self.ui.graphicsView.draw() # Set line edit input if setLineEdit is True: # Change value to line edit (5) self.ui.lineEdit_5.setText(str(newy)) # Reset the class variable self._lowerSlideValue = inewy return def set_minLogValue(self): """ Set the starting time and left slide bar """ print "Minimum Log Value = %s" %(str(self.ui.lineEdit_5.text())) ylim = self.ui.mainplot.get_ylim() if str(self.ui.lineEdit_5.text()) == "": # Empty. Default to minY newminY = ylim[0] else: # Non empty. Parse newminY = float(self.ui.lineEdit_5.text()) # Convert to integer slide value iminlogval = int( (newminY-ylim[0])/(ylim[1] - ylim[0])*100 ) print "ilowerSlide = %d" % (iminlogval) # Return if no change if iminlogval == self._lowerSlideValue: return # Set value if out of range resetL = True if iminlogval >= self._upperSlideValue: iminlogval = self._upperSlideValue - 1 else: resetL = False if resetL is True: newminY = ylim[0] + iminlogval * (ylim[1]-ylim[0]) * 0.01 # Move the vertical line lowerx = self.ui.mainplot.get_xlim() lowery = [newminY, newminY] setp(self.lowerslideline, xdata=lowerx, ydata=lowery) self.ui.graphicsView.draw() # Move the slide bar (lower) self._lowerSlideValue = iminlogval print "LineEdit5 set slide to %d" % (self._lowerSlideValue) self.ui.verticalSlider_2.setValue(self._lowerSlideValue) # Reset line Edit if using default if resetL is True: self.ui.lineEdit_5.setText(str(newminY)) return def move_upperSlider(self): """ Re-setup upper range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ inewy = self.ui.verticalSlider.value() # Return w/o change if inewy == self._upperSlideValue: return # Set to boundary value if inewy <= self._lowerSlideValue: inewy = self._lowerSlideValue + 1 # Reset line editor? if inewy == 100 and self._upperSlideValue > 100: setLineEdit = False else: setLineEdit = True # Move the upper value bar: upperx and uppery are real value (float but not (0,100)) of the figure ylim = self.ui.mainplot.get_ylim() newy = ylim[0] + inewy*(ylim[1] - ylim[0])*0.01 upperx = self.ui.mainplot.get_xlim() uppery = [newy, newy] setp(self.upperslideline, xdata=upperx, ydata=uppery) self.ui.graphicsView.draw() # Change value if setLineEdit is True: self.ui.lineEdit_6.setText(str(newy)) self._upperSlideValue = inewy return def set_maxLogValue(self): """ Set maximum log value from line-edit """ inps = str(self.ui.lineEdit_6.text()) print "Maximum Log Value = %s" %(inps) ylim = self.ui.mainplot.get_ylim() if inps == "": # Empty. Default to minY newmaxY = ylim[1] else: # Parse newmaxY = float(inps) # Convert to integer slide value imaxlogval = int( (newmaxY-ylim[0])/(ylim[1] - ylim[0])*100 ) print "iUpperSlide = %d" % (imaxlogval) # Return if no change if imaxlogval == self._upperSlideValue: return # Set to default if out of range resetL = True # if imaxlogval >= 100: # imaxlogval = 100 if imaxlogval < self._lowerSlideValue: imaxlogval = self._lowerSlideValue + 1 else: resetL = False # Set newmaxY if necessary if resetL is True: newmaxY = ylim[0] + imaxlogval * (ylim[1] - ylim[0]) * 0.01 # Move the vertical line upperx = self.ui.mainplot.get_xlim() uppery = [newmaxY, newmaxY] setp(self.upperslideline, xdata=upperx, ydata=uppery) self.ui.graphicsView.draw() # Set the value to upper slider self._upperSlideValue = imaxlogval self.ui.verticalSlider.setValue(self._upperSlideValue) # Set the value to editor if necessary if resetL is True: self.ui.lineEdit_6.setText(str(newmaxY)) return def browse_File(self): """ Open a file dialog to get file """ filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog', self._defaultdir, "Data (*.nxs *.dat);;All files (*.*)") self.ui.lineEdit.setText(str(filename)) # print "Selected file: ", filename return def load_File(self): """ Load the file by file name or run number """ # Get file name from line editor filename = str(self.ui.lineEdit.text()) # Find out it is relative path or absolute path if os.path.abspath(filename) == filename: isabspath = True else: isabspath = False dataws = self._loadFile(str(filename)) if dataws is None: errmsg = "Unable to locate run %s in default directory %s." % (filename, self._defaultdir) print errmsg self._setErrorMsg(errmsg) else: self._importDataWorkspace(dataws) self._defaultdir = os.path.dirname(str(filename)) # Reset GUI self._resetGUI(resetfilerun=False) return def use_existWS(self): """ Set up workspace to an existing one """ wsname = str(self.ui.comboBox.currentText()) try: dataws = AnalysisDataService.retrieve(wsname) self._importDataWorkspace(dataws) except KeyError: pass # Reset GUI self._resetGUI(resetfilerun=True) return def plotLogValue(self): """ Plot log value """ # Get log value logname = str(self.ui.comboBox_2.currentText()) if len(logname) == 0: # return due to the empty one is chozen return samplelog = self._dataWS.getRun().getProperty(logname) vectimes = samplelog.times vecvalue = samplelog.value # check if len(vectimes) == 0: print "Empty log!" # Convert absolute time to relative time in seconds t0 = self._dataWS.getRun().getProperty("proton_charge").times[0] t0ns = t0.totalNanoseconds() # append 1 more log if original log only has 1 value tf = self._dataWS.getRun().getProperty("proton_charge").times[-1] vectimes.append(tf) vecvalue = numpy.append(vecvalue, vecvalue[-1]) vecreltimes = [] for t in vectimes: rt = float(t.totalNanoseconds() - t0ns) * 1.0E-9 vecreltimes.append(rt) # Set to plot xlim = [min(vecreltimes), max(vecreltimes)] ylim = [min(vecvalue), max(vecvalue)] self.ui.mainplot.set_xlim(xlim[0], xlim[1]) self.ui.mainplot.set_ylim(ylim[0], ylim[1]) setp(self.mainline, xdata=vecreltimes, ydata=vecvalue) samunit = samplelog.units if len(samunit) == 0: ylabel = logname else: ylabel = "%s (%s)" % (logname, samunit) self.ui.mainplot.set_ylabel(ylabel, fontsize=13) # assume that all logs are on almost same X-range. Only Y need to be reset setp(self.leftslideline, ydata=ylim) setp(self.rightslideline, ydata=ylim) # reset the log value limit as previous one does not make any sense setp(self.lowerslideline, xdata=xlim, ydata=[ylim[0], ylim[0]]) self._lowerSlideValue = 0 self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.lineEdit_5.setText("") setp(self.upperslideline, xdata=xlim, ydata=[ylim[1], ylim[1]]) self._upperSlideValue = 100 self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.lineEdit_6.setText("") self.ui.graphicsView.draw() # Load property's statistic and give suggestion on parallel and fast log timeavg = samplelog.timeAverageValue() numentries = samplelog.size() stat = samplelog.getStatistics() duration = stat.duration mean = stat.mean freq = float(numentries)/float(duration) self.ui.label_mean.show() self.ui.label_meanvalue.show() self.ui.label_avg.show() self.ui.label_timeAvgValue.show() self.ui.label_freq.show() self.ui.label_freqValue.show() self.ui.label_logname.show() self.ui.label_lognamevalue.show() self.ui.label_logsize.show() self.ui.label_logsizevalue.show() self.ui.label_meanvalue.setText("%.5e"%(mean)) self.ui.label_timeAvgValue.setText("%.5e"%(timeavg)) self.ui.label_freqValue.setText("%.5e"%(freq)) self.ui.label_lognamevalue.setText(logname) self.ui.label_logsizevalue.setText(str(numentries)) # Set suggested processing scheme if numentries > HUGE_FAST: self.ui.checkBox_fastLog.setCheckState(True) if numentries > HUGE_PARALLEL: self.ui.checkBox_doParallel.setCheckState(True) else: self.ui.checkBox_doParallel.setCheckState(False) else: self.ui.checkBox_fastLog.setCheckState(False) self.ui.checkBox_doParallel.setCheckState(False) return def _importDataWorkspace(self, dataws): """ Import data workspace for filtering """ if dataws is None: return # Plot time counts errmsg = self._plotTimeCounts(dataws) if errmsg is not None: errmsg = "Workspace %s has invalid sample logs for splitting. Loading \ failure! \n%s\n" % (str(dataws), errmsg) self._setErrorMsg(errmsg) return False # Import log self._sampleLogNames = [""] run = dataws.getRun() plist = run.getProperties() for p in plist: pv = p.value if isinstance(pv, numpy.ndarray): times = p.times if len(times) > 1: self._sampleLogNames.append(p.name) # ENDFOR(p) # Set up sample log self.ui.comboBox_2.clear() self.ui.comboBox_2.addItems(self._sampleLogNames) # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() self.ui.label_avg.hide() self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() # Hide 'log name' above the graphic view self.ui.label_logname.hide() self.ui.label_lognamevalue.hide() # Set dataws to class variable self._dataWS = dataws return True def scanEventWorkspaces(self): """ """ wsnames = AnalysisDataService.getObjectNames() eventwsnames = [] for wsname in wsnames: wksp = AnalysisDataService.retrieve(wsname) if wksp.__class__.__name__.count("Event") == 1: eventwsnames.append(wsname) # ENDFOR if len(eventwsnames) > 0: self.ui.comboBox.clear() self.ui.comboBox.addItems(eventwsnames) return def _loadFile(self, filename): """ Load file or run File will be loaded to a workspace shown in MantidPlot """ config = ConfigService # Check input file name and output workspace name if filename.isdigit() is True: # Construct a file name from run number runnumber = int(filename) if runnumber <= 0: print "Run number cannot be less or equal to zero. User gives %s. " % (filename) return None else: ishort = config.getInstrument(self._instrument).shortName() filename = "%s_%s" %(ishort, filename) wsname = filename + "_event" elif filename.count(".") > 0: # A proper file name wsname = os.path.splitext(os.path.split(filename)[1])[0] elif filename.count("_") == 1: # A short one as instrument_runnumber iname = filename.split("_")[0] str_runnumber = filename.split("_")[1] if str_runnumber.isdigit() is True and int(str_runnumber) > 0: # Acccepted format ishort = config.getInstrument(iname).shortName() wsname = "%s_%s_event" % (ishort, str_runnumber) else: # Non-supported print "File name / run number in such format %s is not supported. " % (filename) return None else: # Unsupported format print "File name / run number in such format %s is not supported. " % (filename) return None # Load try: ws = api.Load(Filename=filename, OutputWorkspace=wsname) except: ws = None return ws def _plotTimeCounts(self, wksp): """ Plot time/counts """ import datetime # Rebin events by pulse time try: # Get run start and run stop if wksp.getRun().hasProperty("run_start"): runstart = wksp.getRun().getProperty("run_start").value else: runstart = wksp.getRun().getProperty("proton_charge").times[0] runstop = wksp.getRun().getProperty("proton_charge").times[-1] runstart = str(runstart).split(".")[0].strip() runstop = str(runstop).split(".")[0].strip() t0 = datetime.datetime.strptime(runstart, "%Y-%m-%dT%H:%M:%S") tf = datetime.datetime.strptime(runstop, "%Y-%m-%dT%H:%M:%S") # Calcualte dt = tf-t0 timeduration = dt.days*3600*24 + dt.seconds timeres = float(timeduration)/MAXTIMEBINSIZE if timeres < 1.0: timeres = 1.0 sumwsname = "_Summed_%s"%(str(wksp)) if AnalysisDataService.doesExist(sumwsname) is False: sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname, Params="0, %f, %d"%(timeres, timeduration)) sumws = api.SumSpectra(InputWorkspace=sumws, OutputWorkspace=str(sumws)) sumws = api.ConvertToPointData(InputWorkspace=sumws, OutputWorkspace=str(sumws)) else: sumws = AnalysisDataService.retrieve(sumwsname) except Exception as e: return str(e) vecx = sumws.readX(0) vecy = sumws.readY(0) xmin = min(vecx) xmax = max(vecx) ymin = min(vecy) ymax = max(vecy) # Reset graph self.ui.mainplot.set_xlim(xmin, xmax) self.ui.mainplot.set_ylim(ymin, ymax) self.ui.mainplot.set_xlabel('Time (seconds)', fontsize=13) self.ui.mainplot.set_ylabel('Counts', fontsize=13) # Set up main line setp(self.mainline, xdata=vecx, ydata=vecy) # Reset slide newslidery = [min(vecy), max(vecy)] newleftx = xmin + (xmax-xmin)*self._leftSlideValue*0.01 setp(self.leftslideline, xdata=[newleftx, newleftx], ydata=newslidery) newrightx = xmin + (xmax-xmin)*self._rightSlideValue*0.01 setp(self.rightslideline, xdata=[newrightx, newrightx], ydata=newslidery) self.ui.graphicsView.draw() return def filterByTime(self): """ Filter by time """ # Generate event filters kwargs = {} if self.ui.lineEdit_3.text() != "": rel_starttime = float(self.ui.lineEdit_3.text()) kwargs["StartTime"] = str(rel_starttime) if self.ui.lineEdit_4.text() != "": rel_stoptime = float(self.ui.lineEdit_4.text()) kwargs["StopTime"] = str(rel_stoptime) if self.ui.lineEdit_timeInterval.text() != "": interval = float(self.ui.lineEdit_timeInterval.text()) kwargs["TimeInterval"] = interval splitwsname = str(self._dataWS) + "_splitters" splitinfowsname = str(self._dataWS) + "_info" title = str(self.ui.lineEdit_title.text()) """ Debug for k in kwargs.keys(): print k, kwargs[k], type(kwargs[k]) print "Input workspace = ", str(self._dataWS) END DB """ splitws, infows = api.GenerateEventsFilter( InputWorkspace = self._dataWS, UnitOfTime = "Seconds", TitleOfSplitters = title, OutputWorkspace = splitwsname, InformationWorkspace = splitinfowsname, **kwargs) self.splitWksp(splitws, infows) return def filterByLogValue(self): """ Filter by log value """ # Generate event filter kwargs = {} samplelog = str(self.ui.comboBox_2.currentText()) if len(samplelog) == 0: print "No sample log is selected!" return if self.ui.lineEdit_3.text() != "": rel_starttime = float(self.ui.lineEdit_3.text()) kwargs["StartTime"] = str(rel_starttime) if self.ui.lineEdit_4.text() != "": rel_stoptime = float(self.ui.lineEdit_4.text()) kwargs["StopTime"] = str(rel_stoptime) if self.ui.lineEdit_5.text() != "": minlogvalue = float(self.ui.lineEdit_5.text()) kwargs["MinimumLogValue"] = minlogvalue if self.ui.lineEdit_6.text() != "": maxlogvalue = float(self.ui.lineEdit_6.text()) kwargs["MaximumLogValue"] = maxlogvalue if self.ui.lineEdit_7.text() != "": logvalueintv = float(self.ui.lineEdit_7.text()) kwargs["LogValueInterval"] = logvalueintv logvalchangedir = str(self.ui.comboBox_4.currentText()) kwargs["FilterLogValueByChangingDirection"] = logvalchangedir if self.ui.lineEdit_9.text() != "": logvalueintv = float(self.ui.lineEdit_9.text()) kwargs["TimeTolerance"] = logvalueintv logboundtype = str(self.ui.comboBox_5.currentText()) kwargs["LogBoundary"] = logboundtype if self.ui.lineEdit_8.text() != "": logvaluetol = float(self.ui.lineEdit_8.text()) kwargs["LogValueTolerance"] = logvaluetol splitwsname = str(self._dataWS) + "_splitters" splitinfowsname = str(self._dataWS) + "_info" title = str(self.ui.lineEdit_title.text()) splitws, infows = api.GenerateEventsFilter( InputWorkspace = self._dataWS, UnitOfTime = "Seconds", TitleOfSplitters = title, OutputWorkspace = splitwsname, LogName = samplelog, InformationWorkspace = splitinfowsname, **kwargs) try: self.splitWksp(splitws, infows) except Exception as mtderror: self._setErrorMsg("Splitting Failed!\n %s" % (str(mtderror))) return def splitWksp(self, splitws, infows): """ Run FilterEvents """ dogroupws = self.ui.checkBox_groupWS.isChecked() filterbypulse = self.ui.checkBox_filterByPulse.isChecked() startfrom1 = self.ui.checkBox_from1.isChecked() splitsamplelog = self.ui.checkBox_splitLog.isChecked() corr2sample = str(self.ui.comboBox_tofCorr.currentText()) how2skip = str(self.ui.comboBox_skipSpectrum.currentText()) kwargs = {} if corr2sample == "Direct": ei = float(self.ui.lineEdit_Ei.text()) kwargs["IncidentEnergy"] = ei elif corr2sample == "Customized": corrws = str(self.ui.comboBox_corrWS.currentText()) kwargs["DetectorTOFCorrectionWorkspace"] = corrws # Output workspace name outbasewsname = str(self.ui.lineEdit_outwsname.text()) if len(outbasewsname) == 0: outbasewsname = "tempsplitted" self.ui.lineEdit_outwsname.setText(outbasewsname) api.FilterEvents( InputWorkspace = self._dataWS, SplitterWorkspace = splitws, InformationWorkspace = infows, OutputWorkspaceBaseName = outbasewsname, GroupWorkspaces = dogroupws, FilterByPulseTime = filterbypulse, CorrectionToSample = corr2sample, SpectrumWithoutDetector = how2skip, SplitSampleLogs = splitsamplelog, OutputWorkspaceIndexedFrom1 = startfrom1, OutputTOFCorrectionWorkspace = 'TOFCorrTable', **kwargs) return def showHideEi(self): """ """ corrtype = str(self.ui.comboBox_tofCorr.currentText()) # Incident energy if corrtype == "Direct": self.ui.label_Ei.show() self.ui.lineEdit_Ei.show() else: self.ui.label_Ei.hide() self.ui.lineEdit_Ei.hide() # Workspace if corrtype == "Customized": self.ui.label_Ei_2.show() self.ui.comboBox_corrWS.show() self.ui.pushButton_refreshCorrWSList.show() # Search for table workspace self._searchTableWorkspaces() else: self.ui.label_Ei_2.hide() self.ui.comboBox_corrWS.hide() self.ui.pushButton_refreshCorrWSList.hide() return def _searchTableWorkspaces(self): """ Search table workspaces and add to 'comboBox_corrWS' """ wsnames = AnalysisDataService.getObjectNames() tablewsnames = [] for wsname in wsnames: wksp = AnalysisDataService.retrieve(wsname) if isinstance(wksp, mantid.api._api.ITableWorkspace): tablewsnames.append(wsname) # ENDFOR self.ui.comboBox_corrWS.clear() if len(tablewsnames) > 0: self.ui.comboBox_corrWS.addItems(tablewsnames) return def _clearErrorMsg(self): """ Clear error message """ #self.ui.plainTextEdit_ErrorMsg.setPlainText("") #self.ui.label_error.hide() return def _setErrorMsg(self, errmsg): """ Clear error message """ #self.ui.plainTextEdit_ErrorMsg.setPlainText(errmsg) #self.ui.label_error.show() #print "Testing Pop-up Error Message Window: %s" % (errmsg) self._errMsgWindow = MyPopErrorMsg() self._errMsgWindow.setMessage(errmsg) self._errMsgWindow.show() return def _resetGUI(self, resetfilerun=False, resetwslist=False): """ Reset GUI including all text edits and etc. """ if resetfilerun is True: self.ui.lineEdit.clear() # Plot related self.ui.lineEdit_3.clear() self.ui.lineEdit_4.clear() self.ui.horizontalSlider.setValue(0) self.ui.horizontalSlider_2.setValue(100) self.ui.lineEdit_outwsname.clear() self.ui.lineEdit_title.clear() # Filter by log value self.ui.lineEdit_5.clear() self.ui.lineEdit_6.clear() self.ui.verticalSlider_2.setValue(0) self.ui.verticalSlider.setValue(100) ylim = self.ui.mainplot.get_ylim() miny = ylim[0] maxy = ylim[1] xlim = self.ui.mainplot.get_xlim() setp(self.lowerslideline, xdata=xlim, ydata=[miny, miny]) setp(self.upperslideline, xdata=xlim, ydata=[maxy, maxy]) self.ui.graphicsView.draw() self.ui.lineEdit_7.clear() self.ui.lineEdit_8.clear() self.ui.lineEdit_9.clear() # Filter by time self.ui.lineEdit_timeInterval.clear() # Advanced setup self.ui.comboBox_tofCorr.setCurrentIndex(0) self.ui.lineEdit_Ei.clear() self.ui.checkBox_fastLog.setCheckState(False) self.ui.checkBox_doParallel.setCheckState(False) self.ui.comboBox_skipSpectrum.setCurrentIndex(0) self.ui.checkBox_filterByPulse.setCheckState(False) self.ui.checkBox_from1.setCheckState(False) self.ui.checkBox_groupWS.setCheckState(True) self.ui.checkBox_splitLog.setCheckState(False) # Error message # self.ui.plainTextEdit_ErrorMsg.clear() return