def generate_tree_model(self, data_dict):
        """Generate a tree model for specified dictionary

        :param data_dict: A dictionary
        :type data_dict: dict
        :return: list of QTreeWidgetItem
        :rtype list:
        """
        widget_items = []
        font = QFont()
        font.setBold(True)
        for key in data_dict.keys():
            entry = data_dict[key]
            key_item = QTreeWidgetItem()
            key_item.setText(0, str(key))
            key_item.setFont(0, font)
            if isinstance(entry, dict):
                items = self.generate_tree_model(entry)
                key_item.addChildren(items)
            else:
                # value_item = QTreeWidgetItem()
                key_item.setText(1, str(entry))
                key_item.setFlags(key_item.flags() | Qt.ItemIsEditable)
                # key_item.addChild(key_item)
            widget_items.append(key_item)

        return widget_items
Пример #2
0
    def generate_tree_model(self, data_dict):
        """Generate a tree model for specified dictionary

        :param data_dict: A dictionary
        :type data_dict: dict
        :return: list of QTreeWidgetItem
        :rtype list:
        """
        widget_items = []
        font = QFont()
        font.setBold(True)
        for key in data_dict.keys():
            entry = data_dict[key]
            key_item = QTreeWidgetItem()
            key_item.setText(0, str(key))
            key_item.setFont(0, font)
            if isinstance(entry, dict):
                items = self.generate_tree_model(entry)
                key_item.addChildren(items)
            else:
                # value_item = QTreeWidgetItem()
                key_item.setText(1, str(entry))
                key_item.setFlags(key_item.flags() | Qt.ItemIsEditable)
                # key_item.addChild(key_item)
            widget_items.append(key_item)

        return widget_items
Пример #3
0
    def buildParentItem(self, dcollection, title, rootresource):
        '''
        Builds tree widget items from a dictionary.
        '''
        rtItem = QTreeWidgetItem()
        rtItem.setText(0, title)
        rtItem.setIcon(0, QIcon(rootresource))

        topLevelItems = []

        for k, v in dcollection.iteritems():
            parentItem = QTreeWidgetItem()

            if isinstance(v, dict):
                parentItem.setText(0, k)

                for kc, vc in v.iteritems():
                    child = QTreeWidgetItem()
                    child.setText(0, self._combine(kc, vc))
                    parentItem.addChild(child)

            else:
                parentItem.setText(0, self._combine(k, v))

            topLevelItems.append(parentItem)

        rtItem.addChildren(topLevelItems)
        rtItem.setExpanded(True)

        return rtItem
Пример #4
0
 def treeMenuSetupRecur(self, curStruct, parent=None):
     item = QTreeWidgetItem(parent)
     item.setText(0, curStruct["text"])
     if "flags" in curStruct:
         item.setFlags(curStruct["flags"])
     if "children" in curStruct:
         children = []
         for child in curStruct["children"]:
             children.append(self.treeMenuSetupRecur(child, item))
         item.addChildren(children)
     if "expanded" in curStruct:
         print(curStruct["expanded"])
         item.setExpanded(curStruct["expanded"])
         print(item.isExpanded())
     return item
Пример #5
0
    def buildParentItem(self,dcollection,title,rootresource):
        '''
        Builds tree widget items from a dictionary.
        '''
        rtItem = QTreeWidgetItem()
        rtItem.setText(0,title)
        rtItem.setIcon(0,QIcon(rootresource))
            
        topLevelItems = []
            
        for k,v in dcollection.iteritems():
            parentItem = QTreeWidgetItem()
                
            if isinstance(v,dict):                                                
                parentItem.setText(0,k)
                    
                for kc,vc in v.iteritems():
                    child = QTreeWidgetItem()
                    child.setText(0,self._combine(kc, vc))
                    parentItem.addChild(child)
                
            else:
                parentItem.setText(0,self._combine(k, v))                
                    
            topLevelItems.append(parentItem)
                
        rtItem.addChildren(topLevelItems)
        rtItem.setExpanded(True)
        
        return rtItem

        
        
        
        
        
        
        
        
        
        
        
        
