示例#1
0
    def __init__(self, workspace, documents):
        super(_UISaveFiles, self).__init__(workspace)
        self.cancelled = False
        from PyQt4 import uic  # lazy import for better startup performance
        uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self)
        self.buttonBox.clicked.connect(self._onButtonClicked)

        self._itemToDocument = {}
        for document in documents:
            name = document.fileName()
            if name is None:
                name = 'untitled'
            item = QListWidgetItem(name, self.listWidget)
            if document.filePath() is not None:
                item.setToolTip(document.filePath())
            item.setCheckState(Qt.Checked)
            self._itemToDocument[item] = document
        self.buttonBox.button(self.buttonBox.Discard).setText(
            self.tr('Close &without Saving'))
        self.buttonBox.button(self.buttonBox.Cancel).setText(
            self.tr('&Cancel Close'))
        self.buttonBox.button(self.buttonBox.Save).setText(
            self.tr('&Save checked'))

        self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
示例#2
0
    def __init__(self, workspace, documents):
        super(_UISaveFiles, self).__init__(workspace)
        self.cancelled = False
        uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self)
        self.buttonBox.clicked.connect(self._onButtonClicked)

        self._itemToDocument = {}
        for document in documents:
            name = document.fileName()
            if name is None:
                name = 'untitled'
            item = QListWidgetItem( name, self.listWidget )
            if document.filePath() is not None:
                item.setToolTip( document.filePath() )
            item.setCheckState( Qt.Checked )
            self._itemToDocument[item] = document

        # Retitle buttons, add first letter shortcuts for them.
        bb = self.buttonBox
        self._shortcut = (
          self._firstLetterShortcut(bb.Discard, 'close &Without saving'),
          self._firstLetterShortcut(bb.Cancel, '&Cancel close'),
          self._firstLetterShortcut(bb.Save, '&Save checked') )

        self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
示例#3
0
 def __init__(self, tableView,  parent = None):
     """
     Constructor
     """
     QDialog.__init__(self, parent)
     self.setupUi(self)
     del TableSetting.ret
     TableSetting.ret = None
     self.setWindowTitle(u"自定义列表")
     self.tableView = tableView
     headers=self.tableView.model().headers
     for i in range(len(headers)):
         newItem = QListWidgetItem();
         newItem.setText(headers[i]);
         
         if self.tableView.isColumnHidden(i):
             newItem.setCheckState(QtCore.Qt.Unchecked)
         else:
             newItem.setCheckState(QtCore.Qt.Checked)
         self.listWidget.insertItem(i, newItem)
         if i < 2:
             newItem.setHidden(True)
     items = [str(i) for i in range(self.listWidget.count())]
     for item in items:
         self.comboBox_3.addItem(item)
     self.comboBox_3.setCurrentIndex(self.tableView.freezeNum)        
     
     self.groupBox.setVisible(False)
示例#4
0
文件: workspace.py 项目: vi/enki
    def __init__(self, workspace, documents):
        super(_UISaveFiles, self).__init__(workspace)
        self.cancelled = False
        uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self)
        self.buttonBox.clicked.connect(self._onButtonClicked)

        self._itemToDocument = {}
        for document in documents:
            name = document.fileName()
            if name is None:
                name = 'untitled'
            item = QListWidgetItem( name, self.listWidget )
            if document.filePath() is not None:
                item.setToolTip( document.filePath() )
            item.setCheckState( Qt.Checked )
            self._itemToDocument[item] = document
        self.buttonBox.button(self.buttonBox.Discard).setText(self.tr('close &Without saving'))
        self.buttonBox.button(self.buttonBox.Cancel).setText(self.tr('&Cancel close'))
        self.buttonBox.button(self.buttonBox.Save).setText(self.tr('&Save checked'))
        # Provide first-letter only shortcuts (not Alt+first letter which is
        # already present because of the & before letters) for each button.
        self.shortcut = []
        for letter, button in (("W", self.buttonBox.Discard),
                               ("C", self.buttonBox.Cancel),
                               ("S", self.buttonBox.Save)):
            shortcut = QShortcut(QKeySequence(letter), self)
            shortcut.activated.connect(self.buttonBox.button(button).click)
            self.shortcut.append(shortcut)

        self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
示例#5
0
 def resultitemchanged(self, new_item):
     self.IDC_textDetails.setText('')
     self.IDC_listRessources.clear()
     self.IDC_plainTextLink.clear()
     if new_item is None:
         return
     package = new_item.data(Qt.UserRole)
     self.cur_package = package
     if package is None:
         return
     self.IDC_textDetails.setText(
         u'{0}\n\n{1}\n{2}\n\n{3}'.format(
             package.get('notes', 'no notes'),
             package.get('author', 'no author'),
             package.get('author_email', 'no author_email'),
             package.get('license_id', 'no license_id')
         )
     )
     if package.get('num_resources', 0) > 0:
         for res in package['resources']:
             item = QListWidgetItem(u'{0}: {1}'.format(
                 res.get('format', 'no format')
                 , res.get('name', 'no name')
             ))
             item.setData(Qt.UserRole, res)
             item.setCheckState(Qt.Unchecked)
             self.IDC_listRessources.addItem(item)
示例#6
0
 def __init__(self, rawImageLayer, objectImageLayer, featureTableNames, imagePerObject=True, \
              imagePerTime = True, parent=None):
     QDialog.__init__(self, parent)
     self.setWindowTitle("Export to Knime")
     ui_class, widget_class = uic.loadUiType(os.path.split(__file__)[0] + "/exportToKnimeDialog.ui")
     self.ui = ui_class()
     self.ui.setupUi(self)
     itemRaw = QListWidgetItem(rawImageLayer.name)
     self.ui.rawList.addItem(itemRaw)
     itemObjects = QListWidgetItem(objectImageLayer.name)
     self.ui.objectList.addItem(itemObjects)
     self.imagePerObject = imagePerObject
     self.imagePerTime = imagePerTime
     #FIXME: assume for now tht the feature table is a dict
     try: 
         for plugin, feature_dict in featureTableNames.iteritems():
             print plugin
             for feature_name in feature_dict.keys():
                 print "adding feature:", feature_name
                 item = QListWidgetItem(feature_name)
                 item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                 item.setCheckState(Qt.Unchecked)
                 self.ui.featureList.addItem(item)
                 
     except:
         print "hahaha, doesn't work!"
