def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: print "get radar error " + self.myname + ":" + str( self.wxreply.error()) self.lastwx = 0 return print "radar map received:" + self.myname + ":" + time.ctime() self.wxmovie.stop() self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) mov = QMovie(self.wxbuff, 'GIF') print "radar map frame count:" + self.myname + ":" + str( mov.frameCount()) if mov.frameCount() > 2: self.lastwx = time.time() else: # radar image retreval failed self.lastwx = 0 # retry in 5 seconds QtCore.QTimer.singleShot(5 * 1000, self.getwx) return self.wxmovie = mov self.wwx.setMovie(self.wxmovie) if self.parent().isVisible(): self.wxmovie.start()
def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: print "get radar error "+self.myname+":"+str(self.wxreply.error()) self.lastwx = 0 return print "radar map received:"+self.myname+":"+time.ctime() self.wxmovie.stop() self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) mov = QMovie(self.wxbuff, 'GIF') print "radar map frame count:"+self.myname+":"+str(mov.frameCount()) if mov.frameCount() > 2: self.lastwx = time.time() else: # radar image retreval failed self.lastwx = 0 # retry in 5 seconds QtCore.QTimer.singleShot(5*1000, self.getwx) return self.wxmovie = mov if Config.satellite: self.setMovie( self.wxmovie) else: self.wwx.setMovie( self.wxmovie) if self.parent().isVisible(): self.wxmovie.start()
def __init__(self, parent, radar, rect, myname): global xscale, yscale self.myname = myname self.rect = rect self.baseurl = self.mapurl(radar, rect, False) #print "google map base url: "+self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) QtGui.QLabel.__init__(self, parent) self.interval = Config.radar_refresh * 60 self.lastwx = 0 self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie()
def __init__(self): QWidget.__init__(self) self.tray = Tray(self) self.setMinimumSize(QSize(320, 200)) self.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setMargin(1) self.text = QTextBrowser(self) self.text.setReadOnly(True) self.text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text.setOpenExternalLinks(True) self.verticalLayout.addWidget(self.text) self.text.textChanged.connect(self.on_text_changed) self.notify = Notify(self) self.movie = QMovie() dev = QBuffer() dev.setData(QByteArray.fromBase64(CHECK_IMAGE)) dev.open(QBuffer.ReadOnly) dev.setParent(self.movie) self.movie.setDevice(dev) self.movie.frameChanged.connect(self.on_frame_changed) self.realized = False self.show()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.searchEdit.textChanged.connect(self.search_text_changed) self.ui.show_button.clicked.connect(self.show_episodes) self.ui.searchEdit.returnPressed.connect(self.show_episodes) self.episodes = None self.episode_list = None self.number = 0 self.anime_list = None self.ui.download_button.clicked.connect(self.download) self.ui.res_list_widget.currentItemChanged.connect(self.episode_change) self.com = Comunicate() self.com.sig.connect(self.message) self.com.img.connect(self.set_image) self.ui.anime_list_widget.itemDoubleClicked.connect(self.show_episodes) self.setWindowIcon(QIcon(get_file('animes.png'))) self.ui.anime_list_widget.itemPressed.connect(self.anime_entered) Thread(target=self.load_url_items).start() #self.load_url_items() self.movie = QMovie(get_file('ajax-loader.gif')) self.ui.loading_label.setMovie(self.movie) self.link = None self.main_download_page = None self.tray = SystemTrayIcon(QIcon(get_file('animes.png')), self.com, self) self.com.op.connect(self.show_semard) self.ui.action_About_Semard.activated.connect(self.about_semard) self.ui.action_Contato.activated.connect(self.show_feedback) self.setWindowTitle('Semard - Animes') self.browser = None self.player = None
def __init__(self, model, parent=None): super(ServerToolsWindow, self).__init__(parent) with Resources.directory: self.setupUi(self) self.spinner_movie = QMovie( Resources.get('icons/servertools-spinner.mng')) self.spinner_label.setMovie(self.spinner_movie) self.spinner_label.hide() self.progress_bar.hide() while self.tab_widget.count(): self.tab_widget.removeTab(0) # remove the tab(s) added in designer self.tab_widget.tabBar().hide() self.account_button.setMenu(QMenu(self.account_button)) self.setWindowTitle('Blink Server Tools') self.setWindowIconText('Server Tools') self.model = model self.tab_widget.addTab(ServerToolsWebView(self), '') font = self.account_label.font() font.setPointSizeF(self.account_label.fontInfo().pointSizeF() + 2) font.setFamily("Sans Serif") self.account_label.setFont(font) self.model.rowsInserted.connect(self._SH_ModelChanged) self.model.rowsRemoved.connect(self._SH_ModelChanged) self.account_button.menu().triggered.connect( self._SH_AccountButtonMenuTriggered) web_view = self.tab_widget.currentWidget() web_view.loadStarted.connect(self._SH_WebViewLoadStarted) web_view.loadFinished.connect(self._SH_WebViewLoadFinished) web_view.loadProgress.connect(self._SH_WebViewLoadProgress)
def set_widgets(self): """Set all widgets on the tab.""" contacts = Contact.get_rows() for contact in contacts: contact_name = contact.name contact_email = ' - ' + contact.email if contact.email else '' contact_phone = ' - ' + contact.phone if contact.phone else '' contact_item = QListWidgetItem(contact_name + contact_email + contact_phone) contact_item.setData(Qt.UserRole, contact) self.project_contact_list.addItem(contact_item) self.project_contact_list.setSelectionMode( QAbstractItemView.ExtendedSelection) icon_path = resources_path('images', 'throbber.gif') movie = QMovie(icon_path) self.throbber_loader.setMovie(movie) movie.start() self.get_available_organisations() self.organisation_box.setFocus() self.project_description_text.setTabChangesFocus(True)
def trainOCR(self): self.train_button.setEnabled(False) alldata = self.connectData() testnumbers = self.getRandomData(alldata, self.NUMBERS) testletters = self.getRandomData(alldata, self.LETTERS) teststation = self.getRandomData(alldata, self.STATION) self.movie = QMovie(":/ico/loader.gif") self.loader.setMovie(self.movie) self.movie.start() self.numberstrainerthread = Trainer(self, "numbers", self.base, self.user, testnumbers, testletters, teststation) self.letterstrainerthread = Trainer(self, "letters", self.base, self.user, testnumbers, testletters, teststation) self.stationtrainerthread = Trainer(self, "station", self.base, self.user, testnumbers, testletters, teststation) QObject.connect(self.numberstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.letterstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.stationtrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) #QObject.connect(self.trainerthread, SIGNAL('finishedall(int)'), self.trainingFinished) self.numberstrainerthread.execute() self.letterstrainerthread.execute() self.stationtrainerthread.execute() self.training_summary.setText("Training in progress")
def __init__(self, fileName): QLabel.__init__(self) thread = Thread(self) m = QMovie(fileName) m.start() self.setMovie(m) app.aboutToQuit.connect(thread.stop) thread.start()
def show_unmute(self): self.movie = QMovie(":/unmute.gif", QByteArray(), self) self.movie.setScaledSize(CustomSize*0.7) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.muted = False self.movie.start()
def visualize(self): self.steps = 0 gdal.UseExceptions() si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW if self.point1.x() > self.point2.x(): minx = math.floor(self.point2.x()) maxx = math.ceil(self.point1.x()) else: minx = math.floor(self.point1.x()) maxx = math.ceil(self.point2.x()) if self.point1.y() > self.point2.y(): miny = math.floor(self.point2.y()) maxy = math.ceil(self.point1.y()) else: miny = math.floor(self.point1.y()) maxy = math.ceil(self.point2.y()) dataset_full = gdal.Open(self.dir_path[0] + '/' + self.roofground_file) full_array = dataset_full.ReadAsArray().astype(np.float) fullsizex = full_array.shape[1] fullsizey = full_array.shape[0] toplefty = self.yllcorner + fullsizey gdalclip_build = 'gdal_translate -a_nodata -9999 -projwin ' + str(minx) + ' ' + str(maxy)\ + ' ' + str(maxx) + ' ' + str(miny) + \ ' -of GTiff ' + self.dir_path[0] + '/' + self.roofground_file + ' ' \ + self.plugin_dir + '/data/temp.tif' subprocess.call(gdalclip_build, startupinfo=si) dataset = gdal.Open(self.plugin_dir + '/data/temp.tif') self.energy_array = dataset.ReadAsArray().astype(np.float) sizex = self.energy_array.shape[1] sizey = self.energy_array.shape[0] gdalclipasc_build = 'gdal_translate -a_nodata -9999 -projwin ' + str(minx) + ' ' + str(maxy) + ' ' + str(maxx) +\ ' ' + str(miny) + ' -of GTiff ' + self.dir_path[0] + '/' + self.height_file + ' ' + \ self.plugin_dir + '/data/temp_asc.tif' subprocess.call(gdalclipasc_build, startupinfo=si) dataset = gdal.Open(self.plugin_dir + '/data/temp_asc.tif') self.asc_array = dataset.ReadAsArray().astype(np.float) movie = QMovie(self.plugin_dir + '/loader.gif') self.visDlg.label.setMovie(movie) self.visDlg.label.show() movie.start() self.start_listworker(minx, maxy, sizex, sizey, toplefty)
class ImagePlayer(QWidget): def __init__(self, filename, title, parent=None): QWidget.__init__(self, parent) # Load the file into a QMovie self.movie = QMovie(filename, QByteArray(), self) print(filename) size = self.movie.scaledSize() self.setGeometry(200, 200, size.width(), size.height()) self.setWindowTitle(title) self.movie_screen = QLabel() # Make label fit the gif self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) self.btn_ex = QPushButton() self.btn_ex.setFixedWidth(100) self.btn_ex.setFixedHeight(100) # self.btn_ex.setIcon(QIcon("image/ex_stu.gif")) self.btn_ex.setStyleSheet("background-color: rgba(255,255,255,20);") self.btn_ex.setIcon(QIcon("image/smile.png")) self.btn_ex.setIconSize(QSize(80,80)) self.btn_ex.setFlat(True) popMenu = QMenu(self) entry1 = popMenu.addAction("正确") # self.connect(entry1,SIGNAL('triggered()'), lambda item=item[0]: self.answerRight(item)) entry2 = popMenu.addAction("错误") # self.connect(entry2,SIGNAL('triggered()'), lambda item=item[0]: self.answerWrong(item)) entry3 = popMenu.addAction("替换") # self.connect(entry3,SIGNAL('triggered()'), lambda item=item[0]: self.resetStudent(item)) self.btn_ex.setMenu(popMenu) # Create the layout main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) # main_layout.addWidget(self.btn_ex) self.setLayout(main_layout) # Add the QMovie object to the label self.movie.setCacheMode(QMovie.CacheAll) # self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie_screen.setLayout(QHBoxLayout()) self.movie_screen.layout().addWidget(self.btn_ex) popMenu = QMenu(self) entry1 = popMenu.addAction("正确") # self.movie_screen.setMenu(popMenu) self.movie.start()
class Loading(QDialog): def __init__(self, parent, text=""): super(Loading, self).__init__(parent) self.setStyleSheet("background-color:white;") Gl.Signals["changeLoadingText"].connect(self.change_text) Gl.Signals["endLoading"].connect(self.on_end) self.setWindowTitle("Please wait") # Credit to zegerdon on DeviantArt for his loading gif. self.load_gif = QMovie(os.path.join(Gl.Graphics, "loading_by_zegerdon-deviantart.gif")) self.load_label = QLabel() self.load_label.setMovie(self.load_gif) self.text = QLabel(text) self.text.setStyleSheet("QLabel { color : black; }") self.vbox = QVBoxLayout() self.vbox.addWidget(self.load_label) self.vbox.setAlignment(self.load_label, Qt.AlignCenter) self.vbox.addWidget(self.text) self.vbox.setAlignment(self.text, Qt.AlignCenter) self.vbox.setMargin(20) self.vbox.setSpacing(30) self.setLayout(self.vbox) self.load_gif.start() self.end_loading = False def change_text(self, string): self.text.setText(string) def on_end(self): """ Close on signal. :return: """ self.end_loading = True self.close() # noinspection PyArgumentList def closeEvent(self, close_event): """ If closed by user, exit program. :return: """ if self.end_loading: super(Loading, self).close() else: Gl.Signals["KILL"].emit() QApplication.processEvents()
def View5(self): #Pasamos vista 5 #---------------------- #Aqui se pone el gif :) self.movie = QMovie(self.GIF) self.ui.the_gif.setMovie(self.movie) self.movie.start() #---------------------- #Te gusta la foto? self.ui.setCurrentWidget(self.ui.View5)
def set_widgets(self): """Set all widgets on the tab.""" self.project_combo_box.currentIndexChanged.connect( self.project_combo_box_changed) icon_path = resources_path('images', 'throbber.gif') movie = QMovie(icon_path) self.throbber_loader.setMovie(movie) movie.start() self.get_available_projects() self.project_combo_box.setFocus()
def mute(self): """stop the animation""" self.movie = QMovie(":/mute.gif", QByteArray(), self) self.movie.setScaledSize(CustomSize*0.7) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.muted = True #print("Emitted 'sig_mute'") self.emit(SIGNAL("sig_mute")) self.movie.start()
def create_gif_icon(dir_=None): icon = QIcon() movie = QMovie(dir_) def update_icon(): i = QIcon(movie.currentPixmap()) icon.swap(i) movie.frameChanged.connect(update_icon) movie.start() return icon
def choice_system(self): self.show() self.shop_image.hide() self.change_shop_button.hide() self.return_choice_button.hide() self.advertisement_button.hide() self.gif = QMovie(self.image_choice_system_path) self.change_status_label.setMovie(self.gif) self.gif.start() self.if_success.setText('') # self.change_status_label.setStyleSheet( # "QPushButton{background-image: url(%s)}" % # self.image_choice_system_path) self.change_status_label.show()
def trainOCR(self): self.train_button.setEnabled(False) alldata = self.connectData() testnumbers = self.getRandomData( alldata, [',', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) testletters = self.getRandomData(alldata, [ "'", ',', '-', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]) teststation = self.getRandomData(alldata, [ "'", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]) testlevel = self.getRandomData(alldata, ['*', '+', '#']) self.movie = QMovie(":/ico/loader.gif") self.loader.setMovie(self.movie) self.movie.start() self.numberstrainerthread = Trainer(self, "numbers", self.base, self.user, testnumbers, testletters, teststation, testlevel) self.letterstrainerthread = Trainer(self, "letters", self.base, self.user, testnumbers, testletters, teststation, testlevel) self.stationtrainerthread = Trainer(self, "station", self.base, self.user, testnumbers, testletters, teststation, testlevel) self.leveltrainerthread = Trainer(self, "level", self.base, self.user, testnumbers, testletters, teststation, testlevel) QObject.connect(self.numberstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.letterstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.stationtrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.leveltrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) #QObject.connect(self.trainerthread, SIGNAL('finishedall(int)'), self.trainingFinished) self.numberstrainerthread.execute() self.letterstrainerthread.execute() self.stationtrainerthread.execute() self.leveltrainerthread.execute() self.training_summary.setText("Training in progress")
def __init__(self): super(self.__class__, self).__init__() movie = QMovie(HERE_PATH + "/spinner.gif") movie.setScaledSize(QSize(23, 23)) movie.setSpeed(200) self.setMovie(movie) movie.start()
def __init__(self, model, parent=None): super(ServerToolsWindow, self).__init__(parent) with Resources.directory: self.setupUi(self) self.spinner_movie = QMovie(Resources.get("icons/servertools-spinner.mng")) self.spinner_label.setMovie(self.spinner_movie) self.spinner_label.hide() self.progress_bar.hide() while self.tab_widget.count(): self.tab_widget.removeTab(0) # remove the tab(s) added in designer self.tab_widget.tabBar().hide() self.account_button.setMenu(QMenu(self.account_button)) self.setWindowTitle("Blink Server Tools") self.setWindowIconText("Server Tools") self.model = model self.tab_widget.addTab(ServerToolsWebView(self), "") font = self.account_label.font() font.setPointSizeF(self.account_label.fontInfo().pointSizeF() + 2) font.setFamily("Sans Serif") self.account_label.setFont(font) self.model.rowsInserted.connect(self._SH_ModelChanged) self.model.rowsRemoved.connect(self._SH_ModelChanged) self.account_button.menu().triggered.connect(self._SH_AccountButtonMenuTriggered) web_view = self.tab_widget.currentWidget() web_view.loadStarted.connect(self._SH_WebViewLoadStarted) web_view.loadFinished.connect(self._SH_WebViewLoadFinished) web_view.loadProgress.connect(self._SH_WebViewLoadProgress)
def __init__(self): QWidget.__init__(self) self.tray = Tray(self) self.setMinimumSize(QSize(320, 200)) self.setWindowFlags(Qt.Popup|Qt.FramelessWindowHint) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setMargin(1) self.text = QTextBrowser(self) self.text.setReadOnly(True) self.text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text.setOpenExternalLinks(True) self.verticalLayout.addWidget(self.text) self.text.textChanged.connect(self.on_text_changed) self.notify = Notify(self) self.movie = QMovie() dev = QBuffer() dev.setData(QByteArray.fromBase64(CHECK_IMAGE)) dev.open(QBuffer.ReadOnly) dev.setParent(self.movie) self.movie.setDevice(dev) self.movie.frameChanged.connect(self.on_frame_changed) self.realized = False self.show()
def __init__(self, filename, title, parent=None): QWidget.__init__(self, parent) # Load the file into a QMovie self.movie = QMovie(filename, QByteArray(), self) size = self.movie.scaledSize() self.setGeometry(200, 200, size.width(), size.height()) self.setWindowTitle(title) self.movie_screen = QLabel() # Make label fit the gif self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) # Create the layout main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) # Add the QMovie object to the label self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.searchEdit.textChanged.connect(self.search_text_changed) self.ui.show_button.clicked.connect(self.show_episodes) self.ui.searchEdit.returnPressed.connect(self.show_episodes) self.episodes = None self.episode_list = None self.number = 0 self.anime_list = None self.ui.download_button.clicked.connect(self.download) self.ui.res_list_widget.currentItemChanged.connect(self.episode_change) self.com = Comunicate() self.com.sig.connect(self.message) self.com.img.connect(self.set_image) self.ui.anime_list_widget.itemDoubleClicked.connect(self.show_episodes) self.setWindowIcon(QIcon(get_file('animes.png'))) self.ui.anime_list_widget.itemPressed.connect(self.anime_entered) Thread(target=self.load_url_items).start() #self.load_url_items() self.movie = QMovie(get_file('ajax-loader.gif')) self.ui.loading_label.setMovie(self.movie) self.link = None self.main_download_page = None self.tray = SystemTrayIcon( QIcon(get_file('animes.png')), self.com, self) self.com.op.connect(self.show_semard) self.ui.action_About_Semard.activated.connect(self.about_semard) self.ui.action_Contato.activated.connect(self.show_feedback) self.setWindowTitle('Semard - Animes') self.browser = None self.player = None
def __init__(self, parent=None): QDialog.__init__(self, parent) self.ui = Ui_UpdateInstallProgressDialog() self.ui.setupUi(self) # Swap out the label with the gif to a movie that will actually display # it correctly. self.window = self.ui.updateIconLabel self.movie = QMovie(':/icons/icons/update-in-progress.gif', QByteArray(), self) # Run the GIF self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.window.setMovie(self.movie) self.movie.start()
def __init__(self, parent, text=""): super(Loading, self).__init__(parent) self.setStyleSheet("background-color:white;") Gl.Signals["changeLoadingText"].connect(self.change_text) Gl.Signals["endLoading"].connect(self.on_end) self.setWindowTitle("Please wait") # Credit to zegerdon on DeviantArt for his loading gif. self.load_gif = QMovie(os.path.join(Gl.Graphics, "loading_by_zegerdon-deviantart.gif")) self.load_label = QLabel() self.load_label.setMovie(self.load_gif) self.text = QLabel(text) self.text.setStyleSheet("QLabel { color : black; }") self.vbox = QVBoxLayout() self.vbox.addWidget(self.load_label) self.vbox.setAlignment(self.load_label, Qt.AlignCenter) self.vbox.addWidget(self.text) self.vbox.setAlignment(self.text, Qt.AlignCenter) self.vbox.setMargin(20) self.vbox.setSpacing(30) self.setLayout(self.vbox) self.load_gif.start() self.end_loading = False
def __init__(self, parent, radar, rect): global xscale, yscale self.rect = rect self.baseurl = self.mapurl(radar, rect, False) print "google map base url: "+self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) QtGui.QLabel.__init__(self, parent) self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie()
class LoadingItem(QLabel): def __init__(self): super(LoadingItem, self).__init__() self.movie = QMovie(resources.IMAGES["loading"]) self.setMovie(self.movie) self.movie.setScaledSize(QSize(16, 16)) self.movie.start() def add_item_to_tree(self, folder, tree, item_type=None, parent=None): if item_type is None: item = QTreeWidgetItem() item.setText(0, self.tr(' LOADING: "%1"').arg(folder)) else: item = item_type(parent, self.tr(' LOADING: "%1"').arg(folder), folder) tree.addTopLevelItem(item) tree.setItemWidget(item, 0, self) return item
def __init__(self, parent, text="", isLightTheme=True, onCloseSlot=None, showIP=False): QDialog.__init__(self, parent) self.onCloseSignal.connect(onCloseSlot) # Create connecting image connMov = QMovie(utils.getAbsoluteResourcePath('images/' + ('light' if isLightTheme else 'dark') + '/waiting.gif')) connMov.start() self.connImg = QLabel(self) self.connImg.setMovie(connMov) # Create connecting and IP address labels self.connLabel = QLabel(text, self) if showIP: self.ipLabel = QLabel(self.ipLabelPrefix + "Getting IP address...", self) self.ipHelpLabel = QLabel("Your friend should enter the IP address above as the host to connect to.\n" "Make sure that port " + str(constants.DEFAULT_PORT) + " is forwarded to " "this computer. See the help\nfor more info.", self) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.connImg) hbox.addSpacing(10) hbox.addWidget(self.connLabel) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox) if showIP: vbox.addSpacing(10) vbox.addWidget(QLine()) vbox.addSpacing(10) vbox.addWidget(self.ipLabel) vbox.addSpacing(10) vbox.addWidget(self.ipHelpLabel) vbox.addStretch(1) self.setLayout(vbox) if showIP: # Start the thread to get the IP address and update the IP label when finished self.ipThread = qtThreads.GetIPAddressThread(self.__setIPAddress, self.__getIPAddressFailure) self.ipThread.start()
def add_loading_widgets(self, children): # Generate list if only one item was given if not type(children) is list: item_list = [] item_list.append(children) children = item_list # Add loading widgets to tree items for child in children: if child.tree_item == None: return # Create loading widget load_widget = QtGui.QLabel() load_widget.resize(50,50) #load_widget.setMaximumSize(50,50) load_widget.setStyleSheet("QLabel { background-color: transparent; }") # Create animation load_anim = QMovie(self.datahandler.datapath("ui/images/loading_tree.gif"), "GIF", load_widget) load_anim.setCacheMode(QMovie.CacheAll) load_anim.setSpeed(150) load_anim.setScaledSize(QtCore.QSize(50,50)) # Add to data model and tree child.set_load_widget(load_widget, load_anim) self.tree.setItemWidget(child.tree_item, 1, load_widget)
class ImagePlayerDialog(QDialog): """ Class to display a loading git inside a Dialog when performing eavy computation """ def __init__(self, filename, parent=None): QWidget.__init__(self, parent) # Load the file into a QMovie self.movie = QMovie(filename, QByteArray(), self) size = self.movie.scaledSize() self.setGeometry(200, 200, size.width(), size.height()) self.movie_screen = QLabel() # Make label fit the gif self.movie_screen.setAlignment(Qt.AlignCenter) # Create the layout main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) # Add the QMovie object to the label self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start()
def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: return self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) self.wxmovie = QMovie(self.wxbuff, 'GIF') self.wwx.setMovie( self.wxmovie) if self.parent().isVisible(): self.wxmovie.start()
class LoadingItem(QLabel): def __init__(self): super(LoadingItem, self).__init__() self.movie = QMovie(resources.IMAGES['loading']) self.setMovie(self.movie) self.movie.setScaledSize(QSize(16, 16)) self.movie.start() def add_item_to_tree(self, folder, tree, item_type=None, parent=None): if item_type is None: item = QTreeWidgetItem() item.setText(0, self.tr(' LOADING: "%s"' % folder)) else: item = item_type(parent, self.tr(' LOADING: "%s"' % folder), folder) tree.addTopLevelItem(item) tree.setItemWidget(item, 0, self) return item
class Throbber(QLabel): """A throbber.""" def __init__(self): super(Throbber, self).__init__() self.setAlignment(Qt.AlignCenter) fname = multiplatform.get_path("encuentro/ui/media/throbber.gif") self._movie = QMovie(fname) self.setMovie(self._movie) def hide(self): """Overload to control the movie.""" self._movie.stop() super(Throbber, self).hide() def show(self): """Overload to control the movie.""" self._movie.start() super(Throbber, self).show()
def __init__(self, parent=None): """ Constructor """ QDialog.__init__(self, parent) label = QLabel(self) self.setFixedSize(100, 100) #self.setWindowOpacity(0.5) self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True) self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint) self.connect(self, SIGNAL("finished()"), self.close) self.setContentsMargins(0, 0, 0, 0) movie = QMovie(':/image/ajax-loader.gif') label.setMovie(movie) movie.start()
def __init__(self, parent=None): QWidget.__init__(self, parent) # Create connecting image self.connectingGif = QMovie( qtUtils.getAbsoluteImagePath('waiting.gif')) self.connectingGif.start() self.connetingImageLabel = QLabel(self) self.connetingImageLabel.setMovie(self.connectingGif) self.connectingLabel = QLabel(self) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.connetingImageLabel, alignment=Qt.AlignCenter) hbox.addSpacing(10) hbox.addWidget(self.connectingLabel, alignment=Qt.AlignCenter) hbox.addStretch(1) self.setLayout(hbox)
def __init__(self, parent, text=""): QDialog.__init__(self, parent) # Create waiting image waitingImage = QMovie(qtUtils.getAbsoluteImagePath('waiting.gif')) waitingImage.start() waitingImageLabel = QLabel(self) waitingImageLabel.setMovie(waitingImage) waitingLabel = QLabel(text, self) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(waitingImageLabel) hbox.addSpacing(10) hbox.addWidget(waitingLabel) hbox.addStretch(1) self.setLayout(hbox)
def __init__(self, conf_path): QtGui.QWidget.__init__(self) Ui_Procedure.__init__(self) self.setupUi(self) self.db_api = db_api.DBApi( utils.get_conf_value(conf_path, 'db', 'db_path')) self.image_advertisement_path = utils.get_static_images_path( conf_path, 'image_advisediment_name') self.image_advertisement_path_other = utils.get_static_images_path( conf_path, 'image_advisediment_name2') self.image_guide_path = utils.get_static_images_path( conf_path, 'image_guide_name') self.image_recogniting_path = utils.get_static_images_path( conf_path, 'image_recogniting_name') self.image_unidentified_path = utils.get_static_images_path( conf_path, 'image_unidentified_name') self.guide_timeout = int( utils.get_conf_value(conf_path, 'guide', 'timeout')) self.unidentified_timeout = int( utils.get_conf_value(conf_path, 'unidentified', 'timeout')) self.rec_sys_path = utils.get_static_images_path( conf_path, 'rec_sys_name') self.pra_sys_path = utils.get_static_images_path( conf_path, 'pra_sys_name') self.save_image_base_path = utils.get_conf_value( conf_path, 'cache_fruits_images', 'save_image_base_path') self.pra_button.setStyleSheet("QPushButton{border-image: url(%s)}" % self.pra_sys_path) self.rec_button.setStyleSheet("QPushButton{border-image: url(%s)}" % self.rec_sys_path) self.advertisement_movie = QMovie(self.image_advertisement_path) self.guide_movie = QMovie(self.image_guide_path) self.recogniting_movie = QMovie(self.image_recogniting_path) self.unidentified_movie = QMovie(self.image_unidentified_path) self.advertisement_button.clicked.connect(self.show_guide_ui) self.setWindowFlags(Qt.Qt.FramelessWindowHint) self.running_dialog = '' self.timeout_timer = QTimer() self.timeout_timer.timeout.connect(self.timeout_handler) self.image_choice_system_path = utils.get_static_images_path( conf_path, 'image_logo_name') self.pra_button.clicked.connect(self.show_praitce_dialog) self.rec_button.clicked.connect(self.show_advertisment_ui) self.return_choice_button.clicked.connect(self.upload_cloud) self.choice_system() self.change_shop_button.clicked.connect(self.show_praitce_dialog) self.file_path = '' self.practice_mode = False self.qthread = UploadImage(self.save_image_base_path) self.qthread.signal_upload_resp.connect(self.set_if_success_label) self.setStyleSheet("QPushButton{outline: none}")
def setStatus(self,status,message='',tooltip=None): '''Sets indicator icon and statusbar message''' self.parent.statusbar.showMessage(message) self.parent.statusbar.setToolTip(tooltip if tooltip else '') #progress loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status])) #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status])) self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN)) #icon anim = QMovie(loc, QByteArray(), self) anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT)) anim.setCacheMode(QMovie.CacheAll) anim.setSpeed(self.IMG_SPEED) self.view.clear() self.view.setMovie(anim) anim.start() self.view.repaint() QApplication.processEvents(QEventLoop.AllEvents)
def set_widgets(self): """Set all widgets on the tab.""" self.project_combo_box.currentIndexChanged.connect( self.project_combo_box_changed) checkbox_checked = get_setting('public_project') if checkbox_checked: self.public_projects_checkbox.setCheckState(Qt.Checked) self.public_projects_checkbox.stateChanged.connect( self.public_check_box_changed) icon_path = resources_path('images', 'throbber.gif') movie = QMovie(icon_path) self.throbber_loader.setMovie(movie) movie.start() self.get_available_projects() self.add_contact_label.mousePressEvent = self.add_contact_label_clicked self.set_enabled_add_contact_label(False) self.project_combo_box.setFocus() set_setting('public_project', self.public_projects_checkbox.checkState() == Qt.Checked)
def on_radioButton_clicked(self, checked): """ Slot documentation goes here. """ # TODO: not implemented yet global audio, record_t movie = QMovie(":/icon/icon/siri.gif") self.label_4.setMovie(movie) if checked: self.label_4.setStyleSheet("") movie.start() if self.thread_flag == 0: print "abcd" self.start_flag = 1 record_t = MyThread(ui.record_wave, (ui, ), ui.record_wave.__name__) record_t.setDaemon(True) record_t.start() self.thread_flag = 1 else: movie.stop() self.label_4.setStyleSheet( "border-image: url(:/icon/icon/siri.gif);") if self.thread_flag == 1: self.start_flag = 0 self.thread_flag = 0
def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: print "get radar error " + self.myname + ":" + \ str(self.wxreply.error()) self.lastwx = 0 return print "radar map received:" + self.myname + ":" + time.ctime() self.wxmovie.stop() self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) mov = QMovie(self.wxbuff, 'GIF') print "radar map frame count:" + self.myname + ":" + \ str(mov.frameCount()) + ":r" + str(self.retries) if mov.frameCount() > 2: self.lastwx = time.time() self.retries = 0 else: # radar image retreval failed if self.retries > 3: # give up, last successful animation stays. # the next normal radar_refresh time (default 10min) will apply self.lastwx = time.time() return self.lastwx = 0 # count retries self.retries = self.retries + 1 # retry in 5 seconds QtCore.QTimer.singleShot(5 * 1000, self.getwx) return self.wxmovie = mov if self.satellite: self.setMovie(self.wxmovie) else: self.wwx.setMovie(self.wxmovie) if self.parent().isVisible(): self.wxmovie.start()
def notifyTimeout(self): self.timeoutCount += 1 if self.timeoutCount == self.notifyCount: msg = self.tr(u'No fix for %s since more than %d seconds!') % (self.name, self.timeoutTime * self.timeoutCount / 1000) w = self.iface.messageBar().createMessage(self.tr(u'PosiView Attention'), msg) l = QLabel(w) m = QMovie(':/plugins/PosiView/hand.gif') m.setSpeed(75) l.setMovie(m) m.setParent(l) m.start() w.layout().addWidget(l) self.iface.messageBar().pushWidget(w, QgsMessageBar.CRITICAL, duration=self.notifyDuration)
def __init__(self, visualization, parent_widget = None): QWidget.__init__(self, parent_widget) self.inGui = False self.visualization = visualization size = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.widgetLayout = QGridLayout(self) self.setSizePolicy(size) self.scroll = QScrollArea() file_path = self.visualization.get_file_path() self.label = QLabel() movie = QMovie(QString(file_path), QByteArray(), self) movie.setCacheMode(QMovie.CacheAll) self.label.setMovie(movie) movie.start() self.scroll.setWidget(self.label) self.widgetLayout.addWidget(self.scroll) self.tabIcon = QIcon(":/Images/Images/map.png") self.tabLabel = visualization.table_name
def animationLabel(self, index, animationFile): """ Public slot to set an animated icon. @param index tab index (integer) @param animationFile name of the file containing the animation (string) @return reference to the created label (QLabel) """ if index == -1: return None if hasattr(self.__tabBar, 'setTabButton'): side = self.__freeSide() animation = QLabel(self) if animationFile and not animation.movie(): movie = QMovie(animationFile, QByteArray(), animation) movie.setSpeed(50) animation.setMovie(movie) movie.start() self.__tabBar.setTabButton(index, side, None) self.__tabBar.setTabButton(index, side, animation) return animation else: return None
def notifyTimeout(self): self.timeoutCount += 1 if self.timeoutCount == self.notifyCount: msg = self.tr(u'No fix for %s since more than %d seconds!') % ( self.name, self.timeoutTime * self.timeoutCount / 1000) w = self.iface.messageBar().createMessage( self.tr(u'PosiView Attention'), msg) l = QLabel(w) m = QMovie(':/plugins/PosiView/hand.gif') m.setSpeed(75) l.setMovie(m) m.setParent(l) m.start() w.layout().addWidget(l) self.iface.messageBar().pushWidget(w, QgsMessageBar.CRITICAL, duration=self.notifyDuration)
def setImage(self, img=None, fauxChemin=None, anim=False): """Fonction de mise en place de l'image. Le faux chemin est utile pour dissocier le chemin que verra l'utilisateur du chemin de l'image affichée. Ils sont différents uniquement lorsqu'une image composite est affichée (cadres masque alpha 3D et image composite). L'argument "anim" dit si une image gif doit être animée. """ if not img: img = "Icones" + os.sep + "avant-image.png" self.setToolTip(_(u"image d'accueil")) self.setTailleReelle() return elif fauxChemin: self.setToolTip(fauxChemin) else: self.setToolTip(img) # Chargement du gif le cas échéant if isinstance(img, str) or isinstance(img, unicode): # En général extension = os.path.splitext(img)[1] elif isinstance(img, QString): # Pour selectWidget.py principalement extension = "." + QFileInfo(img).suffix() if extension == ".gif": self.menuStartPauseGif.setVisible(True) self.menuStopGif.setVisible(True) self.gif = 1 self.movie = QMovie(img) # On démarre le gif de toute façon sinon l'image n'est pas visible self.movie.start() if not anim: self.movie.stop() self.imageLabel.setMovie(self.movie) else: # Pour des images non-gif, on cache les menus d'animation self.menuStartPauseGif.setVisible(False) self.menuStopGif.setVisible(False) self.gif = 0 # Visiblement sous windows la taille du QScrollArea renvoie 0, # on passe par l'Objet à l'intérieur pour obtenir la taille de l'image à créer self.preview = EkdPreview(img, self.width(), 0, 10, False, True, True) #(chemin, largeur, qualité, cache?, keepRatio?, magnify? ) # Par défault on charge en taille fenetre self.setTailleFenetre()
def trainOCR(self): self.train_button.setEnabled(False) alldata = self.connectData() testnumbers = self.getRandomData(alldata,[',', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) testletters = self.getRandomData(alldata,["'", ',', '-', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) teststation = self.getRandomData(alldata,["'", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) self.movie = QMovie(":/ico/loader.gif") self.loader.setMovie(self.movie) self.movie.start() self.numberstrainerthread = Trainer(self, "numbers", self.base, self.user, testnumbers, testletters, teststation) self.letterstrainerthread = Trainer(self, "letters", self.base, self.user, testnumbers, testletters, teststation) self.stationtrainerthread = Trainer(self, "station", self.base, self.user, testnumbers, testletters, teststation) QObject.connect(self.numberstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.letterstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.stationtrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) #QObject.connect(self.trainerthread, SIGNAL('finishedall(int)'), self.trainingFinished) self.numberstrainerthread.execute() self.letterstrainerthread.execute() self.stationtrainerthread.execute() self.training_summary.setText("Training in progress")
def UIfixes(self): ''' Stuff you can't do on QtDesigner ''' # reimplementing drops self.ui.fileDropTextLine.__class__.dragMoveEvent = self.mydragMoveEvent self.ui.fileDropTextLine.__class__.dragEnterEvent =self.mydragEnterEvent self.ui.fileDropTextLine.__class__.dropEvent = self.myDropEvent # Waiting animation self.ui.movie_screen.setFixedHeight(0) self.movie = QMovie("loader.gif", QByteArray(), self) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.ui.movie_screen.setMovie(self.movie) if len(self.machinesData) != 0: # if the user already created clients.exe self.ui.tabWidget.setCurrentWidget(self.ui.serverTab) self.table.verticalHeader().setVisible(False) # QtDesigner miss this self.ui.passwordTextBox.setEchoMode(2) # how to do this on Qtdesigner? # darn it QtDesign get your stuff together if configExists: self.ui.usernameTextBox.setText(configFile['USERNAME']) self.ui.passwordTextBox.setText(configFile['PASSWORD'])
def modelsPage(self): models = WizardPageEx('modelCheck') models.setTitle('Forecast') lbl = QLabel("<font style='color: gray'>Forecast horizon:</font>") self.steps = QSpinBox() self.steps.setRange(MIN_FORECAST, MAX_FORECAST) self.steps.setValue(10) self.start = QPushButton('Forecast') self.start.clicked.connect(self.modelling) self.custom = QPushButton('Advanced') self.processing = QLabel() self.gifLoading = QMovie(RES + ICONS + PROGRESS, QByteArray(), self) self.gifLoading.setCacheMode(QMovie.CacheAll) self.gifLoading.setSpeed(100) self.processing.setMovie(self.gifLoading) self.processing.setAlignment(Qt.AlignCenter) self.processing.hide() self.status = QLabel() self.status.setAlignment(Qt.AlignCenter) self.status.hide() layout = QGridLayout() layout.addWidget(lbl, 0, 0) layout.addWidget(self.steps, 0, 1) layout.addWidget(self.start, 0, 2) layout.addWidget(self.custom, 0, 3) layout.addWidget(self.status, 1, 0, 1, 4) layout.addWidget(self.processing, 2, 0, 1, 4) models.setLayout(layout) self.customOpt = CustomOption() self.custom.clicked.connect(self.customOpt.show) self.modelCheck = models.check return models
class VisionneurImagePourEKD(QScrollArea): ''' Classe pour l'affichage des images (avec des barres de défilement)''' def __init__(self, img=None): QScrollArea.__init__(self) # Déclaration du drapeau: a-t-on chargé un *.gif if img and os.path.splitext(img)[1]!=".gif": self.gif = 1 else: self.gif = 0 # Facteur de redimensionnement de l'image à afficher par rapport à la taille réelle de l'image self.factor = 1 # Variables de paramètres self.modeTransformation=Qt.SmoothTransformation #self.modeTransformation=Qt.FastTransformation # widget qui contiendra l'image self.imageLabel = QLabel() self.imageLabel.setAlignment(Qt.AlignCenter) self.setBackgroundRole(QPalette.Dark) self.setWidget(self.imageLabel) # Indispensable pour ne pas avoir d'images tronquées, lors du chargement de nvll img self.setWidgetResizable(True) # Position du curseur dans le QScrollArea au moment du clic de la souris self.positionPresseeSourisIni = QPoint() # Position du point haut-gauche du QScrollArea par rapport au QPixMap entier au # moment du clic de la souris (par la suite appelée "position de la barre de défilement") self.positionBarrePresseeSourisIni = QPoint() # Création du menu contextuel self.menuZoom=QMenu("Zoom") # Entrée zoom taille réelle self.menuTailleReelle=self.menuZoom.addAction(_(u'&Taille Réelle')) self.menuTailleReelle.setIcon(QIcon("Icones" + os.sep + "taillereelle.png")) self.connect(self.menuTailleReelle, SIGNAL("triggered()"), self.setTailleReelle) # Entrée zoom taille fenetre self.menuTailleFenetre=self.menuZoom.addAction(_(u'&Adapter à la fenêtre')) self.menuTailleFenetre.setIcon(QIcon("Icones" + os.sep + "fenetre.png")) self.connect(self.menuTailleFenetre, SIGNAL("triggered()"), self.setTailleFenetre) # Entrée zoom + self.menuZoomPlus=self.menuZoom.addAction(_(u'&Zoom Avant')) self.menuZoomPlus.setIcon(QIcon("Icones" + os.sep + "zoomplus.png")) self.connect(self.menuZoomPlus, SIGNAL("triggered()"), self.zoomAvant) # Entrée zoom - self.menuZoomMoins=self.menuZoom.addAction(_(u'&Zoom Arrière')) self.menuZoomMoins.setIcon(QIcon("Icones" + os.sep + "zoommoins.png")) self.connect(self.menuZoomMoins, SIGNAL("triggered()"), self.zoomArriere) # Entrée mettre en pause/démarrer l'animation du gif self.menuStartPauseGif=self.menuZoom.addAction(_(u"Mettre en pause/démarrer l'animation")) self.menuStartPauseGif.setIcon(QIcon("Icones" + os.sep + "player_end.png")) self.connect(self.menuStartPauseGif, SIGNAL("triggered()"), self.startPauseGif) # Entrée mettre en pause/démarrer l'animation du gif self.menuStopGif=self.menuZoom.addAction(_(u"Arrêter l'animation")) self.menuStopGif.setIcon(QIcon("Icones" + os.sep + "player_stop.png")) self.connect(self.menuStopGif, SIGNAL("triggered()"), self.stopGif) # On cache les 2 menus de *.gif si on ne traite pas ce format if not self.gif: self.menuStartPauseGif.setVisible(False) self.menuStopGif.setVisible(False) # Si une image est en paramètre de classe, on l'affiche directement # sinon on pourra toujours l'afficher plus tard en appelant la # méthode setImage(), le moment venu if img: self.setImage(img) self.setToolTip(img) else: # image par défaut self.setImage("Icones" + os.sep + "avant-image.png") self.setToolTip(_(u"image d'accueil")) self.setTailleReelle() def mousePressEvent(self, event): "Menu contextuel et enregistrement de données préparant le déplacement de l'image par pincement" # Menu contextuel if event.button() == Qt.RightButton: self.menuZoom.popup(event.globalPos()) # On enregistre la position du curseur et de la barre de défilement au moment du clic elif event.button() == Qt.LeftButton: self.positionPresseeSourisIni = QPoint(event.pos()) self.positionBarrePresseeSourisIni.setX(self.horizontalScrollBar().value()) self.positionBarrePresseeSourisIni.setY(self.verticalScrollBar().value()) if PYQT_VERSION_STR >= "4.1.0": # curseur main fermée self.setCursor(Qt.ClosedHandCursor) else: self.setCursor(Qt.SizeAllCursor) event.accept() def mouseMoveEvent(self, event): "Déplacement de l'image dans le QScrollArea quand la souris est pressée" if self.positionPresseeSourisIni.isNull(): event.ignore() return # Nouvelles positions de la barre de défilement (selon x et y) self.horizontalScrollBar().setValue(self.positionBarrePresseeSourisIni.x() + (self.positionPresseeSourisIni.x() - event.pos().x())) self.verticalScrollBar().setValue(self.positionBarrePresseeSourisIni.y() + (self.positionPresseeSourisIni.y() - event.pos().y())) self.horizontalScrollBar().update() self.verticalScrollBar().update() event.accept() def mouseReleaseEvent(self, event): "Réaffichage du curseur classique de la souris" self.setCursor(Qt.ArrowCursor) event.accept() def setScaleMode(self, mode): "Choix du mode de redimensionnement" # Mise à jour du paramètre self.modeTransformation=mode def setTailleFenetre(self): "Affichage taille fenetre" # Gestion de la taille #- Si l'image rentre ##- Si l'image est trop grande # On retaille l'image en gardant le ratio entre # le min (si l'image ne rentre pas dans le cadre), le max (sinon) de : # * La largeur de la fenetre # * La largeur de l'image # * La hauteur de la fenetre # * La hauteur de l'image if (self.preview.height() < self.height()) and (self.preview.width() < self.width()): width=max(self.preview.width(), self.width()) height=max(self.preview.height(), self.height()) else : width=min(self.preview.width(), self.width()) height=min(self.preview.height(), self.height()) if self.gif: self.redimGif(width - 5, height - 5) else: resultat = self.preview.get_preview().scaled(width - 5, height - 5, Qt.KeepAspectRatio, self.modeTransformation) debug(u"Preview : %s, taille : %d, %d" % (self.preview.get_imageName(), self.preview.width(), self.preview.height())) self.factor = min(float(self.height())/self.preview.height(), float(self.width())/self.preview.width()) #-- On met l'image et on redimensionne le Label pour les images simples if not self.gif: self.imageLabel.setPixmap(resultat) def setTailleReelle(self): "Fonction d'affichage en taille réelle" self.preview.origin() width, height = self.preview.width(), self.preview.height() # On redimensionne le label à la taille de l'image if self.gif: self.redimGif(width, height) else: self.imageLabel.setPixmap(self.preview.get_preview()) self.factor = 1 def zoomAvant(self): "Fonction de zoom avant 25%" # On redimensionne l'image à 125% de la taille actuelle factor = 5/4. * self.factor width = int(self.preview.width() * factor) height = int(self.preview.height() * factor) if self.gif: self.redimGif(width, height) else: image = self.preview.get_preview().scaled(width, height, Qt.KeepAspectRatio) self.imageLabel.setPixmap(image) self.factor = factor def zoomArriere(self): "Fonction de zoom arrière 25%" # On redimensionne l'image à 75% de la taille actuelle factor = 3/4. * self.factor width = int(self.preview.width() * factor) height = int(self.preview.height() * factor) if self.gif: self.redimGif(width, height) else: image = self.preview.get_preview().scaled(width, height, Qt.KeepAspectRatio) self.imageLabel.setPixmap(image) self.factor = factor def startPauseGif(self): "Démarrer/mettre en pause l'animation de l'image gif" if self.movie.state() == QMovie.NotRunning: self.movie.start() else: self.movie.setPaused(self.movie.state() != QMovie.Paused) def stopGif(self): "Arrêter l'animation de l'image gif" if self.movie.state() != QMovie.NotRunning: self.movie.stop() def redimGif(self, width, height): """Changer la taille d'affichage du gif en prenant soin d'arrêter et de reprendre l'animation si nécessaire. Il y a un petit bogue d'affichage sur la redimension (il disparait en changeant d'onglet ou de cadre et en revenant. """ etatInitial = self.movie.state() if etatInitial == QMovie.Running: self.movie.stop() self.movie.setScaledSize(QSize(width, height)) if etatInitial == QMovie.Running: self.movie.start() else: # On redémarre le gif sinon l'image n'est pas actualisée et reste à la même taille self.movie.start() self.movie.stop() def isGif(self): "Indique si l'image affichée est un gif. Le test est effectué sur l'extension du fichier" return self.gif def setImage(self, img=None, fauxChemin=None, anim=False): """Fonction de mise en place de l'image. Le faux chemin est utile pour dissocier le chemin que verra l'utilisateur du chemin de l'image affichée. Ils sont différents uniquement lorsqu'une image composite est affichée (cadres masque alpha 3D et image composite). L'argument "anim" dit si une image gif doit être animée. """ if not img: img = "Icones" + os.sep + "avant-image.png" self.setToolTip(_(u"image d'accueil")) self.setTailleReelle() return elif fauxChemin: self.setToolTip(fauxChemin) else: self.setToolTip(img) # Chargement du gif le cas échéant if isinstance(img, str) or isinstance(img, unicode): # En général extension = os.path.splitext(img)[1] elif isinstance(img, QString): # Pour selectWidget.py principalement extension = "." + QFileInfo(img).suffix() if extension == ".gif": self.menuStartPauseGif.setVisible(True) self.menuStopGif.setVisible(True) self.gif = 1 self.movie = QMovie(img) # On démarre le gif de toute façon sinon l'image n'est pas visible self.movie.start() if not anim: self.movie.stop() self.imageLabel.setMovie(self.movie) else: # Pour des images non-gif, on cache les menus d'animation self.menuStartPauseGif.setVisible(False) self.menuStopGif.setVisible(False) self.gif = 0 # Visiblement sous windows la taille du QScrollArea renvoie 0, # on passe par l'Objet à l'intérieur pour obtenir la taille de l'image à créer self.preview = EkdPreview(img, self.width(), 0, 10, False, True, True) #(chemin, largeur, qualité, cache?, keepRatio?, magnify? ) # Par défault on charge en taille fenetre self.setTailleFenetre()
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect): global xscale, yscale self.rect = rect self.baseurl = self.mapurl(radar, rect, False) print "google map base url: "+self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) QtGui.QLabel.__init__(self, parent) self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie() def mapurl(self, radar,rect,markersonly): #'https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er='+rcenter.lat+','+rcenter.lng+'&zoom='+rzoom+'&size=300x275'+markersr; urlp = []; if len(ApiKeys.googleapi) > 0: urlp.append('key='+ApiKeys.googleapi) urlp.append('center='+str(radar['center'].lat)+','+str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width()/2,rsize.height()/2) zoom -= 1 urlp.append('zoom='+str(zoom)) urlp.append('size='+str(rsize.width())+'x'+str(rsize.height())) if markersonly: urlp.append('style=visibility:off') else: urlp.append('maptype=hybrid') for marker in radar['markers']: marks = [] for opts in marker: if opts != 'location': marks.append(opts + ':' + marker[opts]) marks.append(str(marker['location'].lat)+','+str(marker['location'].lng)) urlp.append('markers='+'|'.join(marks)) return 'http://maps.googleapis.com/maps/api/staticmap?'+'&'.join(urlp) def radarurl(self,radar,rect): #wuprefix = 'http://api.wunderground.com/api/'; #wuprefix+wuapi+'/animatedradar/image.gif?maxlat='+rNE.lat+'&maxlon='+rNE.lng+'&minlat='+rSW.lat+'&minlon='+rSW.lng+wuoptionsr; #wuoptionsr = '&width=300&height=275&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1'; rr = getCorners(radar['center'],radar['zoom'],rect.width(),rect.height()) return (Config.wuprefix+ApiKeys.wuapi+'/animatedradar/image.gif'+ '?maxlat='+str(rr['N'])+ '&maxlon='+str(rr['E'])+ '&minlat='+str(rr['S'])+ '&minlon='+str(rr['W'])+ '&width='+str(rect.width())+ '&height='+str(rect.height())+ '&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1&radar_bitmap=1&xnoclutter=1&xnoclutter_mask=1&cors=1' ) def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) def mkfinished(self): if self.mkreply.error() != QNetworkReply.NoError: return self.mkpixmap = QPixmap() self.mkpixmap.loadFromData(self.mkreply.readAll()) if self.mkpixmap.size() != self.rect.size(): self.mkpixmap = self.mkpixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.wmk.setPixmap(self.mkpixmap) def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: return self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) self.wxmovie = QMovie(self.wxbuff, 'GIF') self.wwx.setMovie( self.wxmovie) if self.parent().isVisible(): self.wxmovie.start() def getwx(self): global manager self.wxreq = QNetworkRequest(QUrl(self.wxurl+'&rrrand='+str(time.time()))) self.wxreply = manager.get(self.wxreq) QtCore.QObject.connect(self.wxreply, QtCore.SIGNAL("finished()"),self.wxfinished) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply,QtCore.SIGNAL("finished()"),self.basefinished) def getmk(self): global manager self.mkreq = QNetworkRequest(QUrl(self.mkurl)) self.mkreply = manager.get(self.mkreq) QtCore.QObject.connect(self.mkreply,QtCore.SIGNAL("finished()"),self.mkfinished) def start(self, interval=10*60*1000): self.getbase() self.getmk() self.getwx() self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer,QtCore.SIGNAL("timeout()"), self.getwx) self.timer.start(interval) def wxstart(self): self.wxmovie.start() def wxstop(self): self.wxmovie.stop() def stop(self): try: self.timer.stop() self.timer = None if self.wxmovie: self.wxmovie.stop() except Exception: pass
class Radar(QtGui.QLabel): def __init__(self, parent, radar, rect, myname): global xscale, yscale self.myname = myname self.rect = rect self.baseurl = self.mapurl(radar, rect, False) #print "google map base url: "+self.baseurl self.mkurl = self.mapurl(radar, rect, True) self.wxurl = self.radarurl(radar, rect) QtGui.QLabel.__init__(self, parent) self.interval = Config.radar_refresh*60 self.lastwx = 0 self.setObjectName("radar") self.setGeometry(rect) self.setStyleSheet("#radar { background-color: grey; }") self.setAlignment(Qt.AlignCenter) self.wwx = QtGui.QLabel(self) self.wwx.setObjectName("wx") self.wwx.setStyleSheet("#wx { background-color: transparent; }") self.wwx.setGeometry(0, 0, rect.width(), rect.height()) self.wmk = QtGui.QLabel(self) self.wmk.setObjectName("mk") self.wmk.setStyleSheet("#mk { background-color: transparent; }") self.wmk.setGeometry(0, 0, rect.width(), rect.height()) self.wxmovie = QMovie() def mapurl(self, radar,rect,markersonly): #'https://maps.googleapis.com/maps/api/staticmap?maptype=hybrid¢er='+rcenter.lat+','+rcenter.lng+'&zoom='+rzoom+'&size=300x275'+markersr; urlp = []; if len(ApiKeys.googleapi) > 0: urlp.append('key='+ApiKeys.googleapi) urlp.append('center='+str(radar['center'].lat)+','+str(radar['center'].lng)) zoom = radar['zoom'] rsize = rect.size() if rsize.width() > 640 or rsize.height() > 640: rsize = QtCore.QSize(rsize.width()/2,rsize.height()/2) zoom -= 1 urlp.append('zoom='+str(zoom)) urlp.append('size='+str(rsize.width())+'x'+str(rsize.height())) if markersonly: urlp.append('style=visibility:off') else: urlp.append('maptype=hybrid') for marker in radar['markers']: marks = [] for opts in marker: if opts != 'location': marks.append(opts + ':' + marker[opts]) marks.append(str(marker['location'].lat)+','+str(marker['location'].lng)) urlp.append('markers='+'|'.join(marks)) return 'http://maps.googleapis.com/maps/api/staticmap?'+'&'.join(urlp) def radarurl(self,radar,rect): #wuprefix = 'http://api.wunderground.com/api/'; #wuprefix+wuapi+'/animatedradar/image.gif?maxlat='+rNE.lat+'&maxlon='+rNE.lng+'&minlat='+rSW.lat+'&minlon='+rSW.lng+wuoptionsr; #wuoptionsr = '&width=300&height=275&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1'; rr = getCorners(radar['center'],radar['zoom'],rect.width(),rect.height()) return (Config.wuprefix+ApiKeys.wuapi+'/animatedradar/image.gif'+ '?maxlat='+str(rr['N'])+ '&maxlon='+str(rr['E'])+ '&minlat='+str(rr['S'])+ '&minlon='+str(rr['W'])+ '&width='+str(rect.width())+ '&height='+str(rect.height())+ '&newmaps=0&reproj.automerc=1&num=5&delay=25&timelabel=1&timelabel.y=10&rainsnow=1&smooth=1&radar_bitmap=1&xnoclutter=1&xnoclutter_mask=1&cors=1' ) def basefinished(self): if self.basereply.error() != QNetworkReply.NoError: return self.basepixmap = QPixmap() self.basepixmap.loadFromData(self.basereply.readAll()) if self.basepixmap.size() != self.rect.size(): self.basepixmap = self.basepixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(self.basepixmap) def mkfinished(self): if self.mkreply.error() != QNetworkReply.NoError: return self.mkpixmap = QPixmap() self.mkpixmap.loadFromData(self.mkreply.readAll()) if self.mkpixmap.size() != self.rect.size(): self.mkpixmap = self.mkpixmap.scaled(self.rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.wmk.setPixmap(self.mkpixmap) def wxfinished(self): if self.wxreply.error() != QNetworkReply.NoError: print "get radar error "+self.myname+":"+str(self.wxreply.error()) self.lastwx = 0 return print "radar map received:"+self.myname+":"+time.ctime() self.wxmovie.stop() self.wxdata = QtCore.QByteArray(self.wxreply.readAll()) self.wxbuff = QtCore.QBuffer(self.wxdata) self.wxbuff.open(QtCore.QIODevice.ReadOnly) mov = QMovie(self.wxbuff, 'GIF') print "radar map frame count:"+self.myname+":"+str(mov.frameCount()) if mov.frameCount() > 2: self.lastwx = time.time() else: # radar image retreval failed self.lastwx = 0 # retry in 5 seconds QtCore.QTimer.singleShot(5*1000, self.getwx) return self.wxmovie = mov self.wwx.setMovie( self.wxmovie) if self.parent().isVisible(): self.wxmovie.start() def getwx(self): global lastapiget i = 0.1 # making sure there is at least 2 seconds between radar api calls lastapiget += 2 if time.time() > lastapiget: lastapiget = time.time() else: i = lastapiget - time.time() print "get radar api call spacing oneshot get i="+str(i) QtCore.QTimer.singleShot(i*1000, self.getwx2) def getwx2(self): global manager try: if self.wxreply.isRunning(): return except Exception: pass print "getting radar map "+self.myname+":"+time.ctime() self.wxreq = QNetworkRequest(QUrl(self.wxurl+'&rrrand='+str(time.time()))) self.wxreply = manager.get(self.wxreq) QtCore.QObject.connect(self.wxreply, QtCore.SIGNAL("finished()"),self.wxfinished) def getbase(self): global manager self.basereq = QNetworkRequest(QUrl(self.baseurl)) self.basereply = manager.get(self.basereq) QtCore.QObject.connect(self.basereply,QtCore.SIGNAL("finished()"),self.basefinished) def getmk(self): global manager self.mkreq = QNetworkRequest(QUrl(self.mkurl)) self.mkreply = manager.get(self.mkreq) QtCore.QObject.connect(self.mkreply,QtCore.SIGNAL("finished()"),self.mkfinished) def start(self, interval=0): if interval > 0: self.interval = interval self.getbase() self.getmk() self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer,QtCore.SIGNAL("timeout()"), self.getwx) def wxstart(self): print "wxstart for "+self.myname if (self.lastwx == 0 or (self.lastwx+self.interval) < time.time()): self.getwx() # random 1 to 10 seconds added to refresh interval to spread the queries over time i = (self.interval+random.uniform(1,10))*1000 self.timer.start(i) self.wxmovie.start() QtCore.QTimer.singleShot(1000, self.wxmovie.start) def wxstop(self): print "wxstop for "+self.myname self.timer.stop() self.wxmovie.stop() def stop(self): try: self.timer.stop() self.timer = None if self.wxmovie: self.wxmovie.stop() except Exception: pass
def __init__(self): super(LoadingItem, self).__init__() self.movie = QMovie(resources.IMAGES['loading']) self.setMovie(self.movie) self.movie.setScaledSize(QSize(16, 16)) self.movie.start()
class LearningWizard(QWizard, Ui_Wizard): def __init__(self, settings): QWizard.__init__(self) self.setupUi(self) self.settings = settings self.wizardPage3.pageCreated.connect(self.showSummary) self.wizardPage3.fullfilled = True self.wizardPage2.fullfilled = True self.errors = 0 self.steps = 0 self.delete_images_button.clicked.connect(self.deleteUserImages) self.add_files_button.clicked.connect(self.AddFiles) self.remove_file_button.clicked.connect(self.removeFile) self.save_button.clicked.connect(self.saveImgData) self.train_button.clicked.connect(self.trainOCR) self.ocr_button.clicked.connect(self.runOCR) self.next_button.clicked.connect(self.nextWord) self.prev_button.clicked.connect(self.previousWord) #self.add_screenshots.clicked.connect(self.AddFiles) #self.wizardPage2.pageCreated.connect(self.AnalyzeImg) #self.contrast = 0.0 #self.img_fields = [self.g1,self.g2,self.g3,self.g4,self.g5,self.g6,self.g7,self.g8,self.g9,self.g10,self.g11,self.g12,self.g13,self.g14,self.g15,self.g16,self.g17,self.g18,self.g19,self.g20] #self.input_fields = [self.e1,self.e2,self.e3,self.e4,self.e5,self.e6,self.e7,self.e8,self.e9,self.e10,self.e11,self.e12,self.e13,self.e14,self.e15,self.e16,self.e17,self.e18,self.e19,self.e20] self.gviews = [] self.ledits = [] self.boxlist = [] self.imglist = [] self.charlist = [] self.words = [] self.boundaries = [] self.wordcount = 0 self.current = 0 self.scene = None self.ratio_h = 1.0 self.ratio_w = 1.0 self.base = self.loadBase() self.user = self.loadUser() if not self.base is None: self.base_data_label.setText(self.getBaseData()) if not self.user is None: self.delete_images_button.setEnabled(True) self.user_data_label.setText(self.getUserData()) #self.resizeElements() #for index,item in zip(range(20), self.input_fields): # item.textEdited.connect(partial(self.changeText, index)) self.train_button.setEnabled(True) #self.grid = QGridLayout() #self.field_holder.addLayout(self.grid) def deleteUserImages(self): self.user = None path = self.settings.storage_path+os.sep+"user_training_data.pck" remove(path) self.user_data_label.setText("-") self.delete_images_button.setEnabled(False) def showSummary(self): summary = "" userdata = {} characters = ["'", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '*', '+', '#'] for word in self.words: for letter in word: if letter[1] in characters: if letter[1] in userdata: userdata[letter[1]] += 1 else: userdata[letter[1]] = 1 for key in characters: if key in userdata: summary += '"'+key+'"' +": " +str(userdata[key])+", " self.summary_label.setText(summary) def trainOCR(self): self.train_button.setEnabled(False) alldata = self.connectData() testnumbers = self.getRandomData(alldata,[',', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) testletters = self.getRandomData(alldata,["'", ',', '-', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) teststation = self.getRandomData(alldata,["'", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) testlevel = self.getRandomData(alldata,['*', '+', '#']) self.movie = QMovie(":/ico/loader.gif") self.loader.setMovie(self.movie) self.movie.start() self.numberstrainerthread = Trainer(self, "numbers", self.base, self.user, testnumbers, testletters, teststation, testlevel) self.letterstrainerthread = Trainer(self, "letters", self.base, self.user, testnumbers, testletters, teststation, testlevel) self.stationtrainerthread = Trainer(self, "station", self.base, self.user, testnumbers, testletters, teststation, testlevel) self.leveltrainerthread = Trainer(self, "level" , self.base, self.user, testnumbers, testletters, teststation, testlevel) QObject.connect(self.numberstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.letterstrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.stationtrainerthread, SIGNAL('finished(QString, int)'), self.stepFinished) QObject.connect(self.leveltrainerthread , SIGNAL('finished(QString, int)'), self.stepFinished) #QObject.connect(self.trainerthread, SIGNAL('finishedall(int)'), self.trainingFinished) self.numberstrainerthread.execute() self.letterstrainerthread.execute() self.stationtrainerthread.execute() self.leveltrainerthread.execute() self.training_summary.setText("Training in progress") def trainingFinished(self): if self.errors < 3: self.training_summary.setText("The training sucessfully finished. Your OCR accuracy should be very high.") elif self.errors < 6: self.training_summary.setText("The training sucessfully finished. Your OCR accuracy should satisfactory. You might still increase it by repeating this process with other screenshots.") elif self.errors < 10: self.training_summary.setText("The training sucessfully finished. Your OCR accuracy is sufficient but not perfect. You should repeat this process with other screenshots.") else: self.training_summary.setText("The training finished. Your OCR accuracy is not sufficient. You should repeat this process with other screenshots.") def stepFinished(self, value, error): self.steps += 1 self.details.append(value+"\n") self.errors += error if self.steps == 3: self.trainingFinished() self.movie.stop() self.loader.clear() def connectData(self): connected = {} characters = ["'", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '*', '+', '#'] if self.user is None: self.user = {} if self.base is None: self.base = {} for char in characters: if char in self.base and char in self.user: connected[char] = self.base[char]+self.user[char] elif char in self.base: connected[char] = self.base[char] elif char in self.user: connected[char] = self.user[char] return connected def getRandomData(self, data, characters): self.testsamples = {} samples = 30 for char in characters: amount = len(data[char])/400 if amount > samples: picks = random.sample(range(amount), samples) else: picks = random.sample(range(amount), amount) temp = bitarray() for pick in picks: temp += data[char][pick*400:pick*400+400] self.testsamples[char] = temp return self.testsamples def saveImgData(self): characters = ["'", ',', '-', '&', '[', ']', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '*', '+', '#'] if self.user is None: self.user = {} for word in self.words: for letter in word: if letter[1] in characters: data = bitarray() image = cv2.resize(letter[0], (20, 20)) ret,image = cv2.threshold(image,250,255,cv2.THRESH_BINARY) for row in image: for cell in row: if cell == 255: data.append(True) else: data.append(False) if letter[1] in self.user: self.user[letter[1]] += data else: self.user[letter[1]] = data path = self.settings.storage_path+os.sep+"user_training_data.pck" file = gzip.GzipFile(path, 'wb') pickle.dump(self.user, file,-1) file.close() self.save_button.setEnabled(False) self.train_button.setEnabled(True) def changeText(self, index): #print index self.words[self.current][index][1] = unicode(self.ledits[index].text()) def getBaseData(self): text = "" keys = [] for key in self.base: keys.append(key) keys.sort() for key in keys: text += key + ": " + str(len(self.base[key])/400)+", " #print keys return text def getUserData(self): text = "" keys = [] for key in self.user: keys.append(key) keys.sort() for key in keys: text += key + ": " + str(len(self.user[key])/400)+", " return text def loadBase(self): try: path = self.settings.app_path+os.sep+"trainingdata"+os.sep+"base_training_data.pck" file = gzip.GzipFile(path, 'rb') letters = pickle.load(file) file.close() return letters except: return None def loadUser(self): try: path = self.settings.storage_path+os.sep+"user_training_data.pck" file = gzip.GzipFile(path, 'rb') letters = pickle.load(file) file.close() return letters except: return None def removeFile(self): item = self.file_list.currentItem() self.file_list.takeItem(self.file_list.currentRow()) del item def AddFiles(self): if self.settings["native_dialog"]: files = QFileDialog.getOpenFileNames(self, "Open", self.settings['screenshot_dir']) else: files = QFileDialog.getOpenFileNames(self, "Open", self.settings['screenshot_dir'], options = QFileDialog.DontUseNativeDialog) if files == []: return first_item = None counter = 0 for file in files: file1 = unicode(file).encode(sys.getfilesystemencoding()) item = CustomQListWidgetItem(split(file1)[1], file1, self.settings) if first_item == None: first_item = item self.file_list.addItem(item) counter+=1 """ def resizeElements(self): fields = self.input_fields for field in fields: field.setMinimumSize(QSize(0, self.settings['input_size'])) field.setMaximumSize(QSize(16777215, self.settings['input_size'])) canvases = self.img_fields for canvas in canvases: canvas.setMinimumSize(QSize(0, self.settings['snippet_size'])) canvas.setMaximumSize(QSize(16777215, self.settings['snippet_size'])) """ def runOCR(self): self.add_files_button.setEnabled(False) self.remove_file_button.setEnabled(False) self.ocr_button.setEnabled(False) self.file_list.setEnabled(False) self.repaint() self.current_image = 0 self.results = [] self.images = [] self.prev = [] self.marketoffset = [] self.stationoffset = [] files = self.file_list.count() for i in xrange(files): self.file_list.setCurrentRow(i) item = self.file_list.currentItem() color_image = item.loadColorImage() preview_image = item.addTestImage(color_image) self.images.append(color_image) self.prev.append(preview_image) #cv2.imshow("x", color_image) #cv2.waitKey(0) # #images.append(preview_image) #self.setPreviewImage(preview_image) #return self.stationoffset.append(item.ocr_areas.station_name) self.marketoffset.append(item.ocr_areas.market_table) current_result = OCR(color_image, item.ocr_areas, self.settings["ocr_language"], item, levels = False, levenshtein = False) self.results.append(current_result) self.allBoxes() #print len(self.words) #print self.words[1] self.next_button.setEnabled(True) self.prev_button.setEnabled(False) self.showSet() self.notifier.setText("You did not check every word yet.") def showSet(self): #self.snippet_preview bound = self.boundaries[self.current] #print self.current #print bound[1] image = self.images[bound[0]][bound[1][1]-2:bound[1][3]+3,bound[1][0]-2:bound[1][2]+2] self.drawSnippet(self.snippet_preview, image) for gview in self.gviews: self.grid.removeWidget(gview) gview.deleteLater() gview = None for ledit in self.ledits: self.grid.removeWidget(ledit) ledit.deleteLater() ledit = None self.gviews = [] self.ledits = [] letters = len(self.words[self.current]) for i in range(letters): gview = QGraphicsView() self.grid.addWidget(gview,0,i) self.gviews.append(gview) gview.setMaximumSize(50, self.settings['snippet_size']) gview.setVerticalScrollBarPolicy(1) gview.setHorizontalScrollBarPolicy(1) self.drawSnippet(gview, self.words[self.current][i][0]) ledit = QLineEdit() self.grid.addWidget(ledit,1,i) self.ledits.append(ledit) ledit.setMaximumSize(50, self.settings['input_size']) ledit.setAlignment(Qt.AlignHCenter) ledit.setText(self.words[self.current][i][1]) for index,item in zip(range(50), self.ledits): item.textEdited.connect(partial(self.changeText, index)) self.repaint() """ pictures = len(self.img_fields) if pictures < len(self.imglist)-((self.current-1)*20): for i in range(20): if len(self.imglist) > (self.current*20)+i: self.drawSnippet(self.img_fields[i], self.imglist[(self.current*20)+i]) self.input_fields[i].setText(self.charlist[(self.current*20)+i]) else: self.cleanSnippet(self.img_fields[i]) self.input_fields[i].setText("") self.wizardPage2.fullfilled = True self.wizardPage2.completeChanged.emit() """ def previousWord(self): if self.current > 0: self.current -= 1 self.showSet() self.next_button.setEnabled(True) if self.current == 0: self.prev_button.setEnabled(False) else: self.prev_button.setEnabled(True) def nextWord(self): #print self.maxcount if self.current < self.wordcount-1: self.current += 1 self.showSet() self.prev_button.setEnabled(True) if self.current == self.wordcount-1: self.next_button.setEnabled(False) self.notifier.setText("You checked every word now. If you corrected every letter continue to next page.") else: self.next_button.setEnabled(True) def cleanSnippet(self, graphicsview): scene = QGraphicsScene() graphicsview.setScene(scene) def drawOCRPreview(self): factor = 1.0 img = self.prev[0] old_h = img.height() old_w = img.width() pix = img.scaled(QSize(self.preview.size().width()*factor,self.preview.size().height()*factor), Qt.KeepAspectRatio, Qt.SmoothTransformation) #pix = img.scaled(self.preview.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) new_h = pix.height() new_w = pix.width() self.ratio_h = old_h/float(new_h) self.ratio_w = old_w/float(new_w) self.scene = QGraphicsScene() self.scene.addPixmap(pix) #self.scene.addPixmap(img) self.previewRects = [] pen = QPen(Qt.yellow) redpen = QPen(Qt.red) bluepen = QPen(Qt.blue) greenpen = QPen(Qt.green) #for box in self.boxes(): # rect = self.addRect(self.scene, box, ratio_w, ratio_h, pen) # self.previewRects.append(rect) rect = self.addRect(self.scene, self.boxlist[0], self.ratio_w, self.ratio_h, pen) self.previewRects.append(rect) self.previewSetScene(self.scene) def drawSnippet(self, graphicsview, snippet): """Draw single result item to graphicsview""" try: h, w = snippet.shape except: h, w, c = snippet.shape if h < 1 or w <1: return processedimage = array2qimage(snippet) pix = QPixmap() pix.convertFromImage(processedimage) pix = pix.scaled(graphicsview.width(), graphicsview.height()-1, Qt.KeepAspectRatio, Qt.SmoothTransformation) scene = QGraphicsScene() scene.addPixmap(pix) graphicsview.setScene(scene) graphicsview.show() def addRect(self, scene, item, ratio_w, ratio_h, pen): """Adds a rectangle to scene and returns it.""" rect = scene.addRect((item[0])/ratio_w , (item[2])/ratio_h, item[1]/ratio_w, item[3]/ratio_h, pen) return rect def allBoxes(self): for i in range(self.file_list.count()): self.file_list.setCurrentRow(i) current = self.file_list.currentItem() res = self.results[i].station.name cres = self.results[i] self.charlist += list(res.value.replace(" ", "").upper()) text = res.value.replace(" ", "") imgcount = len(self.results[i].station.name.units) charcount = len(text) word = [] for j in range(imgcount): if j < charcount: char = text[j] else: char = "" unit = self.results[i].station.name.units[j] image = cres.station_img[unit[2]:unit[3]+1,unit[0]:unit[1]] #cv2.imshow("x", image) #cv2.waitKey(0) h = res.h if len(image) > 0: if ((h*1.0)/len(image[0])) > 3: y1 = res.y1 if y1 < 0: y1 = 0 image = cres.station_img[y1:unit[3], unit[0]:unit[1]] border = (h - len(image[0]))/2 image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255)) if len(image) < h/2.0: y1 = res.y1 if y1 < 0: y1 = 0 image = cres.station_img[y1:res.y2, unit[0]:unit[1]] border = (h - len(image[0]))/2 image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255)) th, tw = image.shape if th < 1 or tw < 1: image = np.ones((10,10,1), dtype=np.uint8) * 255 self.imglist.append(image) word.append([image, char]) self.words.append(word) self.boundaries.append([i, [res.box[0]+self.stationoffset[i][0][0], res.box[1]+self.stationoffset[i][0][1], res.box[2]+self.stationoffset[i][0][0], res.box[3]+self.stationoffset[i][0][1]]]) for line in self.results[i].commodities: for item in line.items: if not item is None: text = item.value.replace(" ", "") imgcount = len(item.units) charcount = len(text) word = [] self.charlist += list(item.value.replace(" ", "").upper()) for j in range(imgcount): if j < charcount: char = text[j] else: char = "" unit = item.units[j] self.boxlist.append([unit[0]+current.market_offset[0],unit[1]-unit[0], unit[2]+current.market_offset[1],unit[3]-unit[2]]) image = cres.commodities_img[unit[2]:unit[3]+1,unit[0]:unit[1]] h = line.h if len(image) > 0: if ((h*1.0)/len(image[0])) > 3: y1 = line.y1 if line.y1 >= 0 else 0 if y1 < 0: y1 = 0 image = cres.commodities_img[y1:unit[3], unit[0]:unit[1]] if image.shape[0] > 0 and image.shape[1] > 0: border = (h - len(image[0]))/2 image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255)) if len(image) < h/2.0: y1 = line.y1 if line.y1 >= 0 else 0 if y1 < 0: y1 = 0 image = cres.commodities_img[y1:line.y2, unit[0]:unit[1]] if image.shape[0] > 0 and image.shape[1] > 0: border = (h - len(image[0]))/2 image = cv2.copyMakeBorder(image,0,0,border,border,cv2.BORDER_CONSTANT,value=(255,255,255)) th, tw = image.shape if th < 1 or tw < 1: image = np.ones((10,10,1), dtype=np.uint8) * 255 self.imglist.append(image) word.append([image, char]) self.words.append(word) self.boundaries.append([i, [item.box[0]+self.marketoffset[i][0][0], item.box[1]+self.marketoffset[i][0][1], item.box[2]+self.marketoffset[i][0][0], item.box[3]+self.marketoffset[i][0][1]]]) self.wordcount = len(self.words) #self.maxcount = len(self.imglist)/20 def setPreviewImage(self, image): """Show image in self.preview.""" #factor = self.factor.value() factor = 1.0 pix = image.scaled(QSize(self.preview.size().width()*factor,self.preview.size().height()*factor), Qt.KeepAspectRatio, Qt.SmoothTransformation) scene = QGraphicsScene() scene.addPixmap(pix) self.previewSetScene(scene) def previewSetScene(self, scene): """Shows scene in preview""" self.preview.setScene(scene) self.preview.show()