Пример #6
0
 def display(self):
     '''
     Initialize top-level items
     '''
     if len(self.items) == 0:
         return
 
     self.tree.clear()
     
     #If there is only one item then set it as the root item
     if len(self.items) == 1:
         rootItem = self.items[0]
         
         #Set root font
         rtFont = rootItem.font(0)
         rtFont.setBold(True)
         rootItem.setFont(0,rtFont)
         
         #Add the tree item to the tree widget
         self.tree.addTopLevelItem(rootItem)
         rootItem.setExpanded(True)
         
     else:
         rootItem = QTreeWidgetItem(self.tree)
         rootItem.setText(0,self.title)
         rootItem.setIcon(0,QIcon(self.rootResource))
         
         #Set root font
         rtFont = rootItem.font(0)
         rtFont.setBold(True)
         rootItem.setFont(0,rtFont)
         
         rootItem.addChildren(self.items)
         rootItem.setExpanded(True)
     
     #Force the horizontal scrollbar to show
     self.tree.header().setResizeMode(QHeaderView.ResizeToContents)
Пример #7
0
    def display(self):
        '''
        Initialize top-level items
        '''
        if len(self.items) == 0:
            return

        self.tree.clear()

        #If there is only one item then set it as the root item
        if len(self.items) == 1:
            rootItem = self.items[0]

            #Set root font
            rtFont = rootItem.font(0)
            rtFont.setBold(True)
            rootItem.setFont(0, rtFont)

            #Add the tree item to the tree widget
            self.tree.addTopLevelItem(rootItem)
            rootItem.setExpanded(True)

        else:
            rootItem = QTreeWidgetItem(self.tree)
            rootItem.setText(0, self.title)
            rootItem.setIcon(0, QIcon(self.rootResource))

            #Set root font
            rtFont = rootItem.font(0)
            rtFont.setBold(True)
            rootItem.setFont(0, rtFont)

            rootItem.addChildren(self.items)
            rootItem.setExpanded(True)

        #Force the horizontal scrollbar to show
        self.tree.header().setResizeMode(QHeaderView.ResizeToContents)