示例#7
0
    def refreshAnnotations(self):
        for annotation in self.getAnnotations():
            if annotation not in self.annotations:
                self.annotations.append(annotation)
                self.annotationsName.append('Annotation')
        i = 0
        to_del = []
        for annotation in self.annotations:
            if annotation not in self.getAnnotations():
                to_del.append(i)
            i += 1
        i = 0
        for index in to_del:
            self.annotations.pop(index)
            self.annotationsName.pop(index)
        self.annotationList.clearSelection()
        self.annotationList.clear()

        # argh
        for annotation in self.annotations:
            item = QListWidgetItem(self.annotationsName[i])
            if annotation.isVisible():
                item.setCheckState(Qt.Checked)
            else:
                item.setCheckState(Qt.Unchecked)
            item.setFlags(item.flags() | Qt.ItemIsEditable)
            self.annotationList.addItem(item)
            i += 1
 def populate_well_listWidget(self):
     survey_file = CONF.survey_dir / '.survey'
     if survey_file.exists():
         for name in get_data_files(CONF.well_dir):
             new_item = QListWidgetItem(name, self.wells_listWidget)
             new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
             new_item.setCheckState(Qt.Unchecked)
示例#9
0
    def __init__(self, rawImageLayer, objectImageLayer, featureTableNames, imagePerObject=True, \
                 imagePerTime = True, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle("Export to Knime")
        ui_class, widget_class = uic.loadUiType(
            os.path.split(__file__)[0] + "/exportToKnimeDialog.ui")
        self.ui = ui_class()
        self.ui.setupUi(self)
        itemRaw = QListWidgetItem(rawImageLayer.name)
        self.ui.rawList.addItem(itemRaw)
        itemObjects = QListWidgetItem(objectImageLayer.name)
        self.ui.objectList.addItem(itemObjects)
        self.imagePerObject = imagePerObject
        self.imagePerTime = imagePerTime
        #FIXME: assume for now tht the feature table is a dict
        try:
            for plugin, feature_dict in featureTableNames.iteritems():
                print plugin
                for feature_name in feature_dict.keys():
                    print "adding feature:", feature_name
                    item = QListWidgetItem(feature_name)
                    item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                    item.setCheckState(Qt.Unchecked)
                    self.ui.featureList.addItem(item)

        except:
            print "hahaha, doesn't work!"
示例#10
0
 def __init__(self, mainwin, pdfs):
     KDialog.__init__(self, mainwin)
     self.mainwin = mainwin
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setButtons(KDialog.ButtonCode(
         KDialog.User1 | KDialog.Ok | KDialog.Cancel))
     self.setButtonGuiItem(KDialog.Ok, KStandardGuiItem.print_())
     self.setButtonIcon(KDialog.User1, KIcon("edit-select-all"))
     self.setButtonText(KDialog.User1, i18n("Select all"))
     self.setCaption(i18n("Print documents"))
     b = KVBox(self)
     b.setSpacing(4)
     QLabel(i18n("Please select the files you want to print:"), b)
     fileList = QListWidget(b)
     fileList.setIconSize(QSize(22, 22))
     fileList.setWhatsThis(i18n(
         "These are the PDF documents that are up-to-date (i.e. newer than "
         "the LilyPond source document). "
         "Check the documents you want to send to the printer."))
     
     for pdf in pdfs:
         i = QListWidgetItem(KIcon("application-pdf"), os.path.basename(pdf),
             fileList)
         i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable |
             Qt.ItemIsUserCheckable)
         i.setCheckState(Qt.Unchecked)
     
     fileList.item(0).setCheckState(Qt.Checked)
     self.fileList = fileList
     self.setMainWidget(b)
     self.resize(350, 200)
     self.pdfs = pdfs
     self.user1Clicked.connect(self.selectAll)
 def load_data_list(self):
     folder_path = Path(CONF.data_root) / \
                 CONF.current_survey / "Seismics"
     for name in get_data_files(folder_path):
         new_item = QListWidgetItem(name, self.data_list_Widget)
         new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
         new_item.setCheckState(Qt.Unchecked)
示例#12
0
    def __init__(self, workspace, documents):
        super(_UISaveFiles, self).__init__(workspace)
        self.cancelled = False
        uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self)
        self.buttonBox.clicked.connect(self._onButtonClicked)

        self._itemToDocument = {}
        for document in documents:
            name = document.fileName()
            if name is None:
                name = 'untitled'
            item = QListWidgetItem( name, self.listWidget )
            if document.filePath() is not None:
                item.setToolTip( document.filePath() )
            item.setCheckState( Qt.Checked )
            self._itemToDocument[item] = document

        # Retitle buttons, add first letter shortcuts for them.
        bb = self.buttonBox
        self._shortcut = (
          self._firstLetterShortcut(bb.Discard, 'close &Without saving'),
          self._firstLetterShortcut(bb.Cancel, '&Cancel close'),
          self._firstLetterShortcut(bb.Save, '&Save checked') )

        self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
示例#13
0
 def createCellWidget(self, qmlDict, attr, count):
     """
     Creates specific widgets for each attribute, which can be a QCombobox, a QLineEdit or a QListWidget.
     """
     if attr in qmlDict.keys():
         enableIgnoreOption = False
         #case the type is dict the cell widget must be a combobox
         if isinstance(qmlDict[attr],dict):
             comboItem = DsgCustomComboBox()
             comboItem.addItems(sorted(qmlDict[attr].keys()))
             self.attributeTableWidget.setCellWidget(count, 1, comboItem)
         #case the type is tuple the cell widget must be a listwidget
         if isinstance(qmlDict[attr],tuple):
             (table, filterKeys) = qmlDict[attr]
             #getting the value relation dictionary used to make the listwidget
             valueRelation = self.makeValueRelationDict(table, filterKeys)
             list = QListWidget()
             for key in valueRelation.keys():
                 listItem = QListWidgetItem(key)
                 listItem.setCheckState(Qt.Unchecked)
                 list.addItem(listItem)
             self.attributeTableWidget.setCellWidget(count, 1, list)
     #this is the normal case, a simple lineedit
     else:
         textItem = QLineEdit()
         self.attributeTableWidget.setCellWidget(count, 1, textItem)
         enableIgnoreOption = True
     #insert here aditional parameters
     self.createAditionalParameters(count, enableIgnoreOption)
