Here are the examples of the python api PyQt4.QtGui.QApplication.processEvents taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
64 Examples
3
Example 1
def cleanUp(self):
QApplication.processEvents()
for scene in self._imageViews:
scene.close()
scene.deleteLater()
self._imageViews = []
QApplication.processEvents()
3
Example 2
def button_release(self, event):
""" Button press """
nmode = self.axes.get_navigate_mode()
if event.button == 1:
self.press = False
if nmode == 'ZOOM':
extent = self.axes.get_xbound()
self.paxes.set_xbound(extent[0], extent[1])
self.figure.canvas.draw()
QtGui.QApplication.processEvents()
self.slide_grid(self.mdata)
QtGui.QApplication.processEvents()
else:
self.myparent.update_model()
3
Example 3
def timerEvent(self, event):
if not self.exportloop is None:
try:
QApplication.processEvents()
# if not canceled, process next image in export loop
next(self.exportloop)
except StopIteration:
# if loop finished, call cancel to wrap up the process
self.cancel()
3
Example 4
Project: QuickOSM Source File: QuickOSMWidget.py
def end_process(self):
"""
Make some stuff after the process
"""
self.pushButton_runQuery.setDisabled(False)
self.pushButton_runQuery.setText(self.pushButton_runQuery.initialText)
self.progressBar_execution.setMinimum(0)
self.progressBar_execution.setMaximum(100)
self.progressBar_execution.setValue(100)
QApplication.processEvents()
3
Example 5
def update_pos(self,pos):
if pos>4 and pos<self.s_width/3+100:
self.pos_x=pos
self.setGeometry(0,self.top_pos,self.pos_x+self.SIZE/2+5,self.s_height)
self.update()
QtGui.QApplication.processEvents()
3
Example 6
Project: QuickOSM Source File: QuickOSMWidget.py
def set_progress_percentage(self, percent):
"""
Slot to update percentage during process
"""
self.progressBar_execution.setValue(percent)
QApplication.processEvents()
3
Example 7
Project: pygmi Source File: main.py
def showprocesslog(self, txt, replacelast=False):
"""
Show text on the process log.
Parameters
----------
txt : str
Message to be displayed in the process log
replacelast : bool, optional
flag to indicate whether the last row on the log should be
overwritten.
"""
self.showtext(self.textbrowser_processlog, txt, replacelast)
QtGui.QApplication.processEvents()
3
Example 8
Project: volumina Source File: quadsplitter.py
def on_max(self, dockWidget):
dockWidget.setVisible(True)
for dock in self.dockableContainer:
if not dockWidget == dock:
dock.setVisible(False)
# Force sizes to be updated now
QApplication.processEvents()
# On linux, the vertical splitter doesn't seem to refresh unless we do so manually
# Presumably, this is a QT bug.
self.splitVertical.refresh()
# Viewport doesn't update automatically...
view = dockWidget.graphicsView
view.viewport().setGeometry( view.rect() )
3
Example 9
def settings(self):
""" run """
if self.nofps:
self.parent.showprocesslog('Error: no Fault Plane Solutions')
return False
self.show()
QtGui.QApplication.processEvents()
self.mmc.init_graph()
3
Example 10
def wheelEvent(self,e):
#Window.activateFakewin(self.fakewin.winId())
if self.activity == 'apps':
value= int(e.delta()/120)
max_pages=math.trunc((len(self.allApps)-1)/self.apps_per_page)
if value>0 and self.app_page_state>0:
self.app_page_state-=1
if value<0 and self.app_page_state<max_pages:
self.app_page_state+=1
self.update()
self.repaint()
QtGui.QApplication.processEvents()
3
Example 11
Project: python-gphoto2 Source File: focus-gui.py
@QtCore.pyqtSlot(QtCore.QPoint)
def toggle_zoom(self, pos):
self.zoomed = not self.zoomed
self._draw_image()
if self.zoomed:
QtGui.QApplication.processEvents()
size = self.image_display.viewport().size()
for bar, value in ((self.image_display.horizontalScrollBar(),
float(pos.x()) / float(size.width())),
(self.image_display.verticalScrollBar(),
float(pos.y()) / float(size.height()))):
min_val = bar.minimum()
max_val = bar.maximum()
step = bar.pageStep()
visible = float(step) / float(step + max_val - min_val)
if visible >= 0.99:
continue
value = (value - (visible/ 2.0)) / (1.0 - visible)
bar.setValue(min_val + ((max_val - min_val) * value))
3
Example 12
def updateProgress(self, minimum, maximum, current):
if current == maximum:
self.progressBar.reset()
else:
self.progressBar.setMinimum( minimum )
self.progressBar.setMaximum( maximum )
self.progressBar.setValue( current )
QtGui.QApplication.processEvents()
3
Example 13
Project: python-whiteboard Source File: pywhiteboard.py
def showHideSettings(self):
self.ui.confContainer.setVisible(not self.ui.confContainer.isVisible())
QtGui.QApplication.processEvents()
if self.ui.confContainer.isVisible():
self.ui.pushButtonSettings.setText(self.tr('Hide settings'))
# Res¡ze to max
self.resize(1000,1000)
else:
self.ui.pushButtonSettings.setText(self.tr('Show settings'))
self.adjustSize()
3
Example 14
def set_progress_text(self, text):
"""
Slot to update text during process
"""
self.label_progress.setText(text)
QApplication.processEvents()
3
Example 15
def slide_plot(self, xdat, dat, xdat2, dat2):
""" Slider """
self.figure.canvas.restore_region(self.pbbox)
self.cal[0].set_data([xdat, dat])
if xdat2 is not None:
self.obs[0].set_data([xdat2, dat2])
else:
self.obs[0].set_data([[], []])
self.paxes.draw_artist(self.cal[0])
if xdat2 is not None:
self.paxes.draw_artist(self.obs[0])
self.figure.canvas.update()
QtGui.QApplication.processEvents()
3
Example 16
Project: launcher Source File: Main.py
def open_pl_rect(self):
self.pl_rect_pos=0
while self.pl_rect_pos<(self.s_width/3):
self.pl_rect_pos+=int(self.conf["animation-speed"])*2
self.repaint()
QtGui.QApplication.processEvents()
self.pl_rect_pos=self.s_width/3+2
self.update()
3
Example 17
Project: volumina Source File: quadsplitter.py
def on_min(self, dockWidget):
for dock in self.dockableContainer:
dock.setVisible(True)
# Force sizes to be updated now
QApplication.processEvents()
self._resizeEqual()
# Viewports don't update automatically...
for dock in self.dockableContainer:
view = dock.graphicsView
if hasattr(view, 'viewport'):
view.viewport().setGeometry( view.rect() )
3
Example 18
Project: pygmi Source File: misc.py
def incrmain(self, i=1):
""" increases value by one """
self.mvalue += i
self.pbarmain.setValue(self.mvalue)
n = self.mvalue
total = self.mmax
tleft = (total-n)*(time.clock()-self.mtime)/n
if tleft > 60:
tleft = int(tleft // 60)
self.pbarmain.setFormat('%p% '+str(tleft)+'min left')
else:
tleft = int(tleft)
self.pbarmain.setFormat('%p% '+str(tleft)+'s left')
QtGui.QApplication.processEvents()
3
Example 19
Project: pygmi Source File: tiltdepth.py
def change_band1(self):
"""
Action which occurs when button is pressed. Combo box to change
the first band.
"""
txt = str(self.cbox_band1.currentText())
self.btn_apply.setText('Calculating...')
QtGui.QApplication.processEvents()
self.btn_apply.setEnabled(False)
for i in self.indata['Raster']:
if i.dataid == txt:
self.tiltdepth(i)
self.change_cbar()
self.btn_apply.setEnabled(True)
self.btn_apply.setText('Calculate Tilt Depth')
QtGui.QApplication.processEvents()
3
Example 20
Project: pygmi Source File: misc.py
def to_max(self):
""" Sets the progress to maximum """
self.setMaximum(1)
self.setMinimum(0)
self.setValue(1)
QtGui.QApplication.processEvents()
3
Example 21
@image.setter
def image(self, value):
if isinstance(value, list) or isinstance(value, tuple):
self._videoWidget.paint(value)
else:
self._videoWidget.paint([value])
QApplication.processEvents()
3
Example 22
Project: pygmi Source File: tab_ddisp.py
def combo2(self):
""" Combo box to choose grid 2 """
self.mpl_toolbar.home()
ctxt = str(self.combo_grid2.currentText())
reg = 0
if ctxt == 'Calculated Gravity':
reg = self.lmod1.gregional
self.grid2txt = ctxt
self.grid2 = self.lmod1.griddata[ctxt]
self.mmc.init_grid2(self.grid2, reg, ctxt)
# Needed to force the drawing of colorbar
QtGui.QApplication.processEvents()
self.hs_grid()
3
Example 23
def draw_callback(self):
""" Draw callback """
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
QtGui.QApplication.processEvents()
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
# self.canvas.blit(self.ax.bbox)
self.canvas.update()
3
Example 24
Project: VisTrails Source File: source_configure.py
def portTableResize(self, logicalIndex, oldSize, newSize):
self.performPortConnection(self.disconnect)
if self.inputPortTable.horizontalHeader().sectionSize(logicalIndex)!=newSize:
self.inputPortTable.horizontalHeader().resizeSection(logicalIndex,newSize)
if self.outputPortTable.horizontalHeader().sectionSize(logicalIndex)!=newSize:
self.outputPortTable.horizontalHeader().resizeSection(logicalIndex,newSize)
QtGui.QApplication.processEvents()
self.performPortConnection(self.connect)
3
Example 25
Project: brickv Source File: mainwindow.py
def connect_clicked(self):
if self.ipcon.get_connection_state() == IPConnection.CONNECTION_STATE_DISCONNECTED:
try:
self.last_host = self.combo_host.currentText()
self.button_connect.setDisabled(True)
self.button_connect.setText("Connecting ...")
self.button_connect.repaint()
QApplication.processEvents()
self.ipcon.connect(self.last_host, self.spinbox_port.value())
except:
self.button_connect.setDisabled(False)
self.button_connect.setText("Connect")
QMessageBox.critical(self, 'Connection',
'Could not connect. Please check host, check ' +
'port and ensure that Brick Daemon is running.')
else:
self.do_disconnect()
3
Example 26
def calibrate_clicked(self):
self.status_label.setText('Status: Calibrating...')
self.status_label.repaint()
QApplication.processEvents()
self.ps.calibrate()
self.status_label.setText('Status: New calibration stored in EEPROM')
0
Example 27
Project: brickv Source File: program_info_files.py
def expand_walk_to_model(walk, model, folder_icon, file_icon):
def create_last_modified_item(last_modified):
item = QStandardItem(QDateTime.fromTime_t(last_modified).toString('yyyy-MM-dd HH:mm:ss'))
item.setData(last_modified, USER_ROLE_LAST_MODIFIED)
return item
def expand(parent_item, name, dw):
QApplication.processEvents()
if 'c' in dw:
if name == None:
name_item = parent_item
size_item = None
else:
name_item = QStandardItem(name)
name_item.setData(folder_icon, Qt.DecorationRole)
name_item.setData(ITEM_TYPE_DIRECTORY, USER_ROLE_ITEM_TYPE)
name_item.setData(int(dw['p']), USER_ROLE_PERMISSIONS)
size_item = QStandardItem('')
last_modified_item = create_last_modified_item(int(dw['l']))
parent_item.appendRow([name_item, size_item, last_modified_item])
size = 0
for child_name, child_dw in dw['c'].iteritems():
size += expand(name_item, child_name, child_dw)
if size_item != None:
size_item.setText(get_file_display_size(size))
size_item.setData(size, USER_ROLE_SIZE)
return size
else:
name_item = QStandardItem(name)
name_item.setData(file_icon, Qt.DecorationRole)
name_item.setData(ITEM_TYPE_FILE, USER_ROLE_ITEM_TYPE)
name_item.setData(int(dw['p']), USER_ROLE_PERMISSIONS)
size = int(dw['s'])
size_item = QStandardItem(get_file_display_size(size))
size_item.setData(size, USER_ROLE_SIZE)
last_modified_item = create_last_modified_item(int(dw['l']))
parent_item.appendRow([name_item, size_item, last_modified_item])
return size
expand(model.invisibleRootItem(), None, walk)
return model
0
Example 28
Project: QuickOSM Source File: process.py
def process_query(
dialog=None,
query=None,
nominatim=None,
bbox=None,
output_dir=None,
prefix_file=None,
output_geometry_types=None,
layer_name="OsmQuery",
white_list_values=None,
config_outputs=None):
"""execute a query and send the result file to open_file."""
# Check OGR
if not is_ogr_version_ok():
raise GDALVersion
if not is_osm_driver_enabled():
raise OsmDriverNotFound
# Get output's format
output_format = get_setting('outputFormat')
# Prepare outputs
dialog.set_progress_text(tr("QuickOSM", u"Prepare outputs"))
# Replace Nominatim or BBOX
query = prepare_query(query=query, nominatim_name=nominatim, extent=bbox)
# Getting the default overpass api and running the query
server = get_setting('defaultOAPI')
dialog.set_progress_text(tr("QuickOSM", u"Downloading data from Overpass"))
QApplication.processEvents()
connexion_overpass_api = ConnexionOAPI(url=server, output="xml")
osm_file = connexion_overpass_api.get_file_from_query(query)
return open_file(
dialog=dialog,
osm_file=osm_file,
output_geom_types=output_geometry_types,
white_list_column=white_list_values,
layer_name=layer_name,
output_format=output_format,
output_dir=output_dir,
prefix_file=prefix_file,
config_outputs=config_outputs)
0
Example 29
Project: launcher Source File: Main.py
def close_it(self):
if self.plugin==True:
self.webview.hide()
self.close_pl_rect()
self.plugin=False
self.font_color=(int(self.conf['font-r']),int(self.conf['font-g']),int(self.conf['font-b']))
self.fg_color=(int(self.conf['r']),int(self.conf['g']),int(self.conf['b']))
while self.pos_x>self.HALF_OPEN_POS:
#old_pos=self.pos_x
if self.pos_x<self.s_width/10:
self.pos_x-=float(self.conf["animation-speed"])/4
else:
if self.pos_x>self.s_width/4:
self.pos_x=self.s_width/4
else:
self.pos_x-=float(self.conf["animation-speed"])
self.current_state="nothing"
self.repaint()
QtGui.QApplication.processEvents()
if self.pos_x!=self.HALF_OPEN_POS-2:
self.pos_x=self.HALF_OPEN_POS-2
self.current_state="half_open"
self.setAttribute(QtCore.Qt.WA_X11NetWmWindowTypeDock,True)
self.setGeometry(0,self.top_pos,self.pos_x+self.SIZE/2+3,self.s_height)
self.update()
QtGui.QApplication.processEvents()
0
Example 30
Project: brickv Source File: program_info_logs.py
def refresh_logs(self):
def cb_program_logs_list(result):
okay, message = check_script_result(result, decode_stderr=True)
if not okay:
self.label_error.setText('<b>Error:</b> ' + Qt.escape(message))
self.label_error.setVisible(True)
self.refresh_logs_done()
return
try:
# FIXME: do decompress in an async_call
program_logs_list = json.loads(zlib.decompress(buffer(result.stdout)).decode('utf-8'))
except:
program_logs_list = None
if program_logs_list == None or not isinstance(program_logs_list, dict):
self.label_error.setText('<b>Error:</b> Received invalid data')
self.label_error.setVisible(True)
self.refresh_logs_done()
return
self.label_error.setVisible(False)
def create_file_size_item(size):
item = QStandardItem(get_file_display_size(size))
item.setData(size, USER_ROLE_SIZE)
return item
def update_file_size_item(item, additional_size):
current_size = item.data(USER_ROLE_SIZE)
new_size = current_size + additional_size
item.setText(get_file_display_size(new_size))
item.setData(new_size, USER_ROLE_SIZE)
continuous_row = None
date_rows = {}
time_rows = {}
for file_name, file_size in program_logs_list.iteritems():
QApplication.processEvents()
file_name_parts = file_name.split('_')
if file_name_parts[0] == "continuous":
if len(file_name_parts) != 2:
continue
if continuous_row == None:
continuous_item = QStandardItem("Continuous")
continuous_item.setData(ITEM_TYPE_PARENT_CONT, USER_ROLE_ITEM_TYPE)
continuous_row = [continuous_item, create_file_size_item(0)]
self.tree_logs_model.appendRow(continuous_row)
log_item = QStandardItem(file_name_parts[1])
log_item.setData(self.file_icon, Qt.DecorationRole)
log_item.setData(file_name, USER_ROLE_FILE_NAME)
log_item.setData(ITEM_TYPE_LOG_FILE_CONT, USER_ROLE_ITEM_TYPE)
continuous_row[0].appendRow([log_item, create_file_size_item(file_size)])
update_file_size_item(continuous_row[1], file_size)
else:
if len(file_name_parts) != 3:
continue
try:
timestamp = int(file_name_parts[1].split('+')[0]) / 1000000
except ValueError:
continue
date = QDateTime.fromTime_t(timestamp).toString('yyyy-MM-dd')
time = QDateTime.fromTime_t(timestamp).toString('HH:mm:ss')
date_time = date + 'T' + time
if date in date_rows:
date_row = date_rows[date]
else:
date_item = QStandardItem(date)
date_item.setData(ITEM_TYPE_PARENT_DATE, USER_ROLE_ITEM_TYPE)
date_row = [date_item, create_file_size_item(0)]
date_rows[date] = date_row
self.tree_logs_model.appendRow(date_row)
if date_time in time_rows:
time_row = time_rows[date_time]
else:
time_item = QStandardItem(time)
time_item.setData(ITEM_TYPE_PARENT_TIME, USER_ROLE_ITEM_TYPE)
time_row = [time_item, create_file_size_item(0)]
time_rows[date_time] = time_row
date_row[0].appendRow(time_row)
log_item = QStandardItem(file_name_parts[2])
log_item.setData(self.file_icon, Qt.DecorationRole)
log_item.setData(file_name, USER_ROLE_FILE_NAME)
log_item.setData(ITEM_TYPE_LOG_FILE, USER_ROLE_ITEM_TYPE)
time_row[0].appendRow([log_item, create_file_size_item(file_size)])
update_file_size_item(time_row[1], file_size)
update_file_size_item(date_row[1], file_size)
self.tree_logs.header().setSortIndicator(0, Qt.DescendingOrder)
self.refresh_logs_done()
self.refresh_in_progress = True
self.update_main_ui_state()
width = self.tree_logs.columnWidth(0)
self.tree_logs_model.clear()
self.tree_logs_model.setHorizontalHeaderLabels(self.tree_logs_model_header)
self.tree_logs.setColumnWidth(0, width)
self.script_manager.execute_script('program_logs_list', cb_program_logs_list,
[self.log_directory], max_length=1024*1024,
decode_output_as_utf8=False)
0
Example 31
Project: launcher Source File: Main.py
def mouseReleaseEvent(self,e):
x_m,y_m = e.x(),e.y()
self.drawAppRect=False
Window.activateFakewin(self.fakewin.winId())
#While moving
''''
if self.current_state=="nothing":
if self.plugin==False:
self.webview.hide()
self.move=False
###sets position to right one
pos_list = [self.HALF_OPEN_POS, self.s_width/3]
closest = min(pos_list, key=lambda x: abs(x-self.pos_x))
if closest<self.pos_x:
while closest<self.pos_x:
self.pos_x-=5
self.setGeometry(0,self.top_pos,self.pos_x+9,self.s_height)
QtGui.QApplication.processEvents()
self.update()
self.pos_x=closest
QtGui.QApplication.processEvents()
self.update()
elif closest>self.pos_x:
while closest>self.pos_x:
self.pos_x+=5
self.setGeometry(0,self.top_pos,self.pos_x+9,self.s_height)
QtGui.QApplication.processEvents()
self.update()
self.pos_x=closest
QtGui.QApplication.processEvents()
self.update()
##set the current state
if self.pos_x==self.HALF_OPEN_POS:
self.pos_x-=3
#self.dock_apps = Apps.find_info(self.conf['dock-apps'])
self.current_state="half_open"
elif self.pos_x==self.s_width/3:
self.pos_x-=3
self.current_state="open"
else: self.current_state="nothing"
if self.plugin==True and self.current_state=='open' and self.activity=='apps':
self.webview.show()
if self.plugin==False and self.current_state=='open' and self.activity=='apps':
self.current_text=""
#self.initApps()
'''
#Events
#
if self.current_state=="open":
if self.pos_x-14<x_m<self.pos_x and self.move==False and e.button()==QtCore.Qt.LeftButton:
self.close_it()
if y_m>self.s_height-13:
print("[Duck Launcher] Saving configuration.")
c = Config.check_dict(self.conf)
QtGui.QApplication.processEvents()
print("[Duck Launcher] Quitting, Good Bye!")
QtGui.qApp.quit()
###app events
if self.activity == "apps" and self.plugin==False:
max_apps= math.trunc((len(self.allApps)-1)/self.apps_per_page)+1
minus = math.trunc(len(self.allApps)/self.apps_per_page)*15/2
##Change Page
for i in range(0,max_apps):
btn_size = 15
x_pos = self.s_width/6-btn_size+(btn_size*i)-minus
if x_pos<x_m<x_pos+btn_size and 12<y_m<btn_size+12:
self.app_page_state=i
self.update()
QtGui.QApplication.processEvents()
for i, app in enumerate(self.allApps):
app_page = math.trunc(i/self.apps_per_page)
if app_page==self.app_page_state:
row_pos = math.trunc(i/self.apps_per_row)
page_row_pos=row_pos-(self.apps_per_page/self.apps_per_row*app_page)
col_pos=(i-(row_pos*self.apps_per_row))
x_pos = self.ICON_SIZE*col_pos+30+col_pos*10
y_pos = page_row_pos*self.ICON_SIZE+45+page_row_pos*10
if x_pos<x_m<x_pos+int(self.conf["icon-size"]) and y_pos<y_m<y_pos+int(self.conf["icon-size"]):
if e.button()==QtCore.Qt.LeftButton:
print("[Duck Launcher] Launching '{0}' with '{1}'".format(app["name"],app["exec"]) )
thread = Widgets.Launch(parent=self)
thread.app=app["exec"]
thread.start()
self.close_it()
elif self.activity=="star":
blocks=pickle.loads(Config.get()["blocks"])
all_rows=0
apps_per_row = math.trunc(((self.s_width/3)-30)/int(self.conf["icon-size"]))
for i,b in enumerate(blocks):
all_stuff = Config.get_from_block(b)
if len(all_stuff)!=apps_per_row:
row_num = math.trunc(len(all_stuff)/apps_per_row)+1
else:
row_num = math.trunc(len(all_stuff)/apps_per_row)
h=int(self.conf["icon-size"])*all_rows+i*50
all_rows+=row_num
for j, thing in enumerate(all_stuff):
row_pos = math.trunc(j/apps_per_row)
x_pos = int(self.conf["icon-size"])*(j-(row_pos*apps_per_row))+40
y_pos = (row_pos*int(self.conf["icon-size"])+20)+h+30
if x_pos-10<x_m<x_pos-10+int(self.conf["icon-size"]) and y_pos<y_m<y_pos+int(self.conf["icon-size"]) and x_m<self.pos_x-self.SIZE-3:
if e.button()==QtCore.Qt.LeftButton:
if thing['type']=='app':
the_exec=""
for a in Apps.info(''):
if thing['value'] in a['name']:
the_exec=a['exec']
thread = Widgets.Launch(parent=self)
thread.app=the_exec
thread.start()
print("[Duck Launcher] Launching '{0}' with '{1}'".format(thing["value"], the_exec) )
else:
import webbrowser
webbrowser.open(thing['value'])
elif self.current_state=="half_open":
##buttonsszd
if 0<x_m<self.HALF_OPEN_POS:
if e.button()==QtCore.Qt.LeftButton:
if y_m<self.ICO_TOP:
self.activity="apps"
self.current_text=''
self.open_it()
#self.allApps=Apps.info(self.current_text)
if self.ICO_TOP<y_m<self.ICO_TOP*2:
HOME=os.path.expanduser("~")
self.activity="apps"
self.current_text="#Files "
pl= Plugins.get(str(self.current_text))
html=pl.html(color=(self.conf["r"],self.conf["g"],self.conf["b"]),font=self.conf["font"])
if html!=None:
self.open_it()
self.plugin=True
self.pl_logo="/usr/share/duck-launcher/default-theme/file.svg"
self.fg_color=(40,40,40)
self.font_color=(255,255,255)
self.open_pl_rect()
self.webview.setHtml(html)
self.webview.show()
#self.webview.page().mainFrame().setFocus()
#self.webview.setFocus()
self.update()
if self.ICO_TOP*2<y_m<self.ICO_TOP*3:
self.activity="settings"
Settings(parent=self).start()
if self.ICO_TOP*3<y_m<self.ICO_TOP*4:
self.activity="star"
self.open_it()
if self.s_height-self.HALF_OPEN_POS-5<y_m:
if self.sys_win.isHidden():
#self.open_win.close()
self.sys_win.show()
elif self.sys_win.isHidden()==False:
self.sys_win.close()
for i,a in enumerate(self.dock_apps):
if self.OPEN_STATE_TOP+self.ICO_TOP*i+10<y_m<self.OPEN_STATE_TOP+self.ICO_TOP*(i+1)+10:
if e.button()==QtCore.Qt.LeftButton:
if a["name"] in [e["name"] for e in self.ow_in_dock]:
l=[e for e in self.ow_in_dock if e["name"]==a["name"]]
for k in l:
c = Window.changeWindowState(parent=self,win_info=k["info"])
c.start()
else:
print("[Duck Launcher] Launching '{0}' with '{1}'".format(a["name"], a["exec"]) )
thread = Widgets.Launch(parent=self)
thread.app=a["exec"]
thread.start()
self.dock_options_win.close()
elif e.button()==QtCore.Qt.RightButton:
#LaunchOption(y_pos, app_dict
if self.dock_options_win.isHidden() or self.dock_options_win.app["name"]!=a["name"]:
self.dock_options_win.update_all(self.conf)
self.dock_options_win.setTopPosition(self.OPEN_STATE_TOP+self.ICO_TOP*i+10)
self.dock_options_win.setApp(a)
self.dock_options_win.updateWidth()
self.dock_options_win.show()
else:
self.dock_options_win.close()
if len(self.open_windows)>0:
after_dapps = self.OPEN_STATE_TOP+len(self.dock_apps)*self.ICO_TOP+30
all_wins=[e["info"]["id"] for e in self.ow_in_dock]
ow_list=[o for o in self.open_windows if o["id"] not in all_wins]
for i,w in enumerate(ow_list):
y_pos=i*self.ICO_TOP+after_dapps-3
if y_pos<y_m<y_pos+self.ICO_TOP:
c = Window.changeWindowState(parent=self,win_info=w)
c.start()
self.update()
0
Example 32
Project: brickv Source File: program_page_files.py
def show_add_directory_dialog(self):
directory = get_existing_directory(get_main_window(), 'Add Directory', self.last_directory)
if len(directory) == 0:
return
self.last_directory = directory
if len(self.list_files.findItems(os.path.join(directory, '*'), Qt.MatchFixedString)) > 0:
return
uploads = []
progress = ExpandingProgressDialog(self)
progress.set_progress_text_visible(False)
progress.setWindowTitle('New Program')
progress.setLabelText(u"Collecting content of {0}".format(directory))
progress.setModal(True)
progress.setRange(0, 0)
progress.show()
for root, directories, files in os.walk(directory):
if progress.wasCanceled():
break
for filename in files:
source = os.path.join(root, filename)
target = QDir.fromNativeSeparators(os.path.relpath(source, directory))
uploads.append(Upload(source, target))
# ensure that the UI stays responsive
QApplication.processEvents()
if progress.wasCanceled():
break
if progress.wasCanceled():
return
progress.cancel()
# FIXME: maybe add a warning if the directory contains very many files or large amounts of data
item = QListWidgetItem(os.path.join(directory, '*'))
item.setData(Qt.UserRole, uploads)
item.setData(Qt.DecorationRole, self.folder_icon)
self.list_files.addItem(item)
self.completeChanged.emit()
0
Example 33
Project: volumina Source File: layerwidget_test.py
def impl(self):
try:
# Change the visibility of the *selected* layer
self.o2.visible = False
# Make sure the GUI is caught up on paint events
QApplication.processEvents()
# We must sleep for the screenshot to be right.
time.sleep(0.1)
self.w.repaint()
# Capture the window before we change anything
beforeImg = QPixmap.grabWindow( self.w.winId() ).toImage()
# Change the visibility of the *selected* layer
self.o2.visible = True
self.w.repaint()
# Make sure the GUI is caught up on paint events
QApplication.processEvents()
# We must sleep for the screenshot to be right.
time.sleep(0.1)
# Capture the window now that we've changed a layer.
afterImg = QPixmap.grabWindow( self.w.winId() ).toImage()
# Optional: Save the files so we can inspect them ourselves...
#beforeImg.save('before.png')
#afterImg.save('after.png')
# Before and after should NOT match.
assert beforeImg != afterImg
except:
# Catch all exceptions and print them
# We must finish so we can quit the app.
import traceback
traceback.print_exc()
TestLayerWidget.errors = True
qApp.quit()
0
Example 34
Project: brickv Source File: red_tab_program.py
def refresh_program_tree(self):
def refresh_async():
return get_programs(self.session)
def cb_success(programs):
sorted_programs = {}
for program in programs:
first_upload = program.cast_custom_option_value('first_upload', int, 0)
if first_upload in sorted_programs:
sorted_programs[first_upload][program.identifier] = program
else:
sorted_programs[first_upload] = {program.identifier: program}
for first_upload in sorted(sorted_programs.keys()):
for identifier in sorted(sorted_programs[first_upload].keys()):
self.add_program_to_tree(sorted_programs[first_upload][identifier])
self.refresh_in_progress = False
self.update_ui_state()
self.stacked_container.setCurrentIndex(1)
def cb_error():
pass # FIXME: report error
self.refresh_in_progress = True
self.update_ui_state()
self.tree_programs.clear()
QApplication.processEvents()
# move help widget to front so the other widgets wont show and update during removal
self.stacked_container.setCurrentWidget(self.widget_help)
while self.stacked_container.count() > 1:
self.stacked_container.removeWidget(self.stacked_container.widget(1))
QApplication.processEvents()
async_call(refresh_async, None, cb_success, cb_error)
0
Example 35
Project: launcher Source File: Main.py
def update_all(self,conf):
self.conf=conf
if self.HALF_OPEN_POS!=int(conf["size"]):
self.HALF_OPEN_POS=int(conf['size'])
self.current_state="half_open"
self.pos_x=int(conf["size"])
self.setGeometry(0,self.top_pos,self.HALF_OPEN_POS+6,self.s_height)
self.ICO_TOP=self.HALF_OPEN_POS-5
self.OPEN_STATE_TOP=self.ICO_TOP*4+5
elif self.ICON_SIZE!=int(conf['icon-size']):
self.ICON_SIZE=int(conf['icon-size'])
self.apps_per_row = math.trunc(((self.s_width/3)-30)/self.ICON_SIZE)
self.apps_per_col = math.trunc(((self.s_height)-30)/self.ICON_SIZE)
self.apps_per_page=self.apps_per_col*self.apps_per_row
if self.conf["blocks"]==None:
self.conf["blocks"]=[]
if self.conf["dock-apps"]==None:
self.conf["dock-apps"]=[]
self.dock_apps = Apps.find_info(self.conf['dock-apps'])
self.sys_win.update_all(conf)
self.dock_options_win.update_all(conf)
self.update()
QtGui.QApplication.processEvents()
0
Example 36
def update_progress(self, progress=1):
self._progress.value = self._processing_count
self._processing_count += progress
div = int(self._progress.max / 400)
if div == 0:
div = 1
if (self._processing_count % div) == 0:
self._processing_last_time = time.time()
total_passed_time = self._processing_last_time - \
self._processing_initial_time
remaining_time = (
(self._progress.max * total_passed_time) / self._processing_count) - total_passed_time
time_remaining = datetime(
1, 1, 1) + timedelta(seconds=remaining_time)
time_elapsed = datetime(
1, 1, 1) + timedelta(seconds=(total_passed_time))
values = (time_elapsed.day - 1, time_elapsed.hour, time_elapsed.minute, time_elapsed.second,
time_remaining.day -
1, time_remaining.hour, time_remaining.minute, time_remaining.second,
(float(self._processing_count) / float(self._progress.max)
) * 100.0, self._processing_count, self._progress.max,
self._processing_count / total_passed_time)
self._progress.label = "Elapsed: %d:%d:%d:%d; Remaining: %d:%d:%d:%d; Processed %0.2f %% (%d/%d); Cicles per second: %0.3f" % values
QtGui.QApplication.processEvents()
0
Example 37
Project: python-whiteboard Source File: pywhiteboard.py
def connectWii(self):
if self.connected:
self.disconnectDevice()
return
self.wii = Wiimote()
pBar = PBarDlg(self)
pBar.setModal( True )
pBar.show()
conf = Configuration()
selectedMac = conf.getValueStr("selectedmac")
pBar.reInit(selectedMac)
pool = []
while 1:
thread = self.wii.createConnectThread(selectedMac,pool)
thread.start()
while not thread.wait(30):
QtGui.QApplication.processEvents()
if pBar.cancelled == True:
if self.wii.isConnected():
self.wii.close()
self.wii = None
pBar.close()
return
if selectedMac == '*' and len(pool) >= 1:
if Configuration().getValueStr('nowaitdevices') == 'Yes':
selectedMac = pool[0]
else:
pBar.inform(self.tr('Found ') + str(len(pool)) + self.tr(' Devices. Press to Choose'))
if self.wii.isConnected():
self.connected = True
self.calibrated = False
self.active = False
self.updateButtons()
self.batteryLevel.setValue(self.wii.battery()*100)
self.pushButtonConnect.setText(self.tr("Disconnect"))
pBar.close()
self.confDialog.wii = self.wii
self.confDialog.checkButtons()
self.wii.disable()
self.wii.putCallbackBTN(self.makeBTNCallback())
self.wii.putCallbackIR(None)
self.wii.enable()
# Start calibration if configuration says so
conf = Configuration()
if conf.getValueStr("autocalibration") == "Yes":
if conf.getValueStr("automatrix") == "Yes":
self.calibrateWiiFromSettings()
else:
self.calibrateWiiScreen()
return
if self.wii.error:
self.wii = None
msgbox = QtGui.QMessageBox( self )
msgbox.setWindowTitle( self.tr('Error') )
msgbox.setText( self.tr("Error. Check your bluetooth driver") )
msgbox.setModal( True )
ret = msgbox.exec_()
pBar.close()
return
if pBar.choice:
if len(pool) == 1:
selectedMac = unicode(pool[0])
pBar.reInit(selectedMac)
else:
item, ok = QtGui.QInputDialog.getItem(self,
self.tr("Warning"), self.tr("Choose device"), pool, 0, False)
if ok:
selectedMac = unicode(item)
pBar.reInit(selectedMac)
else:
pBar.close()
return
0
Example 38
def mousePressEvent(self,e):
x_m,y_m=e.x(),e.y()
self.drawButtonRect=False
if 10<y_m<self.size+10:
if 20<x_m<self.size+20:
#sleep
self.buttonRect=QtCore.QRectF(15,0,self.size+10,self.size*1.5)
self.drawButtonRect=True
self.update()
QtGui.QApplication.processEvents()
if self.size*1.3+20<x_m<self.size*1.3+20+self.size:
self.buttonRect=QtCore.QRectF(self.size*1.3+15,0,self.size+10,self.size*1.5)
self.drawButtonRect=True
self.update()
QtGui.QApplication.processEvents()
if self.size*2*1.3+20<x_m<self.size*2*1.3+20+self.size:
self.buttonRect=QtCore.QRectF(self.size*2*1.3+15,0,self.size+10,self.size*1.5)
self.drawButtonRect=True
self.update()
QtGui.QApplication.processEvents()
if self.size*3*1.3+20<x_m<self.size*3*1.3+20+self.size:
self.buttonRect=QtCore.QRectF(self.size*3*1.3+15,0,self.size+10,self.size*1.5)
self.drawButtonRect=True
self.update()
QtGui.QApplication.processEvents()
0
Example 39
@value.setter
def value(self, value):
self._form.horizontalSlider.setValue( value )
QtGui.QApplication.processEvents()
0
Example 40
Project: VisTrails Source File: preferences.py
def test_remove_package(self):
""" Tests if the package really gets deleted, and that it gets
selected again in the available packages list.
"""
pkg = "URL"
_app = get_vistrails_application()
builder = _app.builderWindow
builder.showPreferences()
prefs = builder.preferencesDialog
packages = prefs._packages_tab
prefs._tab_widget.setCurrentWidget(packages)
QtGui.QApplication.processEvents()
# check if package is loaded
av = packages._available_packages_list
try:
item, = av.findItems(pkg, QtCore.Qt.MatchExactly)
av.setCurrentItem(item)
QtGui.QApplication.processEvents()
QtGui.QApplication.processEvents()
packages.enable_current_package()
except ValueError:
# Already enabled
pass
QtGui.QApplication.processEvents()
QtGui.QApplication.processEvents()
inst = packages._enabled_packages_list
item, = inst.findItems(pkg, QtCore.Qt.MatchExactly)
inst.setCurrentItem(item)
QtGui.QApplication.processEvents()
QtGui.QApplication.processEvents()
packages.disable_current_package()
QtGui.QApplication.processEvents()
QtGui.QApplication.processEvents()
# force delayed calls
packages.populate_lists()
packages.select_package_after_update_slot(pkg)
QtGui.QApplication.processEvents()
QtGui.QApplication.processEvents()
# This does not work because the selection is delayed
av = packages._available_packages_list
items = av.selectedItems()
self.assertEqual(len(items), 1, "No available items selected!")
self.assertEqual(items[0].text(), unicode(pkg),
"Wrong available item selected: %s" % items[0].text())
# check if configuration has been written correctly
startup = _app.startup
self.assertIn(pkg, startup.disabled_packages)
self.assertNotIn(pkg, startup.enabled_packages)
0
Example 41
Project: arkos-install Source File: Installer.py
def pkg_check(self):
# If package exists, check authenticity then skip download if necessary
pkg_loc = '/Users/'+os.getlogin()+'/Downloads/latest-rpi.tar.gz'
md5_loc = '/Users/'+os.getlogin()+'/Downloads/latest-rpi.tar.gz.md5.txt'
if os.path.exists(pkg_loc):
if os.path.islink(pkg_loc):
pkg_loc = os.path.realpath(pkg_loc)
self.parent.path = pkg_loc
self.dllabel.setText(_('Package found in working directory! '
'Checking authenticity...'))
QtGui.QApplication.processEvents()
if os.path.exists(md5_loc):
if os.path.islink(md5_loc):
md5_loc = os.path.realpath(md5_loc)
result = self.md5sum(pkg_loc, md5_loc)
if result == 0:
# the md5s were different. continue with download as is
self.dllabel.setText(_('Package found in working '
'directory, but MD5 check failed. Redownloading...'))
return 0
else:
# the md5s were the same! skip the download.
self.dllabel.setText(_('Authentic package found in '
'working directory. Skipping download...'))
return 1
else:
dl_md5 = urllib2.urlopen(
MIRRORS[self.parent.mirror]['url'] + 'latest-rpi.tar.gz.md5.txt')
md5_File = open('/Users/'+os.getlogin()+'/Downloads/latest-rpi.tar.gz.md5.txt', 'w')
md5_File.write(dl_md5.read())
md5_File.close()
result = self.md5sum(pkg_loc, md5_loc)
if result == 0:
# the md5s were different. gotta redownload the package
self.dllabel.setText(_('Package found in working '
'directory, but MD5 check failed. Redownloading...'))
return 0
else:
# the md5s were the same! skip the download.
self.dllabel.setText(_('Authentic package found in '
'working directory. Skipping download...'))
return 1
return 0
0
Example 42
Project: Roam Source File: mainwindow.py
@roam.utils.timeit
def loadProject(self, project):
"""
Load a project into the application.
"""
roam.utils.log(project)
roam.utils.log(project.name)
roam.utils.log(project.projectfile)
roam.utils.log(project.valid)
(passed, message) = project.onProjectLoad()
if not passed:
self.bar.pushMessage("Project load rejected", "Sorry this project couldn't"
"be loaded. Click for me details.",
QgsMessageBar.WARNING, extrainfo=message)
return
self.actionMap.trigger()
self.close_project()
# No idea why we have to set this each time. Maybe QGIS deletes it for
# some reason.
self.badLayerHandler = BadLayerHandler(callback=self.missingLayers)
QgsProject.instance().setBadLayerHandler(self.badLayerHandler)
# Project loading screen
self.stackedWidget.setCurrentIndex(3)
self.projectloading_label.setText("Project {} Loading".format(project.name))
pixmap = QPixmap(project.splash)
w = self.projectimage.width()
h = self.projectimage.height()
self.projectimage.setPixmap(pixmap.scaled(w,h, Qt.KeepAspectRatio))
QApplication.processEvents()
QDir.setCurrent(os.path.dirname(project.projectfile))
fileinfo = QFileInfo(project.projectfile)
QgsProject.instance().read(fileinfo)
0
Example 43
Project: brickv Source File: mainwindow.py
def update_ui_state(self, connection_state=None):
# FIXME: need to call processEvents() otherwise get_connection_state()
# might return the wrong value
QApplication.processEvents()
if connection_state is None:
connection_state = self.ipcon.get_connection_state()
self.button_connect.setDisabled(False)
self.button_flashing.setDisabled(False)
if connection_state == IPConnection.CONNECTION_STATE_DISCONNECTED:
self.button_connect.setText('Connect')
self.combo_host.setDisabled(False)
self.spinbox_port.setDisabled(False)
self.checkbox_authentication.setDisabled(False)
self.edit_secret.setDisabled(False)
self.button_advanced.setDisabled(True)
elif connection_state == IPConnection.CONNECTION_STATE_CONNECTED:
self.button_connect.setText("Disconnect")
self.combo_host.setDisabled(True)
self.spinbox_port.setDisabled(True)
self.checkbox_authentication.setDisabled(True)
self.edit_secret.setDisabled(True)
self.update_advanced_window()
# restart all pause plugins
for info in infos.get_device_infos():
info.plugin.resume_plugin()
elif connection_state == IPConnection.CONNECTION_STATE_PENDING:
self.button_connect.setText('Abort Pending Automatic Reconnect')
self.combo_host.setDisabled(True)
self.spinbox_port.setDisabled(True)
self.checkbox_authentication.setDisabled(True)
self.edit_secret.setDisabled(True)
self.button_advanced.setDisabled(True)
self.button_flashing.setDisabled(True)
# pause all running plugins
for info in infos.get_device_infos():
info.plugin.pause_plugin()
enable = connection_state == IPConnection.CONNECTION_STATE_CONNECTED
for i in range(1, self.tab_widget.count()):
self.tab_widget.setTabEnabled(i, enable)
for device_info in infos.get_device_infos():
device_info.tab_window.setEnabled(enable)
QApplication.processEvents()
0
Example 44
Project: electrum-doge Source File: greenaddress_instant.py
def do_verify(self, tx):
# 1. get the password and sign the verification request
password = None
if self.wallet.use_encryption:
msg = _('GreenAddress requires your signature to verify that transaction is instant.\n'
'Please enter your password to sign a verification request.')
password = self.win.password_dialog(msg)
if not password:
return
try:
self.verify_button.setText(_('Verifying...'))
QApplication.processEvents() # update the button label
addr = self.get_my_addr(tx)
message = "Please verify if %s is GreenAddress instant confirmed" % tx.hash()
sig = self.wallet.sign_message(addr, message, password)
# 2. send the request
connection = httplib.HTTPSConnection('greenaddress.it')
connection.request("GET", ("/verify/?signature=%s&txhash=%s" % (urllib.quote(sig), tx.hash())),
None, {'User-Agent': 'Electrum-DOGE'})
response = connection.getresponse()
response = json.loads(response.read())
# 3. display the result
if response.get('verified'):
QMessageBox.information(None, _('Verification successful!'),
_('%s is covered by GreenAddress instant confirmation') % (tx.hash()), _('OK'))
else:
QMessageBox.critical(None, _('Verification failed!'),
_('%s is not covered by GreenAddress instant confirmation') % (tx.hash()), _('OK'))
except BaseException as e:
import traceback
traceback.print_exc(file=sys.stdout)
QMessageBox.information(None, _('Error'), str(e), _('OK'))
finally:
self.verify_button.setText(self.button_label)
0
Example 45
Project: brickv Source File: distance_ir.py
def sample_interpolate(self, x, y):
spline = NaturalSpline()
points = []
for point in zip(x, y):
points.append((float(point[0]), float(point[1])))
spline.set_points(points)
px = range(0, 2**12, DistanceIR.DIVIDER)
py = []
for X in px:
py.append(spline.get_value(X))
for i in range(x[0]/DistanceIR.DIVIDER):
py[i] = y[0]
for i in range(x[-1]/DistanceIR.DIVIDER, 2**12/DistanceIR.DIVIDER):
py[i] = y[-1]
for i in range(len(py)):
if py[i] > y[0]:
py[i] = y[0]
if py[i] < y[-1]:
py[i] = y[-1]
try:
old_text = self.sample_edit.text()
for i in range(DistanceIR.NUM_VALUES):
value = int(round(py[i]*100))
self.dist.set_sampling_point(i, value)
self.sample_edit.setText("Writing sample point, value: " + str((i, value)))
QApplication.processEvents()
self.sample_edit.setText(old_text)
except ip_connection.Error:
return
0
Example 46
Project: pyVFX-viewer Source File: pyVFXViewer.py
def updateOnTabChange(self):
# Check to see whether we have deleted all tabs or not
skip = False
try:
self.tabWidget.currentWidget().maxProgress
except:
skip = True
self.progressBar.reset()
if not skip:
minimum = 0
maximum = self.tabWidget.currentWidget().maxProgress
current = self.tabWidget.currentWidget().currentProgress
self.updateProgress(minimum, maximum, current)
if self.checkBoxScanSubdirs.checkState() == self.tabWidget.currentWidget().subdirs:
# Do not change checkbox
pass
else:
# Changing checkbox value
self.checkBoxScanSubdirs.blockSignals(True)
if self.tabWidget.currentWidget().subdirs:
self.checkBoxScanSubdirs.setCheckState( QtCore.Qt.Checked )
QtGui.QApplication.processEvents()
else:
self.checkBoxScanSubdirs.setCheckState( QtCore.Qt.Unchecked )
QtGui.QApplication.processEvents()
self.checkBoxScanSubdirs.blockSignals(False)
try:
self.scanDir = self.tabWidget.currentWidget().scanDir
except:
pass
0
Example 47
Project: electrum Source File: qt.py
def do_verify(self, d):
tx = d.tx
wallet = d.wallet
window = d.parent
# 1. get the password and sign the verification request
password = None
if wallet.use_encryption:
msg = _('GreenAddress requires your signature \n'
'to verify that transaction is instant.\n'
'Please enter your password to sign a\n'
'verification request.')
password = window.password_dialog(msg, parent=d)
if not password:
return
try:
d.verify_button.setText(_('Verifying...'))
QApplication.processEvents() # update the button label
addr = self.get_my_addr(d)
message = "Please verify if %s is GreenAddress instant confirmed" % tx.hash()
sig = wallet.sign_message(addr, message, password)
sig = base64.b64encode(sig)
# 2. send the request
response = requests.request("GET", ("https://greenaddress.it/verify/?signature=%s&txhash=%s" % (urllib.quote(sig), tx.hash())),
headers = {'User-Agent': 'Electrum'})
response = response.json()
# 3. display the result
if response.get('verified'):
d.show_message(_('%s is covered by GreenAddress instant confirmation') % (tx.hash()), title=_('Verification successful!'))
else:
d.show_critical(_('%s is not covered by GreenAddress instant confirmation') % (tx.hash()), title=_('Verification failed!'))
except BaseException as e:
import traceback
traceback.print_exc(file=sys.stdout)
d.show_error(str(e))
finally:
d.verify_button.setText(self.button_label)
0
Example 48
Project: launcher Source File: Main.py
def open_it(self):
Window.activateFakewin(self.fakewin.winId())
self.plugin=False
self.sys_win.close()
self.dock_options_win.close()
self.setGeometry(0,self.top_pos,self.s_width/3+8,self.s_height)
while self.pos_x<self.s_width/3-4.5:
self.current_state='nothing'
if self.pos_x<self.s_width/7:
self.pos_x=self.s_width/7
else:
self.pos_x+=float(self.conf["animation-speed"])
self.repaint()
QtGui.QApplication.processEvents()
if self.pos_x!=self.s_width/3-4 :
self.pos_x=self.s_width/3-4
self.current_state="open"
if self.activity=="apps":
self.allApps=Apps.info(self.current_text)
self.setAttribute(QtCore.Qt.WA_X11NetWmWindowTypeDock,False)
self.update()
QtGui.QApplication.processEvents()
0
Example 49
def createTab(self, imageFiles):
# Check to see whether the scanDir is already present inside any of the tab widgets
scanDirFound = self.checkForExistingTab()
if scanDirFound:
# Open existing tab
for x in range( 0, gui.tabWidget.count() ):
if gui.scanDir == gui.tabWidget.widget(x).scanDir:
gui.tabWidget.setCurrentIndex(x)
else:
# Create new tab
newTab = Tab(self, imageFiles)
#self.tabList.append(tab)
self.tabWidget.addTab( newTab, self.listWidgetDirs.currentItem().text() )
self.tabWidget.setCurrentIndex( self.tabWidget.count()-1 )
QtGui.QApplication.processEvents()
newTab.associatedTab = self.tabWidget.currentWidget()
newTab.loadImagery()
0
Example 50
Project: QuickOSM Source File: process.py
def open_file(
dialog=None,
osm_file=None,
output_geom_types=None,
white_list_column=None,
output_format=None,
layer_name="OsmFile",
config_outputs=None,
output_dir=None,
prefix_file=None):
"""
open an osm file
"""
outputs = get_outputs(output_dir, output_format, prefix_file, layer_name)
# Parsing the file
osm_parser = OsmParser(
osm_file=osm_file,
layers=output_geom_types,
white_list_column=white_list_column)
osm_parser.signalText.connect(dialog.set_progress_text)
osm_parser.signalPercentage.connect(dialog.set_progress_percentage)
layers = osm_parser.parse()
# Finishing the process with geojson or shapefile
num_layers = 0
if output_format == "shape":
dialog.set_progress_text(tr("QuickOSM", u"From GeoJSON to Shapefile"))
for i, (layer, item) in enumerate(layers.iteritems()):
dialog.set_progress_percentage(i / len(layers) * 100)
QApplication.processEvents()
if item['featureCount'] and layer in output_geom_types:
final_layer_name = layer_name
# If configOutputs is not None (from My Queries)
if config_outputs:
if config_outputs[layer]['namelayer']:
final_layer_name = config_outputs[layer]['namelayer']
# Transforming the vector file
osm_geometries = {
'points': QGis.WKBPoint,
'lines': QGis.WKBLineString,
'multilinestrings': QGis.WKBMultiLineString,
'multipolygons': QGis.WKBMultiPolygon}
geojson_layer = QgsVectorLayer(item['geojsonFile'], "temp", "ogr")
encoding = get_default_encoding()
if output_format == "shape":
writer = QgsVectorFileWriter(
outputs[layer],
encoding,
geojson_layer.pendingFields(),
osm_geometries[layer],
geojson_layer.crs(),
"ESRI Shapefile")
else:
writer = QgsVectorFileWriter(
outputs[layer],
encoding,
geojson_layer.pendingFields(),
osm_geometries[layer],
geojson_layer.crs(),
"GeoJSON")
for f in geojson_layer.getFeatures():
writer.addFeature(f)
del writer
# Loading the final vector file
new_layer = QgsVectorLayer(outputs[layer], final_layer_name, "ogr")
# Try to set styling if defined
if config_outputs and config_outputs[layer]['style']:
new_layer.loadNamedStyle(config_outputs[layer]['style'])
else:
# Loading default styles
if layer == "multilinestrings" or layer == "lines":
if "colour" in item['tags']:
new_layer.loadNamedStyle(
join(dirname(dirname(abspath(__file__))),
"styles",
layer + "_colour.qml"))
# Add action about OpenStreetMap
actions = new_layer.actions()
actions.addAction(
QgsAction.OpenUrl,
"OpenStreetMap Browser",
'http://www.openstreetmap.org/browse/'
'[% "osm_type" %]/[% "osm_id" %]',
False)
actions.addAction(
QgsAction.GenericPython,
'JOSM',
'from QuickOSM.CoreQuickOSM.Actions import Actions;'
'Actions.run("josm","[% "full_id" %]")',
False)
actions.addAction(
QgsAction.OpenUrl,
"User default editor",
'http://www.openstreetmap.org/edit?'
'[% "osm_type" %]=[% "osm_id" %]',
False)
for link in ['url', 'website', 'wikipedia', 'ref:UAI']:
if link in item['tags']:
link = link.replace(":", "_")
actions.addAction(
QgsAction.GenericPython,
link,
'from QuickOSM.core.actions import Actions;'
'Actions.run("' + link + '","[% "' + link + '" %]")',
False)
if 'network' in item['tags'] and 'ref' in item['tags']:
actions.addAction(
QgsAction.GenericPython,
"Sketchline",
'from QuickOSM.core.actions import Actions;'
'Actions.run_sketch_line("[% "network" %]","[% "ref" %]")',
False)
# Add index if possible
if output_format == "shape":
new_layer.dataProvider().createSpatialIndex()
QgsMapLayerRegistry.instance().addMapLayer(new_layer)
num_layers += 1
return num_layers