Пример #8
0
	def __loadModules(self):
		# init variables
		loadOrder = ["hidden", "setting", "application"]

		currentDir = os.path.abspath(os.curdir)
		modulesPath = currentDir + "/" + self.__v_modulePath
		content = os.listdir(modulesPath)
		content.sort()
		modules = []
		moduleNames = []
		
		# clear gui list
		self.__p_selectModule.treeWidgetModules.reset()
		itemList = {"hidden": [], "setting": [], "application": []}

		# search for modules in module order
		index = 0
		for moduleClassType in loadOrder:
			# find modules
			for name in content:
				# only direcotries without .* and ..
				if (not os.path.isdir(modulesPath + name) or re.match("^\.", name)):
					continue
				# end if
				
				# don't load modules twice
				if (name in moduleNames):
					continue
				# end if

				m = re.match("^(\d+)(.*)$", name)
				suffix = ""
				if (m):
					suffix = m.group(1)
					name = m.group(2)
				# end if

				# change into module directory
				moduleDir = modulesPath + suffix + name
				os.chdir(moduleDir)

				# import module
				fullpath_to_py = moduleDir + "/" + name + ".py"
				if not os.path.isfile(fullpath_to_py):
					continue
				# end if
				
				modHandle = imp.load_source(name, fullpath_to_py)

				# switch back to main directory
				os.chdir(currentDir)

				# auf klasse pruefen
				if (moduleClassType + "ModuleClass" in dir(modHandle)):
					moduleNames.append(suffix+name)
					
					# search for dependencies
					dependencies = ""
					dependenciyList = list()
					if ("dependencies" in dir(modHandle)):
						dependenciyList = modHandle.dependencies
						for d in modHandle.dependencies:
							dependencies += d + ", "
						# end for
						
						dependencies = dependencies[0:len(dependencies) - 2]
					# end if
					item = QTreeWidgetItem([name, dependencies])
					item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
					
					path = modulesPath + suffix + name
					path = re.sub(r'[\\/]+', '/', path)
					module = {"name" : name, "modHandle" : modHandle, "handle" : False, "suffix" : suffix, "path" : path, "dependencies": dependenciyList}
					
					# don't load unused modules
					if (name not in self.__l_usedModules):
						item.setCheckState(0, Qt.Unchecked)
						module["modHandle"] = False
						delete(modHandle)
					else:
						item.setCheckState(0, Qt.Checked)
					# end fi
					
					modules.append(module)

					itemList[moduleClassType].append(item)

					continue
				else:
					delete(modHandle)
				# end if
			# end for
			
			# add items to tree widget
			item = self.__p_selectModule.treeWidgetModules.topLevelItem(index)
			item.addChildren(itemList[moduleClassType])
			
			index += 1
		# end for - search for modules in module order
		
		# init modules
		for module in modules:
			if (module["modHandle"] == False):
				continue
			# end if
			#module["handle"] = module["modHandle"].module(None, module["name"])
			module["handle"] = module["modHandle"].module(self, module["name"])
			
			#self.__p_logger.debug("load module " + module["name"])
		# end for - init modules


		# set static functions
		abstractModuleClass.d_modules = dict()
		abstractModuleClass.p_progressBar = self.progressBarGlobal
		abstractModuleClass.p_progressBarThread = self.__p_progressBarThread


		# open modules and load GUI
		firstDockWidget = None
		for module in modules:
			moduleName = module['name']
			moduleHand = module['handle']
			
			try:
				# Wichtig: Damit auch bei nicht geladenen Modulen die dependencies ueberprueft werden koennen.
				abstractModuleClass.d_modules[moduleName] = module
				
				# if module not used
				if (module["modHandle"] == False):
					continue
				# end if
				
				moduleDir = modulesPath + module["suffix"] + moduleName
	
				# find *.py files in the specific modules directory
				os.chdir(moduleDir)
				content = os.listdir(moduleDir)
				includes = dict()
				for filename in content:
					if (os.path.isfile(moduleDir + "/" + filename)):
						if (re.match(".*\.py$", filename) and not (moduleName + ".py") == filename ):
							name = filename[0:-3]
							includes[name] = imp.load_source(name, moduleDir + "/" + filename)
						# end if
					# end if
				# end for
				os.chdir(currentDir)

				# set module settings
				moduleHand.setModulePath(self.__v_modulePath + module["suffix"] + moduleName, os.path.abspath(os.curdir))
				moduleHand.setIncludes(includes)
	
				# check for module type
				moduleClassType = moduleHand.getClassType()

				# module type specific init
				if (moduleClassType != 'hidden'):
					# load [moduleName].ui
					self.__p_logger.setLevel(logging.WARN)
					uic.loadUi(moduleDir + "/" +moduleName + ".ui", moduleHand)
					self.__p_logger.setLevel(abstractModuleClass.loglevel)

					# load module settings
					moduleHand.initPreSettings()
					moduleHand.handleSettings()
					moduleHand.loadSettings()
				# end if

				# join in specific modules folder for initModule
				os.chdir(moduleDir)
				moduleHand.initModule()
				os.chdir(currentDir)
	
				# add module widget to GUI
				if (moduleClassType != 'hidden'):
					iconPath = False
					icon = None
					
					# get icon path
					iconPath = moduleHand.getIconPath()
					
					# try to load icon
					if (iconPath != False):
						icon = QIcon(iconPath)
					# end if
					
					displayName = moduleHand.getDisplayName()
					
					# init menu button
					button = moduleHand.getMenuButton()
					button.setText(displayName)
					
					# dock widget for current module
					# ... create
					dockWidget = mainWindowDockWidget(displayName, self)
					
					# ... set object name and title
					dockWidget.setObjectName(displayName)
					dockWidget.setWindowTitle(displayName)
					
					# ... add module as widget
					dockWidget.setWidget(moduleHand)
					
					# ... add dock widget to main window
					self.addDockWidget(Qt.LeftDockWidgetArea, dockWidget)
					
					# ... hide dock widget
					dockWidget.setVisible(False)
					
					# tabify all dock widgets
					if (firstDockWidget == None):
						firstDockWidget = dockWidget
					else:
						self.tabifyDockWidget(firstDockWidget, dockWidget)
					# end if
					
					# ... Set window icon.
					dockWidget.setWindowIcon(moduleHand.getMenuButton().icon())
					
					# ... Connect signal for checking and unchecking menu button on visibility change.
					#     If module is tabbed then set active module as current module.
					dockWidget.visibilityChanged[bool].connect(partial(self.__onModuleVisibilityChanged, dockWidget))


					# add button for application module and action for setting module					
					if (moduleClassType == 'application'):
						# get menu button
						button = moduleHand.getMenuButton()
						
						# set icon for menu button
						if (icon != None):
							button.setIcon(icon)
						# end if
						
						# add menu button to tool bar
						self.toolBar.addWidget(button)
						
						# connect signal from application menu button
						button.clicked[QObject].connect(self.__onModuleButtonClicked)
					else:
						# get action
						action = dockWidget.toggleViewAction()
						
						# set icon
						if (icon != None):
							action.setIcon(icon)
						# end if
						
						# add action to settings menu
						self.menuModuleSettings.addAction(action)
					# end if
				else:
					moduleHand.setParent(None)
				# end if
			except Exception as e:
				msg = "Error in module " + moduleName
				self.__p_logger.critical(msg)
				print(msg)
				raise e
			# end try
		# end for


		# init gui
		for module in modules:
			if (module["modHandle"] == False):
				continue
			# end if
			
			self.__v_moduleCounter += 1
			
			moduleDir = modulesPath + module["suffix"] + module["name"]
			moduleClassType = module["handle"].getClassType()
			
			if (moduleClassType != "hidden"):
				os.chdir(moduleDir)

				try:
					module["handle"].initGUI()
				except Exception as e:
					msg = "Fehler in Module " + module["name"]
					self.__p_logger.critical(msg)
					print(msg)
					raise e
				# end try

				os.chdir(currentDir)
			# end if
		# end for
		
		usedModules = self.__l_usedModules.copy()
		# remove not known used modules
		for moduleName in usedModules:
			if (moduleName not in abstractModuleClass.d_modules):
				self.__l_usedModules.remove(moduleName)
				
				continue