示例#14
0
 def load_data_list(self):
     for name in get_data_files(
             Path(CONF.data_root, CONF.current_survey, "Seismics")):
         # only initialize this way can it be set checkable
         new_item = QListWidgetItem(name,
                                    self.control_widget.data_listWidget)
         new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
         new_item.setCheckState(Qt.Unchecked)
示例#15
0
 def update_well_listWidget(self):
     survey_file = CONF.survey_dir / '.survey'
     if survey_file.exists():
         dnames = get_data_files(CONF.well_dir)
         # self.well_listWidget.addItems(dnames)
         for name in dnames:
             new_item = QListWidgetItem(name, self.well_listWidget)
             new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
             new_item.setCheckState(Qt.Unchecked)
	def __init__(self, items=None, parent=None):
		QDialog.__init__(self, parent)
		self.setupUi(self)
		self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
		self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
		if items is not None:
			for item in sorted(items):
				fieldname = QListWidgetItem(QString(item))
				fieldname.setCheckState(Qt.Unchecked)
				self.fieldListWidget.addItem(fieldname)
示例#17
0
 def createEditor(self, parent, option, index):
     # special combobox for field type
     if index.column() == self.column:
         list = QListWidget(parent)
         for item in self.itemsDict:
             listItem = QListWidgetItem(item)
             listItem.setCheckState(Qt.Unchecked)
             list.addItem(listItem)
         return list
     return QItemDelegate.createEditor(self, parent, option, index)
示例#18
0
    def getNewCompo(self, w, cView):
        """Function that finds new composer to be added to the list."""

        nameCompo = cView.composerWindow().windowTitle()
        if not w.findItems(nameCompo, Qt.MatchExactly):
            item = QListWidgetItem()
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            item.setText(nameCompo)
            w.addItem(item)
 def populate_log_listWidget(self):
     self.logs_listWidget.clear()
     well = ppp.Well(
         str(CONF.well_dir /
             ".{}".format(self.well_comboBox.currentText())))
     # self.logs_listWidget.addItems(well.logs)
     for name in well.logs:
         new_item = QListWidgetItem(name, self.logs_listWidget)
         new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
         new_item.setCheckState(Qt.Unchecked)
示例#20
0
 def createEditor(self, parent, option, index):
     # special combobox for field type
     if index.column() == self.column:
         list = QListWidget(parent)
         for item in self.itemsDict:
             listItem = QListWidgetItem(item)
             listItem.setCheckState(Qt.Unchecked)
             list.addItem(listItem)
         return list
     return QItemDelegate.createEditor(self, parent, option, index)
示例#21
0
 def item(icon, fileName):
     """ Add item to the fileList list widget. """
     directory, name = os.path.split(fileName)
     if directory != basedir:
         name += " ({0})".format(os.path.normpath(directory))
     i = QListWidgetItem(KIcon(icon), name, fileList)
     i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable)
     i.ext = os.path.splitext(fileName)[1]
     i.url = KUrl.fromPath(fileName).url()
     i.setCheckState(Qt.Checked if i.ext in exts else Qt.Unchecked)
示例#22
0
    def handleItemChecked(self):
        well_names = []
        for idx in range(self.well_listWidget.count()):
            item = self.well_listWidget.item(idx)
            if item.checkState() == Qt.Checked:
                well_names.append(item.text())
        # first well
        if well_names:
            vlog_list = []
            obp_log_list = []
            nct_list = []
            n_list = []
            first_well = ppp.Well(str(CONF.well_dir / ".{}".format(well_names[0])))
            for log in first_well.logs:
                if "Velocity" in log:
                    vlog_list.append(log)
                if "Overburden" in log:
                    obp_log_list.append(log)
            # for key in first_well.params.keys():
            #     if "nct" in key:
            #         nct_list.append(key)
            #     if "eaton" in key:
            #         n_list.append(key)
            pres_list = ["DST", "MDT", "EMW", "loading", "unloading", "MP"]
            for w_name in well_names:
                well = ppp.Well(str(CONF.well_dir / ".{}".format(w_name)))
                for log in vlog_list:
                    if log not in well.logs:
                        vlog_list.remove(log)
                for log in obp_log_list:
                    if log not in well.logs:
                        obp_log_list.remove(log)
                key_to_remove = []
                for key in pres_list:
                    if key not in well.params.keys():
                        key_to_remove.append(key)
                for key in key_to_remove:
                    pres_list.remove(key)

            self.velocity_comboBox.clear()
            self.velocity_comboBox.addItems(vlog_list)
            self.obp_comboBox.clear()
            self.obp_comboBox.addItems(obp_log_list)
            # self.nct_comboBox.clear()
            # self.nct_comboBox.addItems(nct_list)
            # self.n_comboBox.clear()
            # self.n_comboBox.addItems(n_list)

            self.pres_listWidget.clear()
            for name in pres_list:
                new_item = QListWidgetItem(name, self.pres_listWidget)
                new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
                new_item.setCheckState(Qt.Unchecked)
        else:
            self.pres_listWidget.clear()
 def _load_labels(self):
     self.LabelsListWidget.clear()
     if self.selected_provider:
         labels = self.selected_provider.get_labels()
         for label in labels:
             icon = utils.colored_icon(label['color'])
             item = QListWidgetItem(icon, label['name'], self.LabelsListWidget)
             item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
             item.setCheckState(Qt.Unchecked)
             self.LabelsListWidget.addItem(item)
         self.LabelsListWidget.sortItems()
