本文整理汇总了Python中qgis.gui.QgsMessageBar.clearWidgets方法的典型用法代码示例。如果您正苦于以下问题:Python QgsMessageBar.clearWidgets方法的具体用法?Python QgsMessageBar.clearWidgets怎么用?Python QgsMessageBar.clearWidgets使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qgis.gui.QgsMessageBar
的用法示例。
在下文中一共展示了QgsMessageBar.clearWidgets方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: geopunt4QgisPoidialog
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
#.........这里部分代码省略.........
self.ui.filterPoiTypeCombo.clear()
self.ui.filterPoiCategoryCombo.addItems( poiCategories )
else:
self.ui.filterPoiCategoryCombo.addItems([""] + list(self.poiCategories.keys()))
self.ui.filterPoiTypeCombo.addItems([""] + list(self.poiTypes.keys()))
def onCategorieFilterChange(self):
poithemeText = self.ui.filterPoiThemeCombo.currentText()
poiCategorieText = self.ui.filterPoiCategoryCombo.currentText()
if poiCategorieText != "" and poithemeText != "":
poiCategorieID = self.poiCategories[ poiCategorieText ]
poithemeID = self.poiThemes[ poithemeText ]
poiTypes = [""] + [n[0] for n in self.poi.listPoitypes(poithemeID, poiCategorieID)]
poiTypes.sort()
self.ui.filterPoiTypeCombo.clear()
self.ui.filterPoiTypeCombo.addItems( poiTypes )
def addMinModel(self):
if not self.layernameValid(): return
self.clearGraphicsLayer()
txt = self.ui.poiText.text()
poithemeText = self.ui.filterPoiThemeCombo.currentText()
if poithemeText != "": poitheme = self.poiThemes[ poithemeText ]
else: poitheme = ""
poiCategorieText = self.ui.filterPoiCategoryCombo.currentText()
if poiCategorieText != "": poiCategorie = self.poiCategories[ poiCategorieText ]
else: poiCategorie = ""
poiTypeText = self.ui.filterPoiTypeCombo.currentText()
if poiTypeText!= "": poiType = self.poiTypes[ poiTypeText ]
else: poiType = ""
NISText= self.ui.filterPoiNIS.currentText()
if NISText != "" and not self.ui.currentBoundsVink.isChecked(): Niscode = self.NIScodes[NISText]
else: Niscode = ""
cluster = self.ui.clusterCheck.isChecked()
if self.ui.currentBoundsVink.isChecked():
bbox = self.iface.mapCanvas().extent()
minX, minY = self.gh.prjPtFromMapCrs([bbox.xMinimum(),bbox.yMinimum()], 4326)
maxX, maxY = self.gh.prjPtFromMapCrs([bbox.xMaximum(),bbox.yMaximum()], 4326)
xyBox = [minX, minY, maxX, maxY]
pts= self.poi.fetchPoi( txt, c=1024, srs=4326 , maxModel=0, updateResults=0,
bbox= xyBox, theme= poitheme , category= poiCategorie,
POItype= poiType, clustering= cluster )
else:
pts= self.poi.fetchPoi( txt, c=1024, srs=4326 , maxModel=0, updateResults=0,
bbox=None, theme= poitheme , category= poiCategorie,
POItype= poiType, region= Niscode, clustering= cluster )
if type( pts ) == str:
self.bar.pushMessage( QCoreApplication.translate("geopunt4QgisPoidialog","Waarschuwing"),
pts, level=Qgis.Warning, duration=5)
elif type( pts ) == list or type( pts ) == dict:
self.ph.save_minPois_points(pts, layername=self.layerName, startFolder= os.path.join(self.startDir, self.layerName), saveToFile=self.saveToFile, sender=self )
self.close()
def searchTxtChanged(self):
txt= self.ui.poiText.text()
if txt != "":
msg = QCoreApplication.translate("geopunt4QgisPoidialog",
"Voeg meer punten toe")
else:
msg = QCoreApplication.translate("geopunt4QgisPoidialog",
"Voeg alle punten toe" )
self.ui.addMinModelBtn.setText(msg)
def _getSelectedPois(self):
pois = self.poi.PoiResult
selPois = []
selRows = set( [sel.row() for sel in self.ui.resultLijst.selectedIndexes()] )
for row in selRows:
itemID = self.ui.resultLijst.item(row,0).text()
selPois += [i for i in pois if i["id"] == itemID]
return selPois
def clearGraphicsLayer(self):
for graphic in self.graphicsLayer:
self.iface.mapCanvas().scene().removeItem(graphic)
self.graphicsLayer = []
def layernameValid(self):
if not hasattr(self, 'layerName'):
layerName, accept = QInputDialog.getText(None,
QCoreApplication.translate("geopunt4Qgis", 'Laag toevoegen'),
QCoreApplication.translate("geopunt4Qgis", 'Geef een naam voor de laag op:') )
if accept == False:
return False
else:
self.layerName = layerName
return True
def clean(self):
self.bar.clearWidgets()
self.ui.poiText.setText("")
self.ui.msgLbl.setText("")
self.ui.resultLijst.clearContents()
self.ui.resultLijst.setRowCount(0)
self.clearGraphicsLayer()
示例2: BackupedImgUploaderWizard
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
class BackupedImgUploaderWizard(QtGui.QWizard, FORM_CLASS):
def __init__(self, iface, settings, parent=None):
"""Constructor."""
super(BackupedImgUploaderWizard, self).__init__(parent)
# Set up the user interface from Designer.
# After setupUI you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.iface = iface
self.setupUi(self)
# Message bars need to be attached to pages, since the wizard object
# does not have a layout. It doesn't work to attach the same bar
# object to all pages (it is only shown in the last one). The only way
# I could make it work was to create different QgsMessageBar objects,
# one per page, but it is very to keep track of those references
# along the code. It is messy, there should be a better solution.
self.bar0 = QgsMessageBar()
self.bar0.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
self.page(0).layout().addWidget(self.bar0)
self.bar1 = QgsMessageBar()
self.bar1.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
self.page(1).layout().addWidget(self.bar1)
self.bar2 = QgsMessageBar()
self.bar2.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
self.page(2).layout().addWidget(self.bar2)
self.setButtonText(QtGui.QWizard.CustomButton1, self.tr("&Start upload"));
self.setOption(QtGui.QWizard.HaveCustomButton1, True);
self.settings = settings
# Dictionaries to save imagery info (todo: defined as a classes in the future)
self.metadata = {}
self.reprojected = []
self.licensed = []
# Initialize layers and default settings
self.loadLayers()
self.loadMetadataSettings()
self.loadStorageSettings()
self.loadOptionsSettings()
# register event handlers
""" List of page navigation buttons in QWizard, for reference.
Please comment out and implement following functions if necessary."""
#self.button(QWizard.BackButton).clicked.connect(self.previousPage)
#self.button(QWizard.NextButton).clicked.connect(self.nextPage)
#self.button(QWizard.FinishButton).clicked.connect(self.finishWizard)
#self.button(QWizard.CancelButton).clicked.connect(self.cancelWizard)
# Imagery connections (wizard page 1)
self.layers_tool_button.clicked.connect(self.loadLayers)
self.file_tool_button.clicked.connect(self.selectFile)
self.add_source_button.clicked.connect(self.addSources)
self.remove_source_button.clicked.connect(self.removeSources)
self.up_source_button.clicked.connect(self.upSource)
self.down_source_button.clicked.connect(self.downSource)
# Metadata connections (wizard page 2)
self.sense_start_edit.setCalendarPopup(1)
self.sense_start_edit.setDisplayFormat('dd.MM.yyyy HH:mm')
self.sense_end_edit.setCalendarPopup(1)
self.sense_end_edit.setDisplayFormat('dd.MM.yyyy HH:mm')
self.default_button.clicked.connect(self.loadMetadataSettings)
self.clean_button.clicked.connect(self.cleanMetadataSettings)
self.save_button.clicked.connect(self.saveMetadata)
# Upload tab connections (wizard page 3)
self.storage_combo_box.currentIndexChanged.connect(self.enableSpecify)
self.customButtonClicked.connect(self.startUploader)
# event handling for wizard page 1
def loadLayers(self):
all_layers = self.iface.mapCanvas().layers()
for layer in all_layers:
if not self.layers_list_widget.findItems(layer.name(),Qt.MatchExactly):
item = QListWidgetItem()
item.setText(layer.name())
item.setData(Qt.UserRole, layer.dataProvider().dataSourceUri())
self.layers_list_widget.addItem(item)
def selectFile(self):
selected_file = QFileDialog.getOpenFileName(
self,
'Select imagery file',
os.path.expanduser("~"))
self.source_file_edit.setText(selected_file)
def addSources(self):
filename = self.source_file_edit.text()
selected_layers = self.layers_list_widget.selectedItems()
if not filename and not selected_layers:
self.bar0.clearWidgets()
self.bar0.pushMessage(
#.........这里部分代码省略.........
示例3: ImgSearchDialog
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
#.........这里部分代码省略.........
""" This function is not in use. """
"""
def searchLatest(self):
action = "meta"
dictQueries = {}
try:
dictQueries['sort'] = "desc"
dictQueries['order_by'] = "acquisition_end"
if (self.lineEditResolutionFrom.text() != '' and
self.lineEditResolutionFrom.text() is not None):
dictQueries['gsd_from'] = float(
self.lineEditResolutionFrom.text())
if (self.lineEditResolutionTo.text() != '' and
self.lineEditResolutionTo.text() is not None):
dictQueries['gsd_to'] = float(
self.lineEditResolutionTo.text())
if (self.lineEditNumImages.text() != '' and
self.lineEditNumImages.text() is not None):
dictQueries['limit'] = int(self.lineEditNumImages.text())
self.oamCatalogAccess.setAction(action)
self.oamCatalogAccess.setDictQueries(dictQueries)
metadataInList = self.oamCatalogAccess.getMetadataInList()
self.refreshListWidget(metadataInList)
except Exception as e:
qMsgBox = QMessageBox()
qMsgBox.setWindowTitle('Message')
qMsgBox.setText("Please make sure if you entered " +
"valid data/internet connection, and try again.")
qMsgBox.exec_()
"""
""" This function is not in use. """
"""
def browseLocation(self):
print("Browse location of loaded layer...")
"""
def browseThumbnailAndMeta(self, item):
singleMetaInDict = item.data(Qt.UserRole)
# print(str(singleMetaInDict))
if type(singleMetaInDict) is dict:
if self.imgBrowser is None:
self.imgBrowser = ImgBrowser(self.iface)
self.imgBrowser.thumbnailManager.statusChanged.connect(
self.changeThumbnailStatus)
self.imgBrowser.thumbnailManager.error.connect(
self.displayThumnailDownloadError)
pos = self.pos()
print(pos.x())
print(pos.y())
pos.setX(pos.x() + 400)
pos.setY(pos.y() + 20)
self.imgBrowser.move(pos)
self.imgBrowser.setSingleMetaInDic(singleMetaInDict)
self.imgBrowser.displayMetadata()
self.imgBrowser.displayThumbnail()
if not self.imgBrowser.isVisible():
self.imgBrowser.show()
self.imgBrowser.activateWindow()
def changeThumbnailStatus(self, status):
# print(str(status))
if status == 0:
pass
"""
self.bar.clearWidgets()
self.bar.pushMessage(
'INFO',
'Downloading thumbnail...',
level=QgsMessageBar.INFO,
duration=8)
"""
if status == 1:
self.bar.clearWidgets()
def displayThumnailDownloadError(self, e):
self.bar.clearWidgets()
self.bar.pushMessage(
'Failed to download thumbnail.\n{}'.format(str(e)),
level=QgsMessageBar.WARNING,
duration=8)
def execOk(self):
# save self.defaultQueriesInDict into self.settings
self.saveQueriesSettings()
self.close()
def execCancel(self):
self.close()
示例4: AlgorithmDialog
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
#.........这里部分代码省略.........
'Your input layers do not have the same extent as the project, '
'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
'Do you want to continue?'),
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if reply == QMessageBox.No:
return
ok, msg = self.alg.checkParameterValues(parameters, context)
if msg:
QMessageBox.warning(
self, self.tr('Unable to execute algorithm'), msg)
return
self.btnRun.setEnabled(False)
self.btnClose.setEnabled(False)
buttons = self.mainWidget.iterateButtons
self.iterateParam = None
for i in range(len(list(buttons.values()))):
button = list(buttons.values())[i]
if button.isChecked():
self.iterateParam = list(buttons.keys())[i]
break
self.progressBar.setMaximum(0)
self.lblProgress.setText(self.tr('Processing algorithm...'))
# Make sure the Log tab is visible before executing the algorithm
try:
self.tabWidget.setCurrentIndex(1)
self.repaint()
except:
pass
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
self.setInfo(
self.tr('<b>Algorithm \'{0}\' starting...</b>').format(self.alg.displayName()), escape_html=False)
feedback.pushInfo(self.tr('Input parameters:'))
feedback.pushCommandInfo(pformat(parameters))
feedback.pushInfo('')
start_time = time.time()
if self.iterateParam:
self.buttonCancel.setEnabled(self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)
if executeIterating(self.alg, parameters, self.iterateParam, context, feedback):
feedback.pushInfo(
self.tr('Execution completed in {0:0.2f} seconds'.format(time.time() - start_time)))
self.buttonCancel.setEnabled(False)
self.finish(parameters, context, feedback)
else:
self.buttonCancel.setEnabled(False)
QApplication.restoreOverrideCursor()
self.resetGUI()
else:
command = self.alg.asPythonCommand(parameters, context)
if command:
ProcessingLog.addToLog(command)
self.buttonCancel.setEnabled(self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)
result = executeAlgorithm(self.alg, parameters, context, feedback)
feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds'.format(time.time() - start_time)))
feedback.pushInfo(self.tr('Results:'))
feedback.pushCommandInfo(pformat(result))
feedback.pushInfo('')
self.buttonCancel.setEnabled(False)
self.finish(result, context, feedback)
except AlgorithmDialogBase.InvalidParameterValue as e:
try:
self.buttonBox.accepted.connect(lambda e=e:
e.widget.setPalette(QPalette()))
palette = e.widget.palette()
palette.setColor(QPalette.Base, QColor(255, 255, 0))
e.widget.setPalette(palette)
except:
pass
self.bar.clearWidgets()
self.bar.pushMessage("", self.tr("Wrong or missing parameter value: {0}").format(e.parameter.description()),
level=QgsMessageBar.WARNING, duration=5)
def finish(self, result, context, feedback):
keepOpen = ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN)
if self.iterateParam is None:
if not handleAlgorithmResults(self.alg, context, feedback, not keepOpen):
self.resetGUI()
return
self.executed = True
self.setInfo(self.tr('Algorithm \'{0}\' finished').format(self.alg.displayName()), escape_html=False)
QApplication.restoreOverrideCursor()
if not keepOpen:
self.close()
else:
self.resetGUI()
if self.alg.hasHtmlOutputs():
self.setInfo(
self.tr('HTML output has been generated by this algorithm.'
'\nOpen the results dialog to check it.'), escape_html=False)
示例5: ImgUploaderWizard
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
#.........这里部分代码省略.........
def cancelWizard(self):
# print "cancel wizard button was clicked."
# need to display QMessageBox
if self.upPrgWin is not None:
self.upPrgWin.cancelAllUploads()
# event handling for wizard page 1
def loadLayers(self):
all_layers = self.iface.mapCanvas().layers()
for layer in all_layers:
if not self.layers_list_widget.findItems(
layer.name(), Qt.MatchExactly):
if not self.sources_list_widget.findItems(
layer.name(), Qt.MatchExactly):
item = QListWidgetItem()
item.setText(layer.name())
item.setData(
Qt.UserRole, os.path.abspath(layer.dataProvider().dataSourceUri()))
self.layers_list_widget.addItem(item)
# print(item.data(Qt.UserRole))
def selectFile(self):
selected_file = QFileDialog.getOpenFileName(
self,
'Select imagery file',
os.path.expanduser("~"))
self.source_file_edit.setText(selected_file)
def addSources(self):
filename = self.source_file_edit.text()
selected_layers = self.layers_list_widget.selectedItems()
if not filename and not selected_layers:
self.bar0.clearWidgets()
self.bar0.pushMessage(
'WARNING',
'Either a layer or file should be selected to be added',
level=QgsMessageBar.WARNING)
else:
added = False
if filename:
result_val = validate_file(filename)
if result_val["val"]:
if not self.sources_list_widget.findItems(
filename, Qt.MatchExactly):
item = QListWidgetItem()
item.setText(os.path.basename(filename))
item.setData(Qt.UserRole, os.path.abspath(filename))
print(item.data(Qt.UserRole))
self.sources_list_widget.addItem(item)
self.added_sources_list_widget.addItem(item.clone())
self.source_file_edit.setText('')
added = True
else:
msg = result_val["msg"]
self.bar0.clearWidgets()
self.bar0.pushMessage(
"CRITICAL",
msg,
level=QgsMessageBar.CRITICAL)
QgsMessageLog.logMessage(
"CRITICAL",
msg,
level=QgsMessageLog.INFO)
if selected_layers:
示例6: ResourceSharingDialog
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
#.........这里部分代码省略.........
self.collections_model.sort(0, Qt.AscendingOrder)
self.collection_proxy = CustomSortFilterProxyModel(self)
self.collection_proxy.setSourceModel(self.collections_model)
self.list_view_collections.setModel(self.collection_proxy)
# Active selected collection
self._selected_collection_id = None
# Slots
self.button_add.clicked.connect(self.add_repository)
self.button_edit.clicked.connect(self.edit_repository)
self.button_delete.clicked.connect(self.delete_repository)
self.button_reload.clicked.connect(self.reload_repositories)
self.menu_list_widget.currentRowChanged.connect(self.set_current_tab)
self.list_view_collections.selectionModel().currentChanged.connect(
self.on_list_view_collections_clicked)
self.line_edit_filter.textChanged.connect(self.filter_collections)
self.button_install.clicked.connect(self.install_collection)
self.button_open.clicked.connect(self.open_collection)
self.button_uninstall.clicked.connect(self.uninstall_collection)
self.button_box.button(QDialogButtonBox.Help).clicked.connect(
self.open_help)
# Populate repositories widget and collections list view
self.populate_repositories_widget()
self.reload_collections_model()
def set_current_tab(self, index):
"""Set stacked widget based on active tab.
:param index: The index of the active list widget item.
:type index: int
"""
# Clear message bar first
self.message_bar.clearWidgets()
if index == (self.menu_list_widget.count() - 1):
# Switch to settings tab
self.stacked_menu_widget.setCurrentIndex(1)
else:
# Switch to plugins tab
if index == 1:
# Installed
self.collection_proxy.accepted_status = \
COLLECTION_INSTALLED_STATUS
# Set the web view
title = self.tr('Installed Collections')
description = self.tr(
'On the left you see the list of all collections '
'installed on your QGIS')
else:
# All
self.collection_proxy.accepted_status = COLLECTION_ALL_STATUS
# Set the web view
title = self.tr('All Collections')
description = self.tr(
'On the left you see the list of all collections '
'available from the repositories registered in the '
'settings.')
context = {
'resources_path': resources_path(),
'title': title,
'description': description
}
self.web_view_details.setHtml(
render_template('tab_description.html', context))
self.stacked_menu_widget.setCurrentIndex(0)
示例7: S3Manager
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
class S3Manager(S3Connection):
def __init__(self,
access_key_id,
secret_access_key,
bucket_name,
filenames,
upload_options,
wizard_page,
parent=None):
S3Connection.__init__(self, access_key_id, secret_access_key)
self.upload_options = upload_options
self.bucket_name = bucket_name
self.bucket = None
self.filenames = filenames
self.s3Uploaders = []
self.threads = []
self.count_uploaded_images = 0
self.num_uploading_images = 0
#For GUI (messages and progress bars)
self.wizard_page = wizard_page
self.uploader_widget = QtGui.QWidget()
self.uploader_widget.setWindowTitle("Upload Progress Bars")
self.uploader_widget.setWindowFlags(Qt.WindowStaysOnTopHint)
self.uploader_v_box = QtGui.QVBoxLayout()
self.uploader_widget.setLayout(self.uploader_v_box)
self.msg_bar_main = None
self.msg_bar_main_content = None
self.cancel_button_main = None
self.msg_bars = []
self.msg_bars_content = []
self.progress_bars = []
self.cancel_buttons = []
def getBucket(self):
for trial in xrange(3):
if self.bucket: break
try:
self.bucket = super(S3Manager,self).get_bucket(self.bucket_name)
QgsMessageLog.logMessage(
'Connection established' % trial,
'OAM',
level=QgsMessageLog.INFO)
except:
if trial == 2:
QgsMessageLog.logMessage(
'Failed to connect after 3 attempts',
'OAM',
level=QgsMessageLog.CRITICAL)
return self.bucket
"""for testing purpose"""
"""
rsKeys = []
for key in self.bucket.list():
rsKeys.append(repr(key))
return rsKeys
"""
#functions for threading purpose
def uploadFiles(self):
""" Testing purpose only """
if "notify_oam" in self.upload_options:
print "notify_oam"
if "trigger_tiling" in self.upload_options:
print "trigger_tiling"
# configure the msg_bar_main (including Cancel button and its container)
self.msg_bar_main = QgsMessageBar()
self.msg_bar_main.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
self.wizard_page.layout().addWidget(self.msg_bar_main)
self.msg_bar_main_content = self.msg_bar_main.createMessage('Performing upload...', )
self.cancel_button_main = QPushButton()
self.cancel_button_main.setText('Cancel')
self.cancel_button_main.clicked.connect(self.cancelAllUploads)
self.msg_bar_main_content.layout().addWidget(self.cancel_button_main)
self.msg_bar_main.clearWidgets()
self.msg_bar_main.pushWidget(self.msg_bar_main_content, level=QgsMessageBar.INFO)
self.num_uploading_images = len(self.filenames)
for i in range(0, self.num_uploading_images):
filename = self.filenames[i]
# create a new S3Uploader instance
self.s3Uploaders.append(S3Uploader(filename, self.bucket, self.upload_options, i))
try:
# start the worker in a new thread
#.........这里部分代码省略.........
示例8: ImgUploaderWizard
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
#.........这里部分代码省略.........
def finishWizard(self):
#print "finish wizard button was clicked."
pass
def cancelWizard(self):
#print "cancel wizard button was clicked."
# need to display QMessageBox
if self.s3UpPrgWin != None:
self.s3UpPrgWin.cancelAllUploads()
# event handling for wizard page 1
def loadLayers(self):
all_layers = self.iface.mapCanvas().layers()
for layer in all_layers:
if not self.layers_list_widget.findItems(layer.name(),Qt.MatchExactly):
if not self.sources_list_widget.findItems(layer.name(),Qt.MatchExactly):
item = QListWidgetItem()
item.setText(layer.name())
item.setData(Qt.UserRole, layer.dataProvider().dataSourceUri())
self.layers_list_widget.addItem(item)
def selectFile(self):
selected_file = QFileDialog.getOpenFileName(
self,
'Select imagery file',
os.path.expanduser("~"))
self.source_file_edit.setText(selected_file)
def addSources(self):
filename = self.source_file_edit.text()
selected_layers = self.layers_list_widget.selectedItems()
if not filename and not selected_layers:
self.bar0.clearWidgets()
self.bar0.pushMessage(
'WARNING',
'Either a layer or file should be selected to be added',
level=QgsMessageBar.WARNING)
else:
added = False
if filename:
result_val = validate_file(filename)
if result_val["val"]:
if not self.sources_list_widget.findItems(filename,Qt.MatchExactly):
item = QListWidgetItem()
item.setText(os.path.basename(filename))
item.setData(Qt.UserRole, filename)
self.sources_list_widget.addItem(item)
self.added_sources_list_widget.addItem(item.clone())
self.source_file_edit.setText('')
added = True
else:
msg = result_val["msg"]
self.bar0.clearWidgets()
self.bar0.pushMessage("CRITICAL", msg, level=QgsMessageBar.CRITICAL)
QgsMessageLog.logMessage("CRITICAL", msg, level=QgsMessageLog.INFO)
if selected_layers:
for item in selected_layers:
if validate_layer(item.text(), self.iface):
if not self.sources_list_widget.findItems(item.text(),Qt.MatchExactly):
self.layers_list_widget.takeItem(self.layers_list_widget.row(item))
self.sources_list_widget.addItem(item)
self.added_sources_list_widget.addItem(item.clone())
added = True
else:
示例9: geopunt4QgisAdresDialog
# 需要导入模块: from qgis.gui import QgsMessageBar [as 别名]
# 或者: from qgis.gui.QgsMessageBar import clearWidgets [as 别名]
class geopunt4QgisAdresDialog(QtGui.QDialog):
def __init__(self, iface):
QtGui.QDialog.__init__(self, None)
self.setWindowFlags( self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint )
#self.setWindowFlags( self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
self.iface = iface
# initialize locale
locale = QtCore.QSettings().value("locale/userLocale", "nl")
if not locale: locale == 'nl'
else: locale = locale[0:2]
localePath = os.path.join(os.path.dirname(__file__), 'i18n', 'geopunt4qgis_{}.qm'.format(locale))
if os.path.exists(localePath):
self.translator = QtCore.QTranslator()
self.translator.load(localePath)
if QtCore.qVersion() > '4.3.3': QtCore.QCoreApplication.installTranslator(self.translator)
self._initGui()
def _initGui(self):
"""setup the user interface"""
self.ui = Ui_geopunt4Qgis()
self.ui.setupUi(self)
#get settings
self.s = QtCore.QSettings()
self.loadSettings()
#setup geometryHelper object
self.gh = gh.geometryHelper(self.iface)
#create graphicsLayer
self.graphicsLayer = []
#populate gemeenteBox
gemeentes = json.load( open(os.path.join(os.path.dirname(__file__),
"data/gemeentenVL.json")) )
gemeenteNamen = [str( n["Naam"]) for n in gemeentes]
self.ui.gemeenteBox.addItems( gemeenteNamen )
self.ui.gemeenteBox.setEditText(QtCore.QCoreApplication.translate(
"geopunt4QgisAdresDialog", "gemeente"))
self.ui.gemeenteBox.setStyleSheet('QComboBox {color: #808080}')
self.ui.gemeenteBox.setFocus()
self.completer = QtGui.QCompleter( self )
self.completerModel = QtGui.QStringListModel( self )
self.ui.gemeenteBox.setCompleter( self.completer )
self.completer.setModel( self.completerModel )
self.completer.setCaseSensitivity(False)
self.completerModel.setStringList( gemeenteNamen )
#setup a message bar
self.bar = QgsMessageBar()
self.bar.setSizePolicy( QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed )
self.ui.verticalLayout.addWidget(self.bar)
self.ui.buttonBox.addButton( QtGui.QPushButton("Sluiten"), QtGui.QDialogButtonBox.RejectRole )
for btn in self.ui.buttonBox.buttons():
btn.setAutoDefault(0)
#event handlers
if self.adresSearchOnEnter:
self.ui.zoekText.returnPressed.connect(self.onZoekActivated)
else:
self.ui.zoekText.textEdited.connect(self.onZoekActivated)
self.ui.gemeenteBox.currentIndexChanged.connect(self.onZoekActivated)
self.ui.resultLijst.itemDoubleClicked.connect(self.onItemActivated)
self.ui.resultLijst.itemClicked.connect(self.onItemClick)
self.ui.ZoomKnop.clicked.connect(self.onZoomKnopClick)
self.ui.Add2mapKnop.clicked.connect(self.onAdd2mapKnopClick)
self.ui.buttonBox.helpRequested.connect(self.openHelp)
self.finished.connect(self.clean )
def loadSettings(self):
self.saveToFile = int( self.s.value("geopunt4qgis/adresSavetoFile" , 1))
layerName = self.s.value("geopunt4qgis/adreslayerText", "")
if layerName :
self.layerName= layerName
self.adresSearchOnEnter = int( self.s.value("geopunt4qgis/adresSearchOnEnter" , 0))
self.timeout = int( self.s.value("geopunt4qgis/timeout" ,15))
if int( self.s.value("geopunt4qgis/useProxy" , 0)):
self.proxy = self.s.value("geopunt4qgis/proxyHost" ,"")
self.port = self.s.value("geopunt4qgis/proxyPort" ,"")
else:
self.proxy = ""
self.port = ""
self.startDir = self.s.value("geopunt4qgis/startDir", os.path.dirname(__file__))
self.gp = geopunt.Adres(self.timeout, self.proxy, self.port)
def openHelp(self):
webbrowser.open_new_tab("http://www.geopunt.be/voor-experts/geopunt-plug-ins/functionaliteiten/zoek-een-adres")
def onZoekActivated(self):
self._clearGraphicsLayer()
self.bar.clearWidgets()
gemeente = self.ui.gemeenteBox.currentText()
if gemeente <> QtCore.QCoreApplication.translate("geopunt4QgisAdresDialog","gemeente"):
self.ui.gemeenteBox.setStyleSheet('QComboBox {color: #000000}')
#.........这里部分代码省略.........