Пример #9
0
class SchemeSummaryWidget(QTreeWidget):
    """
    A widget for displaying scheme summary information after lodgement
    """
    link_clicked = pyqtSignal(str)

    def __init__(self, parent=None):
        super(QTreeWidget, self).__init__(parent)

        self.setHeaderHidden(True)
        self.setColumnCount(2)
        self.setColumnWidth(0, 300)
        self.setColumnWidth(1, 200)
        self._scheme = None
        self._documents = None
        self._holder = None

        # Widget items
        self.scheme_info = QTreeWidgetItem()
        self.supporting_document = QTreeWidgetItem()
        self.holders_info = QTreeWidgetItem()
        self.scm_num = QTreeWidgetItem()
        self.scm_name = QTreeWidgetItem()
        self.scm_date_apprv = QTreeWidgetItem()
        self.scm_date_est = QTreeWidgetItem()
        self.scm_ra_type = QTreeWidgetItem()
        self.scm_ra_name = QTreeWidgetItem()
        self.scm_land_hold_num = QTreeWidgetItem()
        self.scm_sg_num = QTreeWidgetItem()
        self.scm_title_deed_num = QTreeWidgetItem()
        self.scm_lro = QTreeWidgetItem()
        self.scm_region = QTreeWidgetItem()
        self.scm_desc = QTreeWidgetItem()
        self.scm_reg_div = QTreeWidgetItem()
        self.scm_numplots = QTreeWidgetItem()
        self.scm_blk_area = QTreeWidgetItem()

        self._page_name = 'page_name'

        view_str = self.tr('Go to page')

        # Labels for holders and documents
        self.lbl_view_holders = self.create_hyperlink_widget(view_str, 'HLD')
        self.lbl_view_holders.linkActivated.connect(self.on_hyperlink_click)
        self.lbl_view_support_docs = self.create_hyperlink_widget(
            view_str, 'DOC')
        self.lbl_view_support_docs.linkActivated.connect(
            self.on_hyperlink_click)

        self._initialize_view()

    def _initialize_view(self):
        """
        Set scheme details to be shown in a summary as collapsed items.
        """
        # call label
        # Define top-level items
        self.scheme_info.setText(0, self.tr('Scheme Information'))
        self.supporting_document.setText(0, self.tr('Supporting Documents'))
        self.holders_info.setText(0, self.tr('List of Holders: '))
        self.addTopLevelItems(
            [self.scheme_info, self.supporting_document, self.holders_info])

        # Add child elements items to categories
        self.scheme_info.addChildren([
            self.scm_num, self.scm_name, self.scm_date_apprv,
            self.scm_date_est, self.scm_ra_type, self.scm_ra_name,
            self.scm_land_hold_num, self.scm_sg_num, self.scm_title_deed_num,
            self.scm_lro, self.scm_region, self.scm_desc, self.scm_reg_div,
            self.scm_numplots, self.scm_blk_area
        ])

        # Expand top-level items
        self.scheme_info.setExpanded(True)
        # self.supporting_document.setExpanded(True)

        # Static children items
        # Scheme
        self.scm_region.setText(0, self.tr('Region '))
        self.scm_ra_type.setText(0, self.tr('Type of Relevant Authority '))
        self.scm_ra_name.setText(0, self.tr('Name of Relevant Authority '))
        self.scm_land_hold_num.setText(0, self.tr('Land Hold Plan Number '))
        self.scm_sg_num.setText(0, self.tr('Surveyor General Number '))
        self.scm_title_deed_num.setText(0, self.tr('Title Deed Number '))
        self.scm_num.setText(0, self.tr('Number of Scheme '))
        self.scm_name.setText(0, self.tr('Name of Scheme '))
        self.scm_date_apprv.setText(0, self.tr('Date of Approval'))
        self.scm_date_est.setText(0, self.tr('Date of Establishment '))
        self.scm_lro.setText(0, self.tr('Land Rights Office '))
        self.scm_desc.setText(0, self.tr('Scheme Description '))
        self.scm_reg_div.setText(0, self.tr('Registration Division '))
        self.scm_numplots.setText(0, self.tr('Number of Plots '))
        self.scm_blk_area.setText(0, self.tr('Block Area '))

        # Set links for holders and documents
        self.setItemWidget(self.holders_info, 1, self.lbl_view_holders)
        self.setItemWidget(self.supporting_document, 1,
                           self.lbl_view_support_docs)

    def create_hyperlink_widget(self, name, code):
        """
        Creates a clickable QLabel widget that appears like a hyperlink.
        :param name: Display name of the hyperlink.
        :type name: str
        :return: Returns the QLabel widget with appearance of a hyperlink.
        :rtype: QLabel
        """
        lbl_link = QLabel()
        lbl_link.setAlignment(Qt.AlignLeft)
        lbl_link.setText(u'<a href=\'placeholder\'>{0}</a>'.format(name))
        lbl_link.setTextInteractionFlags(Qt.TextBrowserInteraction)

        lbl_link.setProperty(self._page_name, code)

        return lbl_link

    def on_hyperlink_click(self):
        """
        Slot raised when hyperlink to view documents has been clicked.
        Navigate back to the documents page or holders page based on the
        clicked link.
        :return:str
        """
        sender = self.sender()
        if not self._is_page_name_valid(sender):
            return

        code = sender.property(self._page_name)

        self.link_clicked.emit(code)

    def _is_page_name_valid(self, sender):
        # Assert if the page called by signal can be found
        if not sender:
            QMessageBox.critical(self, self.tr('Error'),
                                 self.tr('Error in finding the page'))
            return False

        return True