示例#24
0
 def populate_entities_widget(self):
     """
     Add entities in the instance file into a list view widget
     """
     self.lst_widget.clear()
     entities = self.instance_entities()
     if len(entities) > 0:
         for entity in entities:
             list_widget = QListWidgetItem(
                 current_profile().entity_by_name(entity).short_name, self.lst_widget)
             list_widget.setCheckState(Qt.Checked)
示例#25
0
 def populate_entities_widget(self):
     """
     Add entities in the instance file into a list view widget
     """
     self.lst_widget.clear()
     entities = self.instance_entities()
     if len(entities) > 0:
         for entity in entities:
             list_widget = QListWidgetItem(
                 current_profile().entity_by_name(entity).short_name, self.lst_widget)
             list_widget.setCheckState(Qt.Checked)
示例#26
0
 def on_domainListWidget_currentRowChanged(self, idx):
     curItem = self.domainListWidget.item(idx)
     self.filterListWidget.clear()
     if curItem:
         self.domainName = curItem.data(0)
         self.domainDict = self.abstractDb.getDomainDictV2('dominios.'+self.domainName)
         for codeName in self.domainDict.keys():
             newItem = QListWidgetItem(codeName)
             newItem.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable)
             newItem.setCheckState(QtCore.Qt.Unchecked)
             self.filterListWidget.addItem(newItem)
示例#27
0
 def showAttr(self):
     self.dlg.attributeList.clear()
     current = self.dlg.fileListWidget.currentItem()
     attributes = current.attributes
     for attr in attributes:
         item = QListWidgetItem(attr[0], self.dlg.attributeList)
         item.setFlags(item.flags() & ~Qt.ItemIsSelectable)
         if attr[1] == 0:
             item.setCheckState(Qt.Unchecked)
         else:
             item.setCheckState(Qt.Checked)
         self.dlg.attributeList.addItem(item)
示例#28
0
 def update_horizon_listWidget(self):
     self.horizon_listWidget.clear()
     well_name = self.well_comboBox.currentText()
     well = ppp.Well(str(CONF.well_dir / ".{}".format(well_name)))
     try:
         horizons = well.params['horizon'].keys()
         for name in horizons:
             new_item = QListWidgetItem(name, self.horizon_listWidget)
             new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
             new_item.setCheckState(Qt.Unchecked)
     except KeyError as e:
         print(e.message)
示例#29
0
    def initializePage(self):
        super(InterfacePage, self).initializePage()
        self.lw_interface.clear()
        exsits = []
        for key in app.g_configurations.interfaces:
            if app.g_configurations.interfaces[key]:
                exsits.append(key)

        for interface in app.g_configurations.config['interfaces']:
            # name + description
            display = interface['name'] + ' (' + interface['description'] + ')'
            # print display
            # litem = QListWidgetItem(interface['name'])
            litem = QListWidgetItem(display)
            litem.setToolTip(interface['description'])
            litem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)

            isdefault = False
            isUseable = True

            if app.g_configurations.component_type == "window":
                if interface['flag_win'] == 3:  #必须实现
                    isdefault = True
                    litem.setFlags(Qt.ItemIsUserCheckable)
                elif interface['flag_win'] == 2:  #可选并选中
                    isdefault = True
                elif interface['flag_win'] == 1:  #可选并不选
                    isdefault = False
                else:  #不需实现
                    isUseable = False
            else:
                if interface['flag_service'] == 3:
                    isdefault = True
                    litem.setFlags(Qt.ItemIsUserCheckable)
                elif interface['flag_service'] == 2:
                    isdefault = True
                elif interface['flag_service'] == 1:
                    isdefault = False
                else:
                    isUseable = False

            if app.g_configurations.initialized:
                if interface['name'] in exsits:
                    isdefault = True
                else:
                    isdefault = False

            if isdefault:
                litem.setCheckState(Qt.Checked)
            else:
                litem.setCheckState(Qt.Unchecked)
            if isUseable:
                self.lw_interface.addItem(litem)
示例#30
0
    def insertCheckableItem(self, index, label, state, isBonus=False):
        """
		Fügt einen Eintrag an der angegebenen Indexposition ein.
		"""

        item = QListWidgetItem()
        item.setText(label)
        item.setCheckState(state)
        if isBonus:
            item.setData(Qt.ForegroundRole, QColor(Config.COLOR_BONUS))
            item.setFlags(item.flags() & Qt.ItemIsUserCheckable)
        self.insertItem(index, item)
 def create_plugin_view(self, showAll = True):
     for p_name, p_info in self.p_info.iteritems():
         item = QListWidgetItem(p_info["name"], self.ui.pluginView)
         item.setToolTip(p_name)
         item.setCheckState(Qt.Checked if p_info["activated"] else Qt.Unchecked)
         if p_info["forced"]:
             item.setForeground(Qt.gray)
             flags = item.flags()
             flags &= ~Qt.ItemIsUserCheckable
             item.setFlags(flags)
         
         item.setHidden(not showAll and p_info["forced"])
         self.ui.pluginView.addItem(item)
示例#32
0
 def restoreSettings(self):
     s = QSettings()
     n = s.beginReadArray('EMailList')
     print "n=", n
     for i in range(n):
         s.setArrayIndex(i)
         checked = s.value('Checked', Qt.Checked, type=Qt.CheckState)
         address = s.value('EMail', '', type=QString)
         print i, checked, address
         item = QListWidgetItem(address)
         item.setCheckState(checked)
         self.emailListWidget.insertItem(0, item)
     s.endArray()
示例#33
0
    def initializePage(self):
        super(InterfacePage, self).initializePage()
        exsits = []
        for key in app.g_configurations.interfaces:
            if app.g_configurations.interfaces[key]:
                exsits.append(key)

        for interface in app.g_configurations.config['interfaces']:
            litem = QListWidgetItem(interface['name'])
            litem.setToolTip(interface['description'])
            litem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if app.g_configurations.initialized:
                if interface['name'] in exsits:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            else:
                isdefault = False
                if app.g_configurations.component_type == "window":
                    if interface['default'] & 2:
                        isdefault = True
                else:
                    if interface['default'] & 1:
                        isdefault = True
                if isdefault:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            self.lw_interface.addItem(litem)
示例#34
0
 def updateOrder(self):
     self.listbox.clear()
     self.macros = self.loadMacros()
     cparser = PuddleConfig()
     to_check = cparser.get('actions', 'checked', [])
     for i, m in sorted(self.macros.items()):
         func_name = m.name
         item = QListWidgetItem(func_name)
         item.setFlags(item.flags() | Qt.ItemIsEditable)
         if func_name in to_check:
             item.setCheckState(Qt.Checked)
         else:
             item.setCheckState(Qt.Unchecked)
         self.listbox.addItem(item)
示例#35
0
    def initializePage(self):
        super(InterfacePage, self).initializePage()
        exsits = []
        for key in app.g_configurations.interfaces:
            if app.g_configurations.interfaces[key]:
                exsits.append(key)

        for interface in app.g_configurations.config['interfaces']:
            litem = QListWidgetItem(interface['name'])
            litem.setToolTip(interface['description'])
            litem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if app.g_configurations.initialized:
                if interface['name'] in exsits:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            else:
                isdefault = False
                if app.g_configurations.component_type == "window":
                    if interface['default'] & 2:
                        isdefault = True
                else:
                    if interface['default'] & 1:
                        isdefault = True
                if isdefault:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            self.lw_interface.addItem(litem)
示例#36
0
        def addListItem(self, component, title, valid=True, checked=True):
            item = QListWidgetItem(title)
            item.component = component
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            if valid:
                pass
            else:
                item.setForeground(QColor('gray'))

            if checked:
                item.setCheckState(Qt.Checked)
            else:
                item.setCheckState(Qt.Unchecked)

            self.components_list.addItem(item)
示例#37
0
  def __init__(self, name = None, attributes = [], selectedAttributes = []):
     QListWidget.__init__(self)
     self.menu = AttributeSelectorMenu(self)
     self.setSelectionMode(QAbstractItemView.ExtendedSelection)
     if name:
       self.name = name
     self.attributes = attributes
     for attribute in self.attributes:
	item = QListWidgetItem(attribute)
	item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
	if attribute in selectedAttributes:
          item.setCheckState(Qt.Checked)
	else:
	   item.setCheckState(Qt.Unchecked)
	self.addItem(item)
示例#38
0
    def update_pres_listWidget(self):
        pres_list = ["DST", "MDT", "EMW", "loading", "unloading", "MP"]
        well_name = self.well_comboBox.currentText()
        well = ppp.Well(str(CONF.well_dir / ".{}".format(well_name)))
        key_to_remove = []
        for key in pres_list:
            if key not in well.params.keys():
                key_to_remove.append(key)
        for key in key_to_remove:
            pres_list.remove(key)

        self.pres_listWidget.clear()
        for name in pres_list:
            new_item = QListWidgetItem(name, self.pres_listWidget)
            new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
            new_item.setCheckState(Qt.Unchecked)
示例#39
0
 def profile_instance_entities(self):
     """
     Add the user entities that are in the form to be imported into database
     into a list view widget
     :return: model
     """
     self.lst_widget.clear()
     entity_list = self.instance_entities()
     if entity_list is not None and len(entity_list) > 0:
         for entity in entity_list:
             list_widget = QListWidgetItem(
                 current_profile().entity_by_name(entity).short_name,
                 self.lst_widget)
             list_widget.setCheckState(Qt.Checked)
     else:
         return
示例#40
0
    def set_project_id(self, prjId = None):
        self.sectionListWidget.clear()

        if prjId is not None:
            self.projectId = prjId

        if self.projectId is None:
            return

        for s_id, section in self.data[prjId]['Sections'].items():
            title = '{0}: de {1} a {2}'.format(section['Counter'], section['StartNode'], section['EndNode'])
            item = QListWidgetItem(warning_icon, title)
            item.setData(Qt.UserRole, s_id)
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Checked if section['Import'] else Qt.Unchecked)
            self.sectionListWidget.addItem(item)
        self.update_status()
示例#41
0
    def modelChanged(self):
        self.list.clear()

        items = self.model.getList()

        for item in items:
            list_item = QListWidgetItem(item)
            list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)

            if self.model.isValueSelected(item):
                list_item.setCheckState(Qt.Checked)
            else:
                list_item.setCheckState(Qt.Unchecked)

            self.list.addItem(list_item)

        self.filterList(self.search_box.filter())
示例#42
0
    def modelChanged(self):
        self._list.clear()

        items = self._model.getList()

        for item in items:
            list_item = QListWidgetItem(item)
            list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)

            if self._model.isValueSelected(item):
                list_item.setCheckState(Qt.Checked)
            else:
                list_item.setCheckState(Qt.Unchecked)

            self._list.addItem(list_item)

        self.filterList(self._search_box.filter())
示例#43
0
	def __init__(self, key, exper, asm, primer_data=None, parent=None):
		"""Requires key, experiment, an opened assembly window and primers
		dictionary of the format

		primer_data = {primer_name: {"status": "Repeat", "position": (10, 40)}}

		"""
		super(Window, self).__init__(parent)
		self.setupUi(self)
		self.setWindowTitle("Iterate CRISPR {0}".format(__version__))
		if primer_data is None:
			primer_data = {}
		self.primer_data = primer_data
		self.key = key
		self.exper = exper
		self.keyLabel.setText(key)
		self.experLabel.setText(exper)
		self.asm = asm

		self.stopButton.clicked.connect(stop)
		self.skipButton.clicked.connect(self.close)
		self.selectAllButton.clicked.connect(self.selectAll)
		self.selectNoneButton.clicked.connect(self.selectNone)
		self.finishedButton.clicked.connect(self.saveFinished)
		self.unfinishedButton.clicked.connect(self.saveUnfinished)
		self.recalculateButton.clicked.connect(self.recalculate)
		self.exportButton.clicked.connect(self.exportDatabase)
		self.listWidget.itemChanged.connect(self.itemChanged)

		for content in self.primer_data.keys():
			item = QListWidgetItem(content, self.listWidget)
			if self.primer_data[content]["status"] == "Repeat":
				item.setCheckState(Qt.Checked)
			else:
				item.setCheckState(Qt.Unchecked)
		self.listWidget.itemDoubleClicked.connect(self.selectInAssembler)

		# restore main window state
		settings = QSettings()
		size = settings.value("Window/Size", QVariant(QSize(600, 500))).toSize()
		self.resize(size)
		position = settings.value("Window/Position",
								QVariant(QPoint(0, 0))).toPoint()
		self.move(position)
		self.restoreState(settings.value("Window/State").toByteArray())
		QTimer.singleShot(6000, self.hideHint)
示例#44
0
	def __addListItems(self):
		i = 0
		for key in self.__statistics.keys():
			name = self.sender().getProjectName(key)
			if name is None:
				name = key
			color = self.__colors[i]

			item = QListWidgetItem(name)
			item.setData(Qt.DecorationRole, QVariant(QColor(color)))
			item.setData(Qt.UserRole, QVariant(key))
			item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
			item.setCheckState(Qt.Checked)
			self.__projectsList.addItem(item)

			i = i + 1
			if i >= len(self.__colors):
				i = 0
示例#45
0
    def __init__(self, fieldNames):
        QDialog.__init__(self)

        self.ui = Ui_FieldChooser()
        self.ui.setupUi(self)

        self.items = []
        self.ui.fieldList.clear()
        for fieldName in fieldNames:
            item = QListWidgetItem()
            item.setText(fieldName)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            self.ui.fieldList.addItem(item)
            self.items.append(item)

        QObject.connect(self.ui.unselectAll, SIGNAL("clicked()"),
                        self.unselectAll)
        QObject.connect(self.ui.selectAll, SIGNAL("clicked()"), self.selectAll)
示例#46
0
    def showRequest(self, task):
        req = task.getRequest()
        self.task = task

        self.label_remote.setText(req['meta']['remote'])
        self.label_transport.setText(req['meta']['scheme'])
        self.label_local.setText(req['meta']['local'])

        accounts = req['accounts']
        for a in accounts:
            addr = a['address']
            typ = a['type']
            url = a['url']
            item = QListWidgetItem(addr)
            item.setCheckState(Qt.Checked)
            item.setData(Qt.StatusTipRole, "{} {}".format(typ, url))
            self.accountListWidget.addItem(item)

        self.window.show()
示例#47
0
    def __init__(self, fieldNames):
        QDialog.__init__(self)

        self.ui = Ui_FieldChooser()
        self.ui.setupUi(self)

        self.items = []
        self.ui.fieldList.clear()
        for fieldName in fieldNames:
            item = QListWidgetItem()
            item.setText(fieldName)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            self.ui.fieldList.addItem(item)
            self.items.append(item)

        QObject.connect(self.ui.unselectAll,
                SIGNAL("clicked()"), self.unselectAll)
        QObject.connect(self.ui.selectAll,
                SIGNAL("clicked()"), self.selectAll)
示例#48
0
    def add_ladspa_settings(self, dialog):
        self.ladspa_settings_page = QWidget()
        layout = QGridLayout()
        self.ladspa_settings_page.setLayout(layout)

        text = i18n("LADSPA is a standard for handling audio filters and effects. Every linux software archive offers a large number of effects - search for LADSPA to get more.\
            Not every effect is supported by Pulseaudio and others simple don't make sense (or create only noise).<br/><br/>\
            The following list shows all available effects on your system: Only checked effects will appear in the context-menu.")

        if not LADSPAEffects().ladspa_sdk_available():
            text = text + i18n("<br/><br/><b>Warning:</b> Cannot find the executables 'listplugins' and 'analyseplugin' which are required for dynamically detecting installed effects.<br/>\
               In OpenSUSE, Fedora and Arch Linux the package is named 'ladspa', in Debian/Ubuntu 'ladspa-sdk'.<br/><br/>")

        ladspa_intro = QLabel(text)

        ladspa_intro.setWordWrap(True)
        layout.addWidget(ladspa_intro, 0,0)

        self.ladspa_enabled_checkbox = QCheckBox()
        self.ladspa_enabled_checkbox.setText(i18n("Enable LADSPA effects."))
        self.ladspa_enabled_checkbox.setChecked(self.is_ladspa_enabled())
        self.ladspa_enabled_checkbox.stateChanged.connect(dialog.settingsModified)
        layout.addWidget(self.ladspa_enabled_checkbox, 1,0)

        self.effects_list_widget = QListWidget()
        layout.addWidget(self.effects_list_widget,2,0)
        self.effects_list_widget.itemClicked.connect(dialog.settingsModified)

        blacklisted = LADSPAEffects().blacklist()
        effects = LADSPAEffects().all_effects()
        for effect in effects:
            item = QListWidgetItem(effect["preset_name"])
            item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if effect["preset_name"] in blacklisted:
                item.setCheckState(Qt.Unchecked)
            else:
                item.setCheckState(Qt.Checked)
            self.effects_list_widget.addItem(item)

        layout.addItem(QSpacerItem(0,0, QSizePolicy.Minimum,QSizePolicy.Expanding), 3,0)
        dialog.addPage(self.ladspa_settings_page, i18n("Effects / Equalizer"), "preferences-desktop-sound")
 def __add_gstke(self, filter):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     try:
         self.ui.LST_GSTKE.clear()
         #show them sorted
         for gst, props in sorted(self.gstke.iteritems()):
             item = None
             if gst == 'EXCEPTION':
                 item = QListWidgetItem(props)
             else:
                 if filter in gst:
                     item = QListWidgetItem(gst)
                     item.setData(Qt.UserRole, props)
                     if props != 'FEHLER':
                         item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                         #important! won't work otherwise
                         item.setCheckState(Qt.Unchecked)
             if not item is None:
                 self.ui.LST_GSTKE.addItem(item)
     finally:
         QApplication.restoreOverrideCursor()
示例#50
0
    def __init__(self, workspace, documents):
        super(_UISaveFiles, self).__init__(workspace)
        self.cancelled = False
        uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self)
        self.buttonBox.clicked.connect(self._onButtonClicked)

        self._itemToDocument = {}
        for document in documents:
            name = document.fileName()
            if name is None:
                name = 'untitled'
            item = QListWidgetItem( name, self.listWidget )
            if document.filePath() is not None:
                item.setToolTip( document.filePath() )
            item.setCheckState( Qt.Checked )
            self._itemToDocument[item] = document
        self.buttonBox.button(self.buttonBox.Discard).setText(self.tr('Close &without Saving'))
        self.buttonBox.button(self.buttonBox.Cancel).setText(self.tr('&Cancel Close'))
        self.buttonBox.button(self.buttonBox.Save).setText(self.tr('&Save checked'))

        self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
    def showAttributes(self):
        """ List unique values of the selected field from source layer and show them in widget"""
        if not self.checkExistingVector():
            return
        listAttr = []
        self.dlg.valuesList.clear()
        lyr = myLayers[self.dlg.srcLayer.currentIndex()]
        
        for feature in lyr.getFeatures():
            # attrs = feature.attributes()
            attr = feature.attributes()[self.dlg.fltField.currentIndex()]
            if attr not in listAttr:
                listAttr.append(attr)
        listAttr.sort()

        for value in listAttr:
            value = str(value)
            item = QListWidgetItem()
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            item.setText(value)
            self.dlg.valuesList.addItem(item)
 def resultitemchanged(self, new_item):
     self.IDC_textDetails.setText("")
     self.IDC_listRessources.clear()
     self.IDC_plainTextLink.clear()
     if new_item is None:
         return
     package = new_item.data(Qt.UserRole)
     self.cur_package = package
     if package is None:
         return
     self.IDC_textDetails.setText(
         u"{0}\n\n{1}\n{2}\n\n{3}".format(
             package.get("notes", "no notes"),
             package.get("author", "no author"),
             package.get("author_email", "no author_email"),
             package.get("license_id", "no license_id"),
         )
     )
     if package.get("num_resources", 0) > 0:
         for res in package["resources"]:
             item = QListWidgetItem(u"{0}: {1}".format(res.get("format", "no format"), res.get("name", "no name")))
             item.setData(Qt.UserRole, res)
             item.setCheckState(Qt.Unchecked)
             self.IDC_listRessources.addItem(item)
    def window_loaded(self):
        try:
            self.util.msg_log('window_loaded')
            self.util.msg_log('before stop')
            self.timer.stop()
            self.timer = None
            self.util.msg_log('before get_groupds')
            ok, result = self.cc.get_groups()
            if ok is False:
                QApplication.restoreOverrideCursor()
                self.util.dlg_warning(result)
                return

            if not result:
                self.list_all_clicked()
            else:
                for entry in result:
                    item = QListWidgetItem(entry['display_name'])
                    item.setData(Qt.UserRole, entry)
                    #item.setCheckState(Qt.Checked)
                    item.setCheckState(Qt.Unchecked)
                    self.IDC_listGroup.addItem(item)
        finally:
            QApplication.restoreOverrideCursor()
示例#54
0
    def initExtList(self):
        extset=set(self.parent().settings.extensions)
        #for easier performance in checking
        for ext in self.parent().settings.extensions:
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Checked)

        for ext in self.parent().settings.faulty_exts:
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setBackground(QBrush(QColor('red')))
            item.setForeground(QBrush(QColor('black')))
            item.setCheckState(Qt.Checked)

        for ext in allMDExtensions():
            if ext in extset: continue
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
示例#55
0
文件: qwms.py 项目: adamczi/QWMS
class QWMS:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'QWMS_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference, window on top
        self.dlg = QWMSDialog(self.iface.mainWindow())

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&QWMS')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'QWMS')
        self.toolbar.setObjectName(u'QWMS')

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('QWMS', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/QWMS/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Get WMS'),
            callback=self.run,
            parent=self.iface.mainWindow())


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&QWMS'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def approveChoice(self, i):
        """Returns index of WMS service"""
        self.dlg.textEdit.clear()
        self.selectedWMSIndex = self.dlg.comboBox.currentIndex()
        return self.selectedWMSIndex       

    def selectedChoice(self):
        """Gets layers of selected WMS"""
        
        ## Execute GetCapabilities
        if self.dlg.comboBox.currentIndex() == len(wmsList): # if GDOS
            url_to_wms_getcaps = wms_getcap_gdos
        else:            
            service = wmsLinks[self.dlg.comboBox.currentIndex()] # else
            url_to_wms_getcaps = wms_getcap_geop % (service)

        ## Read the XML
        try:
            tree = ET.parse(urllib2.urlopen(url_to_wms_getcaps))
        except: 
            self.dlg.textEdit.setPlainText('Server error')
        root = tree.getroot()

        self.layerDict = {} # User-friendly names
        self.layerDictURL = {} # Names that URL parses

        ## Choose proper path and get available layers to dict
        ## depending on XML structure
        layerID = 0 
     
        if root.findall(xmlStructureURL_3):
            for layer in root.findall(xmlStructureURL_3):
                if layer.tag == layerTagTitle:
                    self.layerDict[layerID-1] = (layer.text)
                if layer.tag == layerTagName:
                    self.layerDictURL[layerID] = (layer.text)
                layerID += 1            
        else: 
            if root.findall(xmlStructureURL_2):
                for layer in root.findall(xmlStructureURL_2):
                    if layer.tag == layerTagTitle:
                        self.layerDict[layerID-1] = (layer.text)
                    if layer.tag == layerTagName:
                        self.layerDictURL[layerID] = (layer.text)
                        layerID += 1            
            else:
                if root.findall(xmlStructureURL_1):
                    for layer in root.findall(xmlStructureURL_1):
                        if layer.tag == layerTagTitle:
                            self.layerDict[layerID-1] = (layer.text)
                        if layer.tag == layerTagName:
                            self.layerDictURL[layerID] = (layer.text)
                            layerID += 1
                else:
                    if root.findall(xmlStructureURL_4):
                        for layer in root.findall(xmlStructureURL_4):
                            if layer.tag == layerTagTitle:
                                self.layerDict[layerID-1] = (layer.text)
                            if layer.tag == layerTagName:
                                self.layerDictURL[layerID] = (layer.text)
                            layerID += 1       
                    else:
                        self.iface.messageBar().pushMessage("Error", "Unknown metadata structure", level=QgsMessageBar.WARNING, duration=3)
            
        ## Gets available layers and adds them as checkboxes
        self.dlg.listWidget.clear()
        self.dlg.listWidget.setVisible(True)  
        for key, value in self.layerDict.iteritems():
            self.layerToSelect = QListWidgetItem()
            self.layerToSelect.setText(value)
            self.layerToSelect.setFlags(self.layerToSelect.flags() | QtCore.Qt.ItemIsUserCheckable)
            if len(self.layerDict) <= 1: # if only one layer available
                self.layerToSelect.setCheckState(QtCore.Qt.Checked)
                self.dlg.listWidget.addItem(self.layerToSelect)
                self.dlg.listWidget.setEnabled(False)    
            else: # if more than one available
                self.layerToSelect.setCheckState(QtCore.Qt.Unchecked)
                self.dlg.listWidget.addItem(self.layerToSelect)
                self.dlg.listWidget.setEnabled(True) 
                self.dlg.pushButton_3.setEnabled(True)          
        self.dlg.pushButton_2.setEnabled(True)
        return

    def iterate(self):
        """Checks which layers have been selected and returns them"""
        self.items = []
        self.countChecked = 0
        for index in xrange(self.dlg.listWidget.count()):
            if self.dlg.listWidget.item(index).checkState() == QtCore.Qt.Checked:
                self.countChecked += 1
                self.items.append(self.dlg.listWidget.item(index).text())

        ## Get IDs of chosen layers to query it from listDictURL dict
        self.keysIDs = []
        self.keysURL = []
        self.indexStyles = []
        for i in self.items:
            for key, value in self.layerDict.iteritems():
                if i == value:
                    self.keysIDs.append(key)

        ## Create 'styles' part of WMS URL depending on number of layers chosen
        for i in self.keysIDs:
            for key, value in self.layerDictURL.iteritems():
                if i == key:
                    self.keysURL.append(value)
                    self.indexStyles.append(wms_styles)
        return self.items

    def textBox(self):
        """Shows URL to be queried in the text box"""
        ## Gets current EPSG
        canvas = self.iface.mapCanvas()
        currentEPSG = canvas.mapRenderer().destinationCrs().authid()
        if currentEPSG not in availableEPSG:
            currentEPSG = 'EPSG:4326'

        ## Get part of WMS URL corresponding to selected service
        if self.dlg.comboBox.currentIndex() == len(wmsList):
            wms_url = wms_url_gdos
        else:            
            service = wmsLinks[self.dlg.comboBox.currentIndex()]
            wms_url = wms_url_geop % (service)

        self.iterate()

        ## If more than one layer selected
        if self.countChecked > 1:
            for selectedLayer in self.keysURL:
                indexLayers = '&layers='.join(self.keysURL)
                indexStyles = '&'.join(self.indexStyles)

            self.urlWithParams = wms_separator.join((wms_url,
                                                wms_format,
                                                wms_layers
                                                 + indexLayers,
                                                indexStyles,
                                                wms_crs
                                                + currentEPSG))

        ## If one layer selected
        elif self.countChecked == 1:
            for selectedLayer in self.keysURL:
                indexLayers = self.keysURL[0]

            self.urlWithParams = wms_separator.join((wms_url,
                                    wms_format,
                                    wms_layers
                                     + indexLayers,
                                    wms_styles,
                                    wms_crs
                                    + currentEPSG))
        else:
            self.urlWithParams = 'Error'

        ## Insert URL to be queried in TextBox
        self.dlg.textEdit.setPlainText(self.urlWithParams)

        return self.urlWithParams

    def selectAllNone(self):
        """Selects or deselects all layers in checkbox list"""
        if self.dlg.listWidget.item(0).checkState() == QtCore.Qt.Unchecked:
            for index in xrange(self.dlg.listWidget.count()):
                self.dlg.listWidget.item(index).setCheckState(QtCore.Qt.Checked)
        else:
            for index in xrange(self.dlg.listWidget.count()):
                self.dlg.listWidget.item(index).setCheckState(QtCore.Qt.Unchecked)

    def run(self):      
        """ Run the plugin """        
        self.dlg.pushButton_2.setEnabled(False)
        self.dlg.pushButton_3.setEnabled(False)
        ## Show the dialog
        self.dlg.show()

        ## Add services to the list:
        if self.dlg.comboBox.count() == 0:
            self.dlg.comboBox.addItems(wmsList)
            self.dlg.comboBox.insertSeparator(39)

        ## Refreshes window after changing service
        self.dlg.comboBox.currentIndexChanged.connect(self.approveChoice)

        ## Get layers of selected service
        self.dlg.pushButton.clicked.connect(self.selectedChoice)

        ## Select all/none layers
        self.dlg.pushButton_3.clicked.connect(self.selectAllNone)

        ## Get WMS address to be queried
        self.dlg.pushButton_2.clicked.connect(self.textBox)

        ## Run the dialog event loop
        result = self.dlg.exec_()       

        ## After pressing OK do
        if result:      
            if self.dlg.textEdit.toPlainText() == '':
                self.textBox() # If Get WMS URL is not clicked

            finalURL = self.dlg.textEdit.toPlainText()
            if finalURL != 'Error':
            ## Add layer(s)
                if self.dlg.comboBox.currentIndex() == len(wmsList): # if GDOS
                    rlayer = QgsRasterLayer(finalURL, wmsList[39], 'wms')
                else:            
                    rlayer = QgsRasterLayer(finalURL, wmsList[self.dlg.comboBox.currentIndex()], 'wms')

                if not rlayer.isValid():
                     self.iface.messageBar().pushMessage("Error", "Layer failed to load", level=QgsMessageBar.WARNING, duration=3)
                else:
                    QgsMapLayerRegistry.instance().addMapLayer(rlayer)
            else:
                self.iface.messageBar().pushMessage("Error", "Error in querying available layers", level=QgsMessageBar.WARNING, duration=3)