def __init__(self, methodName):
        """Run once on class initialisation."""
        unittest.TestCase.__init__(self, methodName)
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        rasterFileInfo = QFileInfo(myPath)
        mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(),
                                      rasterFileInfo.completeBaseName())
        rasterRenderer = QgsMultiBandColorRenderer(
            mRasterLayer.dataProvider(), 2, 3, 4)
        mRasterLayer.setRenderer(rasterRenderer)
        #pipe = mRasterLayer.pipe()
        #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer'
        QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer])

        # create composition with composer map
        self.mMapRenderer = QgsMapRenderer()
        layerStringList = QStringList()
        layerStringList.append(mRasterLayer.id())
        self.mMapRenderer.setLayerSet(layerStringList)
        self.mMapRenderer.setProjectionsEnabled(False)
        self.mComposition = QgsComposition(self.mMapRenderer)
        self.mComposition.setPaperSize(297, 210)
        self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100)
        self.mComposerMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mComposerMap)
Exemplo n.º 2
0
 def get_string_list(self, column):
     """Returns a column as a QStringList"""
     tempList = QStringList()
     result = QtSql.QSqlQuery('''SELECT DISTINCT %s FROM presentations''' % column)
     while result.next():
         tempList.append(result.value(0).toString())
     return tempList
def prepareQtMacBundle(toolname, version, args):
    """
    Module function for starting Qt tools that are Mac OS X bundles.

    @param toolname  plain name of the tool (e.g. "designer") (string or QString)
    @param version indication for the requested version (Qt 4) (integer)
    @param args    name of input file for tool, if any (QStringList)
    @return command-name and args for QProcess (tuple)
    """
    if version == 4:
        qtDir = Preferences.getQt("Qt4Dir")
    else:
        return ("", QStringList())
    
    fullBundle = os.path.join(qtDir, 'bin',
        generateQtToolName(toolname)) + ".app"
    if not os.path.exists(fullBundle):
        fullBundle = os.path.join(qtDir, 
            generateQtToolName(toolname)) + ".app"

    newArgs = QStringList()
    newArgs.append("-a")
    newArgs.append(fullBundle)
    newArgs += args

    return ("open", newArgs)
Exemplo n.º 4
0
    def set_root_folder(self, root_folder):
        self.tree.clear()
        self.clear_all_load_animations()
        
        if self.root_folder != None:
            del self.root_folder
        self.root_folder = root_folder

        # Add root
        columns = QStringList()
        columns.append(root_folder.get_name())
        columns.append(root_folder.get_size())
        root_item = QTreeWidgetItem(columns)

        self.set_icon(root_folder.mime_type, root_item)
        
        self.tree.addTopLevelItem(root_item)
        root_item.setExpanded(True)
        root_folder.tree_item = root_item

        self.generate_children(root_folder)
        self.add_loading_widgets(root_folder)

        self.tree.setCurrentItem(root_item)
        self.start_load_anim(root_folder)
        
        self.tree.header().resizeSections(QHeaderView.ResizeToContents)
Exemplo n.º 5
0
	def __init__(self, parent=None, TreeFileName=DefaultTreeFileName):
		QTreeWidget.__init__(self, parent)
		self.parent = parent
		self.setGeometry(0,0, self.parent.width(), self.parent.height())
		self.setColumnCount(2)
		self.setColumnWidth(0,270)
		#self.header().setStretchLastSection(False)
		#self.resizeColumnToContents(1)
		headerTitles = QStringList()
		headerTitles.append(QString("Parameter"))
		headerTitles.append(QString("Value"))
		self.setHeaderLabels(headerTitles)
		self.setEditTriggers(QTreeWidget.DoubleClicked|QTreeWidget.EditKeyPressed)
		self.rootItems = []
		self.currentItemChanged.connect(self.visit)
		self.itemDoubleClicked.connect(self.edit_)
		self.editing = None
		self.expandAll()
		self.ScenarioName = ''
		self.NodeDescriptions = dict()  # textual parameter descriptions
		self.ParamScenario = dict()  # name of corresponding scenario for parameters
		self.changed = False
		self.ApplicationPath = ''
		self.TreeFileName = TreeFileName
		self.RunCfgFileName = DefaultCfgFileName
		self.load()
		self.parent.setWindowTitle(self.NodeValue('Title').replace('_',' ') + ' ' + DefaultTtitle)
Exemplo n.º 6
0
    def initializePage(self):
        super(PanelPage, self).initializePage()

        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 30, 20, 30)

        row0 = QHBoxLayout()
        lable0 = QLabel('  依赖库:')
        lable0.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        items0 = QStringList()
        for moudel in app.g_configurations.libs:
            items0.append(moudel['name'])
        self.lw_files.addItems(items0)
        row0.addWidget(lable0)
        row0.addWidget(self.lw_files)

        row1 = QHBoxLayout()
        lable1 = QLabel('工程文件:')
        lable1.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        items1 = QStringList()
        for file in app.g_configurations.config['files']:
            items1.append(file['target'])
        self.lw_files.addItems(items1)
        row1.addWidget(lable1)
        row1.addWidget(self.lw_files)

        rootLayout.addLayout(row0)
        rootLayout.addLayout(row1)
        self.setLayout(rootLayout)
Exemplo n.º 7
0
 def _nameList(self, filt=None, without=None, upto=None):
     # need to search all tables for a string list of object names
     # filt is a ModuleBase subclass to filter by
     # without is a row number to exclude from the current table
     # upto means only look at objects up to "upto" row in the current table
     if (filt, without, upto) in self._cachedNameList:
         timestamp, sl = self._cachedNameList[(filt, without, upto)]
         if self._parent.lastModified() < timestamp:
             return sl
     sl = QStringList()
     for name in self._parent.getTableNames():
         table = self._parent._tables[name]
         # if we have a filter, then make sure this table is a subclass of it
         if filt is not None and not issubclass(table.ob, filt):
             # if we are only going up to a certain table and this is it
             if table == self and upto is not None:
                 return sl
             continue
         for i, trow in enumerate(table.rows):
             if table == self:
                 # if the current table is self, make sure we are excluding
                 # the without row
                 if without is not None and without == i:
                     continue
                 # make sure we only go up to upto
                 if upto is not None and upto == i:
                     return sl
             # add a non-null name, which is not commented out to the list
             if not trow[2].isNull() and not \
                     (not trow[0].isNull() and trow[0].toBool() == True):
                 sl.append(trow[2].toString())
     # store the cached value
     self._cachedNameList[(filt, without, upto)] = (time.time(), sl)
     return sl
Exemplo n.º 8
0
 def get_string_list(self, column):
     """Returns a column as a QStringList"""
     tempList = QStringList()
     result = QtSql.QSqlQuery('''SELECT DISTINCT %s FROM presentations''' % column)
     while result.next():
         tempList.append(result.value(0).toString())
     return tempList
Exemplo n.º 9
0
 def on_addInstalledApiFileButton_clicked(self):
     """
     Private slot to add an API file from the list of installed API files
     for the selected lexer language.
     """
     installedAPIFiles = self.__currentAPI.installedAPIFiles()
     if len(installedAPIFiles) > 0:
         installedAPIFilesPath = QFileInfo(installedAPIFiles[0]).path()
         installedAPIFilesShort = QStringList()
         for installedAPIFile in installedAPIFiles:
             installedAPIFilesShort.append(QFileInfo(installedAPIFile).fileName())
         file, ok = KQInputDialog.getItem(
             self,
             self.trUtf8("Add from installed APIs"),
             self.trUtf8("Select from the list of installed API files"),
             installedAPIFilesShort,
             0,
             False,
         )
         if ok:
             self.apiList.addItem(
                 Utilities.toNativeSeparators(QFileInfo(QDir(installedAPIFilesPath), file).absoluteFilePath())
             )
     else:
         KQMessageBox.warning(
             self,
             self.trUtf8("Add from installed APIs"),
             self.trUtf8("""There are no APIs installed yet.""" """ Selection is not available."""),
         )
         self.addInstalledApiFileButton.setEnabled(False)
Exemplo n.º 10
0
    def initializePage(self):
        super(PanelPage, self).initializePage()

        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 30, 20, 30)

        row0 = QHBoxLayout()
        lable0 = QLabel('  依赖库:')
        lable0.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        items0 = QStringList()
        for moudel in app.g_configurations.libs:
            items0.append(moudel['name'])
        self.lw_files.addItems(items0)
        row0.addWidget(lable0)
        row0.addWidget(self.lw_files)

        row1 = QHBoxLayout()
        lable1 = QLabel('工程文件:')
        lable1.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        items1 = QStringList()
        for file in app.g_configurations.config['files']:
            items1.append(file['target'])
        self.lw_files.addItems(items1)
        row1.addWidget(lable1)
        row1.addWidget(self.lw_files)

        rootLayout.addLayout(row0)
        rootLayout.addLayout(row1)
        self.setLayout(rootLayout)
Exemplo n.º 11
0
    def __saveScreenshot(self):
        format = "png"
        initialPath = QDesktopServices.storageLocation(
            QDesktopServices.PicturesLocation)
        # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
        if initialPath.isEmpty():
            initialPath = QDir.currentPath()
        initialPath += "/untitled." + format

        fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath)
        fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
        fileDialog.setDirectory(initialPath)
        mimeTypes = QStringList()

        for bf in QImageWriter.supportedImageFormats():
            mimeTypes.append(QLatin1String(bf))

        # fileDialog.setMin setMimeTypeFilters(mimeTypes)
        # fileDialog.selectMimeTypeFilter("image/" + format);
        fileDialog.setDefaultSuffix(format)
        if fileDialog.accept():
            return

        fileName = fileDialog.selectedFiles().first()

        if not self.originalPixmap.save(fileName):
            QtGui.QMessageBox.Warning(
                self, u"保存错误",
                u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName)))
Exemplo n.º 12
0
 def _nameList(self, filt = None, without = None, upto = None):
     # need to search all tables for a string list of object names
     # filt is a ModuleBase subclass to filter by
     # without is a row number to exclude from the current table
     # upto means only look at objects up to "upto" row in the current table
     if (filt, without, upto) in self._cachedNameList:
         timestamp, sl = self._cachedNameList[(filt, without, upto)]
         if self._parent.lastModified() < timestamp:
             return sl
     sl = QStringList()
     for name in self._parent.getTableNames():
         table = self._parent._tables[name]
         # if we have a filter, then make sure this table is a subclass of it
         if filt is not None and not issubclass(table.ob, filt):
             # if we are only going up to a certain table and this is it
             if table == self and upto is not None:
                 return sl
             continue
         for i,trow in enumerate(table.rows):
             if table == self:
                 # if the current table is self, make sure we are excluding
                 # the without row
                 if without is not None and without == i:
                     continue
                 # make sure we only go up to upto
                 if upto is not None and upto == i:
                     return sl
             # add a non-null name, which is not commented out to the list
             if not trow[2].isNull() and not \
                     (not trow[0].isNull() and trow[0].toBool() == True):
                 sl.append(trow[2].toString())
     # store the cached value
     self._cachedNameList[(filt, without, upto)] = (time.time(), sl)
     return sl
 def __init__(self):
     """
     Constructor
     """
     ConfigurationPageBase.__init__(self)
     self.setupUi(self)
     self.setObjectName("EditorKeywordsPage")
     
     # set initial values
     self.__keywords = {
         "": QStringList(["", "", "", "", "", "", "", "", "", ""])
     }
     languages = [''] + QScintilla.Lexers.getSupportedLanguages().keys()
     languages.sort()
     for lang in languages:
         if lang:
             lex = QScintilla.Lexers.getLexer(lang)
             if isinstance(lex, LexerContainer):
                 continue
             keywords = Preferences.getEditorKeywords(lang)[:]
             if keywords.isEmpty():
                 keywords = QStringList("")
                 for kwSet in range(1, 10):
                     kw = lex.keywords(kwSet)
                     if kw is None:
                         kw = ""
                     keywords.append(kw)
             self.__keywords[lang] = keywords
         self.languageCombo.addItem(lang)
     
     self.currentLanguage = QString()
     self.currentSet = 1
     self.on_languageCombo_activated(self.currentLanguage)
Exemplo n.º 14
0
    def __init__(self, methodName):
        """Run once on class initialisation."""
        unittest.TestCase.__init__(self, methodName)
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        rasterFileInfo = QFileInfo(myPath)
        mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(),
                                      rasterFileInfo.completeBaseName())
        rasterRenderer = QgsMultiBandColorRenderer(
            mRasterLayer.dataProvider(), 2, 3, 4)
        mRasterLayer.setRenderer(rasterRenderer)
        #pipe = mRasterLayer.pipe()
        #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer'
        QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer])

        # create composition with composer map
        self.mMapRenderer = QgsMapRenderer()
        layerStringList = QStringList()
        layerStringList.append(mRasterLayer.id())
        self.mMapRenderer.setLayerSet(layerStringList)
        self.mMapRenderer.setProjectionsEnabled(False)
        self.mComposition = QgsComposition(self.mMapRenderer)
        self.mComposition.setPaperSize(297, 210)
        self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100)
        self.mComposerMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mComposerMap)
Exemplo n.º 15
0
 def list(self):
     q = QSqlQueryModel()
     q.setQuery("SELECT name FROM platform")
     strlist = QStringList()
     strlist.append(u"全部")
     for i in range(q.rowCount()):
         strlist.append(q.record(i).value(0).toString())
     return strlist
Exemplo n.º 16
0
 def list(self):
     q = QSqlQueryModel()
     q.setQuery("SELECT name FROM platform")
     strlist = QStringList()
     strlist.append(u"全部")
     for i in range(q.rowCount()):
         strlist.append(q.record(i).value(0).toString())
     return strlist
Exemplo n.º 17
0
    def getThemeList(self):

        dir = QDir("/usr/share/enlightenment/data/themes")
        dir.setFilter( QDir.NoSymLinks | QDir.Files )
        a = QStringList()
        a.append("*.edj")
        dir.setNameFilters(a)
        return dir.entryList()
Exemplo n.º 18
0
 def save(self):
     """
     Public slot to save the Icons configuration.
     """
     dirList = QStringList()
     for i in range(self.iconDirectoryList.count()):
         dirList.append(self.iconDirectoryList.item(i).text())
     Preferences.setIcons("Path", dirList)
Exemplo n.º 19
0
def buildQStringList(items):
	"""
	@rtype: QStringList
	"""
	returnData = QStringList()
	for item in items:
		returnData.append(item)

	return returnData
Exemplo n.º 20
0
def buildQStringList(items):
    """
	@rtype: QStringList
	"""
    returnData = QStringList()
    for item in items:
        returnData.append(item)

    return returnData
Exemplo n.º 21
0
 def set_devlist(self, devlist, isWIN32):
     qslist = QStringList()
     if isWIN32:
         for dev in devlist:
             qslist.append(QString(dev.description))
     else:
         for dev in self.capturer.devlist:
             qslist.append(QString(dev.name))
     self.devComboBox.addItems(qslist)
Exemplo n.º 22
0
def fieldNames(layer):
    fields = layer.dataProvider().fields()

    if QGis.QGIS_VERSION_INT < 10900:
        from PyQt4.QtCore import QStringList
        fieldNames = QStringList()
        for field in fields.values():
            fieldNames.append(field.name())
    else:
        return map(lambda field: field.name(), fields)
Exemplo n.º 23
0
 def __editorGetApisFromApiList(self):
     """
     Private slot to retrieve the api filenames from the list.
     
     @return list of api filenames (QStringList)
     """
     apis = QStringList()
     for row in range(self.apiList.count()):
         apis.append(self.apiList.item(row).text())
     return apis
 def __extractFileFilters(self):
     """
     Private method to extract the file filters.
     """
     filters = QStringList()
     for row in range(self.fileFiltersList.count()):
         filters.append(self.fileFiltersList.item(row).text())
     if self.__showsOpenFilters:
         self.openFileFilters = filters
     else:
         self.saveFileFilters = filters
Exemplo n.º 25
0
	def mimeTypes(self):
		"""
		Reimplements the :meth:`QAbstractItemModel.mimeTypes` method.
		
		:return: Mime types.
		:rtype: QStringList
		"""

		types = QStringList()
		types.append("application/x-umbragraphmodeldatalist")
		return types
Exemplo n.º 26
0
    def testPrintMapFromTemplate(self):
        """Test that we can get a map to render in the template."""
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        myFileInfo = QFileInfo(myPath)
        myRasterLayer = QgsRasterLayer(myFileInfo.filePath(),
                                       myFileInfo.completeBaseName())
        myRenderer = QgsMultiBandColorRenderer(
                        myRasterLayer.dataProvider(), 2, 3, 4)
        #mRasterLayer.setRenderer( rasterRenderer )
        myPipe = myRasterLayer.pipe()
        assert myPipe.set( myRenderer ), "Cannot set pipe renderer"

        QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer])

        myMapRenderer = QgsMapRenderer()
        myLayerStringList = QStringList()
        myLayerStringList.append(myRasterLayer.id())
        myMapRenderer.setLayerSet(myLayerStringList)
        myMapRenderer.setProjectionsEnabled(False)

        myComposition = QgsComposition(myMapRenderer)
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        myTemplateFile = file(myFile, 'rt')
        myTemplateContent = myTemplateFile.read()
        myTemplateFile.close()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument)

        # now render the map, first zooming to the raster extents
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage

        myExtent = myRasterLayer.extent()
        myMap.setNewExtent(myExtent)

        myImagePath = os.path.join(str(QDir.tempPath()),
                                   'template_map_render_python.png')

        myPageNumber = 0
        myImage = myComposition.printPageAsRaster(myPageNumber)
        myImage.save(myImagePath)
        assert os.path.exists(myImagePath), 'Map render was not created.'

        # Not sure if this is a predictable way to test but its quicker than
        # rendering.
        myFileSize = QFileInfo(myImagePath).size()
        myExpectedFileSize = 100000
        myMessage = ('Expected file size to be greater than %s, got %s'
                     ' for %s' %
                     (myExpectedFileSize, myFileSize, myImagePath))
        assert myFileSize > myExpectedFileSize, myMessage
Exemplo n.º 27
0
    def detailsButtonClicked(self):
        changedList = QStringList()
        (install, remove, unauthenticated) = self._deb.required_changes
        for i in install:
            changedList.append(_("To be installed: %s") % i)
        for r in remove:
            changedList.append(_("To be removed: %s") % r)

        KMessageBox.informationList(
            self,
            _("<b>To install the following changes are required:</b>"),
            changedList, _("Details"))
Exemplo n.º 28
0
 def __init__(self, dataSource, columns, logger):
     super(TableModelBase, self).__init__()
     self.dataSource = dataSource
     self.columns = columns
     self.logger = logger
     if self.columns != None:
         self.setColumnCount(len(self.columns))
         stringList = QStringList()
         for colName, _ in self.columns:
             stringList.append(colName)
         self.setHorizontalHeaderLabels(stringList)
     self.keys = []
Exemplo n.º 29
0
def select_git_directory():
    settings = QSettings("majerti", "gitbuster")
    settings.beginGroup("Last run")

    filepath = '/'
    last_directory = settings.value("directory", QVariant(QDir.homePath()))
    dirs_list = settings.value("recent directories",
                               QStringList()).toStringList()
    custom_entries = settings.value("custom entries",
                                    QStringList()).toStringList()

    recent_dirs_urls = [QUrl.fromLocalFile(dir) for dir in dirs_list]
    home_url = QUrl.fromLocalFile(QDir.homePath())
    custom_entries_urls = [QUrl.fromLocalFile(dir) for dir in custom_entries]

    while not is_top_git_directory(unicode(filepath)):
        file_dialog = QFileDialog(None, "Open git repository",
                                  last_directory.toString())
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOptions(QFileDialog.ShowDirsOnly)
        if recent_dirs_urls:
            file_dialog.setSidebarUrls(
                [home_url,] +
                custom_entries_urls +
                recent_dirs_urls[-6:]
            )
        ret = file_dialog.exec_()

        custom_entries = QStringList()
        custom_entries_urls = []
        for url in file_dialog.sidebarUrls():
            if url not in recent_dirs_urls and url != home_url:
                custom_entries.append(QString(url.path()))
                custom_entries_urls.append(url)
        settings.setValue("custom entries", custom_entries)

        if ret:
            filepath = file_dialog.selectedFiles()[0]
        else:
            return ret

        if not filepath:
            return filepath

    if not dirs_list.contains(filepath):
        dirs_list.append(filepath)
        settings.setValue("recent directories", dirs_list)

    settings.setValue("directory", filepath)
    settings.endGroup()
    settings.sync()

    return unicode(filepath)
Exemplo n.º 30
0
 def addApp(self):
     """ popup to add a show"""
     listsuggest = self.nextep.getSuggestions()
     listsug = QStringList()
     for i in listsuggest:
         listsug.append(i[0])
     (tvshow, isok) = QtGui.QInputDialog.getItem (self.parent, \
                   "add a tv show", 'Which show do you want to track?', \
                   listsug, editable = True)
     if (isok and tvshow):
         self.parent.nextep.addShow(str(tvshow))
         print "should add", tvshow, " :p"
Exemplo n.º 31
0
    def testPrintMapFromTemplate(self):
        """Test that we can get a map to render in the template."""
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        myFileInfo = QFileInfo(myPath)
        myRasterLayer = QgsRasterLayer(myFileInfo.filePath(),
                                       myFileInfo.completeBaseName())
        myRenderer = QgsMultiBandColorRenderer(myRasterLayer.dataProvider(), 2,
                                               3, 4)
        #mRasterLayer.setRenderer( rasterRenderer )
        myPipe = myRasterLayer.pipe()
        assert myPipe.set(myRenderer), "Cannot set pipe renderer"

        QgsMapLayerRegistry.instance().addMapLayers([myRasterLayer])

        myMapRenderer = QgsMapRenderer()
        myLayerStringList = QStringList()
        myLayerStringList.append(myRasterLayer.id())
        myMapRenderer.setLayerSet(myLayerStringList)
        myMapRenderer.setProjectionsEnabled(False)

        myComposition = QgsComposition(myMapRenderer)
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        myTemplateFile = file(myFile, 'rt')
        myTemplateContent = myTemplateFile.read()
        myTemplateFile.close()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument)

        # now render the map, first zooming to the raster extents
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage

        myExtent = myRasterLayer.extent()
        myMap.setNewExtent(myExtent)

        myImagePath = os.path.join(str(QDir.tempPath()),
                                   'template_map_render_python.png')

        myPageNumber = 0
        myImage = myComposition.printPageAsRaster(myPageNumber)
        myImage.save(myImagePath)
        assert os.path.exists(myImagePath), 'Map render was not created.'

        # Not sure if this is a predictable way to test but its quicker than
        # rendering.
        myFileSize = QFileInfo(myImagePath).size()
        myExpectedFileSize = 100000
        myMessage = ('Expected file size to be greater than %s, got %s'
                     ' for %s' % (myExpectedFileSize, myFileSize, myImagePath))
        assert myFileSize > myExpectedFileSize, myMessage
Exemplo n.º 32
0
 def cargaTablas(self):
       temp = QStringList("Elija Una Fuente")
       connection = None
       try:
             connection =  sqlite3.connect("escenarios.db")
             cursor = connection.cursor()
             cursor.execute("SELECT name FROM escenario")
             data = cursor.fetchall()
             for row in data:
                   temp.append(row[0])
                   #print row[0]
       except sqlite3.Error , e:
             print "Error %s:" % e.args[0]
             if connection:
                   connection.close()
Exemplo n.º 33
0
 def cargaTablas(self):
     temp = QStringList("Elija Una Fuente")
     connection = None
     try:
         connection = sqlite3.connect("escenarios.db")
         cursor = connection.cursor()
         cursor.execute("SELECT name FROM escenario")
         data = cursor.fetchall()
         for row in data:
             temp.append(row[0])
             #print row[0]
     except sqlite3.Error, e:
         print "Error %s:" % e.args[0]
         if connection:
             connection.close()
Exemplo n.º 34
0
    def __init__(self, fullPath, displayName = None, parent = None):
        assert isinstance(fullPath, str)

        if displayName is None:
            displayName = fullPath
        self.__fullPath = fullPath
        self.__displayName = displayName

        stringList = QStringList()
        stringList.append(QString(displayName))

        st = os.stat(fullPath)
        self.__lastAccessDate = datetime.fromtimestamp(st.st_atime)

        dateStr = self.getStrDate()
        stringList.append(QString(dateStr))
        super(Item, self).__init__(parent, stringList)
Exemplo n.º 35
0
 def __convertFilter(filter, selectedFilter = None):
     """
     Private function to convert a Qt file filter to a KDE file filter.
     
     @param filter Qt file filter (QString or string)
     @param selectedFilter this is set to the selected filter
     @return the corresponding KDE file filter (QString)
     """
     rx = QRegExp("^[^(]*\(([^)]*)\).*$")
     fileFilters = filter.split(';;')
     
     newfilter = QStringList()
     for fileFilter in fileFilters:
         sf = selectedFilter and selectedFilter.compare(fileFilter) == 0
         namefilter = QString(fileFilter).replace(rx, "\\1")
         fileFilter = QString(fileFilter).replace('/', '\\/')
         if sf:
             newfilter.prepend("%s|%s" % (namefilter, fileFilter))
         else:
             newfilter.append("%s|%s" % (namefilter, fileFilter))
     return newfilter.join('\n')
Exemplo n.º 36
0
    def __initialize(self):

        self.setWindowIcon(QIcon(ICON_ROCKET))

        # Find out all supported baud rates
        attrs = dir(termios)
        baudRates = sorted([int(attr[1:]) for attr in attrs if (("B" == attr[0].upper()) and attr[1:].isdigit())])
        if 0 in baudRates:
            baudRates.remove(0)
        
        baudRateList = QStringList()
        for rate in baudRates:
            baudRateList.append(QString(str(rate)))

        self.comboBoxBaudRate.addItems(baudRateList)

        self.__history = History()

        self.__loadSettings()

        self.pushButtonSend.clicked.connect(self.onPushButtonSendClicked)
        self.pushButtonOpenClose.clicked.connect(self.onPushButtonOpenCloseClicked)
        self.checkBoxRawText.stateChanged.connect(self.onCheckBoxRawTextStateChanged)

        # self.lineEditData is a custom widget so slignal-slot connection is made this way
        # when recompiling ui_Dialog.ui do not forget to change
        # self.lineEdit = QtGui.QLineEdit(...) for self.lineEdit = rhelpers.widgets.LineEdit(...)
        QObject.connect(self.lineEditData, SIGNAL("keyPressed"), self.__keyPressed)

        self.pushButtonSend.setEnabled(False)
        self.lineEditData.setEnabled(False)

        self.__serial = Serial()

        self.__serialWidgets = list()
        self.__serialWidgets.append(self.lineEditDevice)
        self.__serialWidgets.append(self.comboBoxBaudRate)
        self.__serialWidgets.append(self.comboBoxDataBits)
        self.__serialWidgets.append(self.comboBoxParity)
        self.__serialWidgets.append(self.comboBoxStopBits)
Exemplo n.º 37
0
    def getWallpaperSettings(self):
        dir = QDir("/usr/share/wallpapers/Pardus_Mood/contents")
        dir.setFilter( QDir.NoSymLinks | QDir.Files )
        a = QStringList()
        a.append ("*.jpeg")
        a.append("*.jpg")
        a.append("*.png")
        dir.setNameFilters(a)
        lst = dir.entryList()
        items = []
        for desktopFile in lst:
            wallpaper = {}
            try:
                wallpaper["wallpaperTitle"] = "picture"
            except:
                wallpaper["wallpaperTitle"] = "picture1"

            try:
                wallpaper["wallpaperDesc"] = "description"
            except:
                wallpaper["wallpaperDesc"] = "description1"

                # Get all files in the wallpaper's directory
            thumbFolder = desktopFile

            #    """
            #    Appearantly the thumbnail names doesn't have a standart.
            #    So we get the file list from the contents folder and
            #    choose the file which has a name that starts with "scre".

            #    File names I've seen so far;
            #    screenshot.jpg, screnshot.jpg, screenshot.png, screnshot.png
            #    """
            wallpaper["wallpaperThumb"] = "/usr/share/wallpapers/Pardus_Mood/contents/%s"%desktopFile
            wallpaper["wallpaperFile"] = desktopFile
            items.append(wallpaper)

        CONFIG_KAPTANRC.setValue("Wallpaper/Source","/usr/share/wallpapers/Pardus_Mood/contents/%s" %desktopFile)
        self.getWallpaper(desktopFile)
        return items
Exemplo n.º 38
0
    def dropMimeData(self, data, action, row, column, parent):

        # 如果放入动作是Qt.IgnoreAction,那么返回True
        if (action == Qt.IgnoreAction):
            return True
        # 如果数据的格式不是指定的格式,那么返回False
        if (not data.hasFormat("application/vnd.text.list")):
            return False
        # 因为这里是列表,只用一列,所以列大于0时返回False
        if (column > 0):
            return False
        # 设置开始插入的行
        if (row != -1):
            beginRow = row
        elif parent.isValid():
            beginRow = parent.row()
        else:
            beginRow = self.rowCount(QModelIndex())

        # 将数据从QMimeData中读取出来,然后插入到模型中
        encodedData = data.data("application/vnd.text.list")
        stream = QDataStream(encodedData, QIODevice.ReadOnly)

        newItems = QStringList()
        rows = 0

        while (not stream.atEnd()):
            text = QString()
            stream >> text
            newItems.append(text)
            rows += 1

        self.insertRows(beginRow, rows, QModelIndex())
        for text in newItems:
            idx = self.index(beginRow, 0, QModelIndex())
            self.setData(idx, QVariant(text))
            beginRow += 1

        return True
Exemplo n.º 39
0
    def addTree(self, opusDataPath, parentWidget):
        self.containerWidget = parentWidget
        self.opusDataPath = opusDataPath

        self.treeview = QTreeView()
        filters = QStringList()
        filters.append("*.*")
        #filters.append("*.py")
        #filters.append("*.shp")
        #filters.append("*.tif")
        self.model = QDirModel(filters, QDir.Files|QDir.AllDirs|QDir.NoDotAndDotDot, QDir.Name)
        self.treeview.setModel(self.model)
        if self.opusDataPath:
            self.treeview.setRootIndex(self.model.index(self.opusDataPath))
        self.treeview.setColumnWidth(0,200)
        self.treeview.hideColumn(2)
        self.treeview.hideColumn(3)

        self.containerWidget.layout().addWidget(self.treeview)

        # Hook up to the mousePressEvent and pressed
        self.treeview.setContextMenuPolicy(Qt.CustomContextMenu)
Exemplo n.º 40
0
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()
        if role != Qt.DisplayRole:
            return QVariant()

        item = index.internalPointer()
        node = item.node

        attributeMap = node.attributes()
        #        if node.nodeName() == 'xml':
        #            return

        if index.column() == 0:
            name = None
            if attributeMap.contains("name"):
                name = attributeMap.namedItem("name").nodeValue()

            if name is not None:
                return QVariant(node.nodeName() + ": " + name)
            else:
                return QVariant(node.nodeName())
        elif index.column() == 1:
            if self.__allAttributes:
                attributes = QStringList()
                for i in range(attributeMap.count()):
                    attribute = attributeMap.item(i)
                    attributes.append(attribute.nodeName() + "=\"" +
                                      attribute.nodeValue() + "\"")
                return QVariant(attributes.join(" ") + "  ")
            else:
                return QVariant((
                    attributeMap.namedItem("type").nodeValue() +
                    "  ") if attributeMap.contains("type") else QString("  "))

        elif index.column() == 2:
            return QVariant(node.nodeValue().split("\n").join(" "))
        else:
            return QVariant()
Exemplo n.º 41
0
	def run(self):
		self.project.newMessage.emit()
		self.project.addMessage.emit("# running: "+self.command+"\n")
		start_time=time.time()
		self.proc = QProcess(None)
		self.proc.readyReadStandardError.connect(self.stdErrReady)
		self.proc.readyReadStandardOutput.connect(self.stdOutReady) 
		self.proc.setWorkingDirectory(self.project.path)
		commands = self.command.split(' ')
		args=QStringList()
		for cmd in commands[1:]:
			args.append(cmd)
		self.proc.start(QString(commands[0]), args, mode=QIODevice.ReadOnly)
		self.proc.waitForFinished()
		
		end_time=time.time()
		if (self.proc.exitCode()==0):
			self.project.statusChanged.emit("SUCCESS")
			self.project.addMessage.emit("# \""+self.command+"\" finished in "+str(end_time-start_time)+"sec\n")
		else:
			self.project.statusChanged.emit("FAILED")
			self.project.addErrorMessage.emit("# \""+self.command+"\" finished in "+str(end_time-start_time)+ "sec with status:"+str(self.proc.exitCode())+"\n")
Exemplo n.º 42
0
Arquivo: grid.py Projeto: nesaro/driza
 def __preguntar_conversion(self, variable, objetivo):
     """Pregunta cual de los metodos disponibles para la conversion desea escoger el usuario"""
     if not isinstance(objetivo, str):
         LOG.debug("__preguntar_conversion: Bad type for string: "+str(objetivo.__class__))
         raise TypeError
     lista = []
     if variable.diccionarioconversion.has_key("Agrupador"):
         #Conversión a todos los tipos
         lista += variable.diccionarioconversion["Agrupador"]
     for tipo in variable.diccionarioconversion.iterkeys():
         if tipo == objetivo:
             lista += variable.diccionarioconversion[tipo]
     #Elaborar una lista y preguntar al usuario
     qlista = QStringList()
     for elemento in lista:
         qlista.append(elemento)
     cadena = QInputDialog.getItem(self, "Elige!", u"Elige una función de conversion", qlista, 0, False)
     #devolver el nombre de la funcion
     if cadena[1]:
         return str(cadena[0])
     else:
         return ""
Exemplo n.º 43
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        uic.loadUi("mainwindow.ui", self)
        strlist = QStringList()
        strlist.append("yafei")
        strlist.append("yafeilinux")
        strlist.append("Qt")
        strlist.append("Qt Creator")

        listModel = QStringListModel(strlist, self)
        self.filterModel = QSortFilterProxyModel(self)
        # 为代理模型添加源模型
        self.filterModel.setSourceModel(listModel)
        # 在视图中使用代理模型
        self.listView.setModel(self.filterModel)
Exemplo n.º 44
0
    def addTree(self, opusDataPath, parentWidget):
        self.containerWidget = parentWidget
        self.opusDataPath = opusDataPath

        self.treeview = QTreeView()
        filters = QStringList()
        filters.append("*.*")
        #filters.append("*.py")
        #filters.append("*.shp")
        #filters.append("*.tif")
        self.model = QDirModel(filters,
                               QDir.Files | QDir.AllDirs | QDir.NoDotAndDotDot,
                               QDir.Name)
        self.treeview.setModel(self.model)
        if self.opusDataPath:
            self.treeview.setRootIndex(self.model.index(self.opusDataPath))
        self.treeview.setColumnWidth(0, 200)
        self.treeview.hideColumn(2)
        self.treeview.hideColumn(3)

        self.containerWidget.layout().addWidget(self.treeview)

        # Hook up to the mousePressEvent and pressed
        self.treeview.setContextMenuPolicy(Qt.CustomContextMenu)
Exemplo n.º 45
0
    def __init__(self):
        super(ThirdPart, self).__init__()
        self.completed = False
        self.setTitle(u'第三方库设置')
        self.setSubTitle(u'需要设置的第三方库')
        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(14, 20, 10, 20)

        self.tw_interface = QTableWidget(0, 3)
        headerLabels = QStringList()
        headerLabels.append(u'库名')
        headerLabels.append(u'库路径')
        headerLabels.append(u'打开')
        self.tw_interface.setHorizontalHeaderLabels(headerLabels)
        self.tw_interface.setSelectionBehavior(1)
        self.tw_interface.setRowCount(0)
        self.tw_interface.setColumnWidth(0, 200)
        self.tw_interface.setColumnWidth(1, 280)
        self.tw_interface.horizontalHeader().setStretchLastSection(True)

        self.mhlayout = QHBoxLayout()
        on_new_btn = QPushButton()
        on_new_btn.setText(u'添加类库')
        on_new_btn.clicked.connect(self.on_new)

        on_delete_btn = QPushButton()
        on_delete_btn.setText(u'删除类库')
        on_delete_btn.clicked.connect(self.on_delete)

        space = QSpacerItem(40, 28, QSizePolicy.Expanding)
        self.mhlayout.addSpacerItem(space)
        self.mhlayout.addWidget(on_new_btn)
        self.mhlayout.addWidget(on_delete_btn)

        rootLayout.addWidget(self.tw_interface)
        rootLayout.addLayout(self.mhlayout)
        self.setLayout(rootLayout)
        self.setStyleSheet(sheetstyle)

        self.alloneEnv = os.getenv('ALLONEDIR', '../..').replace('\\', '/')
Exemplo n.º 46
0
    def __init__(self):
        super(BaseInfoPage, self).__init__()

        self.setTitle('工程配置')
        self.setSubTitle('设置工程的参数')
        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 30, 20, 30)

        self.project_name = ""
        self.project_dir = ""
        self.completed = False

        row1 = QHBoxLayout()
        lable1 = QLabel('工程名称:')
        self.et_project_name = QLineEdit()
        self.et_project_name.setTextMargins(-6, 0, 0, 0)
        self.et_project_name.textChanged.connect(self.on_text_changed)
        row1.addWidget(lable1)
        row1.addWidget(self.et_project_name)

        # row2 = QHBoxLayout()
        # lable2 = QLabel('工程位置:')
        # self.et_project_location = QLineEdit()
        # self.et_project_location.textChanged.connect(self.on_text_changed)
        # self.et_project_location.setReadOnly(True)
        # btn_location = QPushButton('...')
        # btn_location.setFixedWidth(50)
        # btn_location.clicked.connect(self.getSavePath)
        # row2.addWidget(lable2)
        # row2.addWidget(self.et_project_location)
        # row2.addWidget(btn_location)

        row3 = QHBoxLayout()
        lable3 = QLabel('源模板:   ')
        self.cb_wizard_type = QComboBox()
        items = QStringList()
        for key in app.g_templates:
            items.append(key)
        self.cb_wizard_type.addItems(items)
        row3.addWidget(lable3)
        row3.addWidget(self.cb_wizard_type)

        row4 = QHBoxLayout()
        lable4 = QLabel('平台类型:')
        checkboxLayout = QHBoxLayout()
        self.cb_pt_win = QCheckBox('Win')
        self.cb_pt_linux = QCheckBox('Linux')
        checkboxLayout.addWidget(self.cb_pt_win)
        checkboxLayout.addWidget(self.cb_pt_linux)
        row4.addWidget(lable4)
        row4.addLayout(checkboxLayout)

        row6 = QHBoxLayout()
        self.cb_pt_version = QComboBox()
        items_pt_version = QStringList()
        items_pt_version.append('x86')
        items_pt_version.append('x64')
        self.cb_pt_version.addItems(items_pt_version)
        row6.addWidget(QLabel('平台级别:'))
        row6.addWidget(self.cb_pt_version)

        row5 = QHBoxLayout()
        lable5 = QLabel('组件类型:')
        self.cb_component_type = QComboBox()
        items_component_type = QStringList()
        items_component_type.append('服务')
        items_component_type.append('窗口')
        self.cb_component_type.addItems(items_component_type)
        self.registerField('component_type*', self.cb_component_type)
        self.cb_component_type.currentIndexChanged.connect(
            self.on_currentIndex_Changed)
        row5.addWidget(lable5)
        row5.addWidget(self.cb_component_type)

        space1 = QSpacerItem(40, 28, QSizePolicy.Expanding)
        row7 = QHBoxLayout()
        lable7 = QLabel('翻译文件:')
        self.chkb_transFile = QCheckBox()
        row7.addWidget(lable7)
        row7.addWidget(self.chkb_transFile)
        row7.addSpacerItem(space1)

        space2 = QSpacerItem(40, 28, QSizePolicy.Expanding)
        row8 = QHBoxLayout()
        lable8 = QLabel('资源文件:')
        self.chkb_resourceFile = QCheckBox()
        row8.addWidget(lable8)
        row8.addWidget(self.chkb_resourceFile)
        row8.addSpacerItem(space2)

        rootLayout.addLayout(row1)
        rootLayout.addSpacing(10)
        rootLayout.addLayout(row3)
        rootLayout.addSpacing(10)
        rootLayout.addLayout(row5)
        rootLayout.addSpacing(10)
        rootLayout.addLayout(row6)
        rootLayout.addSpacing(10)
        rootLayout.addLayout(row7)
        rootLayout.addSpacing(10)
        rootLayout.addLayout(row8)
        rootLayout.addSpacing(31)

        self.setLayout(rootLayout)
        self.setStyleSheet(styleSheet)
Exemplo n.º 47
0
    #print(u'{0:08d} {1}'.format(stamp,description))

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv) # create an app
    from PyQt4.QtGui import QWidget
    import pqIMC
    IMC = pqIMC.tricorder()
    IMC.mainWindow = QWidget()
    beep()
    noteEvent("about to call infoMsg")
    infoMsg("This is the message","Did you hear that beep?")
    noteEvent("about to call getStringMsg")
    (s, b) = getStringMsg("TITLE STRING", "label text")
    if b : print( "got "+s)
    else: print("cancel")
    (s, b) = getStringMsg("TITLE STRING", "what you should enter", "prepared")
    if b : print( "got "+s)
    else: print("cancel")
    noteEvent("Whatever...")
    #ew = QTextEdit()
    #(b,qs) = getFindMsg(ew)
    #print(b,qs)
    qsl = QStringList()
    qsl.append("ONE")
    qsl.append("TWO")
    (s, b) = getChoiceMsg("TITLE STRING", "label text",qsl)
    if b : print ("Choice "+unicode(s))
    else: print ("Cancel "+unicode(s))
    printKeyEvent(
        QKeyEvent(QEvent.KeyPress,43,Qt.AltModifier|Qt.ControlModifier) )
Exemplo n.º 48
0
    myargs.pop(0)

    # Parse window title
    window_title = myargs[0]
    myargs.pop(0)
    # Parse description
    description = myargs[0]
    myargs.pop(0)

    mw.drawMainWindows()

    # Parse label descriptions
    ncolumn = 0
    while (ncolumn < column_number):
        label_descr = myargs[0]
        label_list.append(label_descr)
        myargs.pop(0)
        ncolumn += 1
    #print "labels: " + str(label_list)
    # Parse contents
    row = 0
    while myargs:
        new_harddisk = []
        ncolumn = 0
        while (ncolumn < column_number):
            new_harddisk_descr = myargs[0]
            new_harddisk.append(new_harddisk_descr)
            myargs.pop(0)
            ncolumn += 1
        harddisks.append(new_harddisk)
        mw.refresh_harddisks()
Exemplo n.º 49
0
class StringListDlg(QDialog):

    acceptedList = Signal(QStringList)

    def __init__(self, name, stringlist=None, parent=None):
        super(StringListDlg, self).__init__(parent)
        self.name = name
        self.create_widgets(stringlist)
        self.layout_widgets()
        self.setWindowTitle("Edit {0} List".format(self.name))

    def create_widgets(self, stringlist):
        self.listWidget = QListWidget()
        if stringlist is not None:
            self.listWidget.addItems(stringlist)
            self.listWidget.setCurrentRow(0)

    def layout_widgets(self):
        buttonLayout = QVBoxLayout()
        for text, slot in (("&Add...", self.add), ("&Edit...", self.edit),
                           ("&Remove...", self.remove), ("&Up", self.up),
                           ("&Down", self.down), ("&Sort",
                                                  self.listWidget.sortItems),
                           ("Close", self.accept)):
            button = QPushButton(text)
            if not MAC:
                button.setFocusPolicy(Qt.NoFocus)
            if text == "Close":
                buttonLayout.addStretch()
            buttonLayout.addWidget(button)
            button.clicked.connect(slot)
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)

    def add(self):
        row = self.listWidget.currentRow()
        title = "Add {0}".format(self.name)
        string, ok = QInputDialog.getText(self, title, title)
        if ok and not string.isEmpty():
            self.listWidget.insertItem(row, string)

    def edit(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is not None:
            title = "Edit {0}".format(self.name)
            string, ok = QInputDialog.getText(self, title, title,
                                              QLineEdit.Normal, item.text())
            if ok and not string.isEmpty():
                item.setText(string)

    def remove(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        reply = QMessageBox.question(
            self, "Remove {0}".format(self.name),
            "Remove {0} `{1}'?".format(self.name, unicode(item.text())),
            QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            item = self.listWidget.takeItem(row)
            del item

    def up(self):
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row - 1, item)
            self.listWidget.setCurrentItem(item)

    def down(self):
        row = self.listWidget.currentRow()
        if row < self.listWidget.count() - 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + 1, item)
            self.listWidget.setCurrentItem(item)

    def reject(self):
        self.accept()

    def accept(self):
        self.stringlist = QStringList()
        for row in range(self.listWidget.count()):
            self.stringlist.append(self.listWidget.item(row).text())
        self.acceptedList.emit(self.stringlist)
        QDialog.accept(self)
Exemplo n.º 50
0
    def __init__(self):
        super(BaseInfoPage, self).__init__()

        self.setTitle('工程配置')
        self.setSubTitle('设置工程的参数')
        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 30, 20, 30)

        self.project_name = ""
        self.project_dir = ""
        self.completed = False

        row1 = QHBoxLayout()
        lable1 = QLabel('工程名称:')
        self.et_project_name = QLineEdit()
        self.et_project_name.textChanged.connect(self.on_text_changed)
        row1.addWidget(lable1)
        row1.addWidget(self.et_project_name)
        row1.addSpacing(200)

        # row2 = QHBoxLayout()
        # lable2 = QLabel('工程位置:')
        # self.et_project_location = QLineEdit()
        # self.et_project_location.textChanged.connect(self.on_text_changed)
        # self.et_project_location.setReadOnly(True)
        # btn_location = QPushButton('...')
        # btn_location.setFixedWidth(50)
        # btn_location.clicked.connect(self.getSavePath)
        # row2.addWidget(lable2)
        # row2.addWidget(self.et_project_location)
        # row2.addWidget(btn_location)

        row3 = QHBoxLayout()
        lable3 = QLabel('源模板  :')
        self.cb_wizard_type = QComboBox()
        items = QStringList()
        for key in app.g_templates:
            items.append(key)
        self.cb_wizard_type.addItems(items)
        row3.addWidget(lable3)
        row3.addWidget(self.cb_wizard_type)
        row3.addStretch(0)

        row4 = QHBoxLayout()
        lable4 = QLabel('平台类型:')
        checkboxLayout = QHBoxLayout()
        self.cb_pt_win = QCheckBox('Win')
        self.cb_pt_linux = QCheckBox('Linux')
        checkboxLayout.addWidget(self.cb_pt_win)
        checkboxLayout.addWidget(self.cb_pt_linux)
        row4.addWidget(lable4)
        row4.addLayout(checkboxLayout)
        row4.addStretch(0)

        row6 = QHBoxLayout()
        self.cb_pt_version = QComboBox()
        items_pt_version = QStringList()
        items_pt_version.append('x86')
        items_pt_version.append('x64')
        self.cb_pt_version.addItems(items_pt_version)
        row6.addWidget(QLabel('平台级别:'))
        row6.addWidget(self.cb_pt_version)
        row6.addStretch(0)

        row5 = QHBoxLayout()
        lable5 = QLabel('组件类型:')
        self.cb_component_type = QComboBox()
        items_component_type = QStringList()
        items_component_type.append('服务')
        items_component_type.append('窗口')
        self.cb_component_type.addItems(items_component_type)
        row5.addWidget(lable5)
        row5.addWidget(self.cb_component_type)
        row5.addStretch(0)

        rootLayout.addLayout(row1)
        #rootLayout.addLayout(row2)
        rootLayout.addLayout(row3)
        rootLayout.addLayout(row5)
        rootLayout.addLayout(row6)
        #rootLayout.addLayout(row4)

        self.setLayout(rootLayout)
Exemplo n.º 51
0
    listWidgetItem.setToolTip("this is b!")

    listWidget.insertItem(1, listWidgetItem)
    # 设置排序为倒序
    listWidget.sortItems(Qt.DescendingOrder)
    # 显示列表部件
    listWidget.show()

    #********************** 2. QTreeWidget *******************/

    treeWidget  = QTreeWidget()
    # 必须设置列数
    treeWidget.setColumnCount(2)
    # 设置标头
    headers = QStringList()
    headers.append("name")
    headers.append("year")

    treeWidget.setHeaderLabels(headers)
    # 添加项目
    grade1 =  QTreeWidgetItem(treeWidget)
    grade1.setText(0,"Grade1")
    student =  QTreeWidgetItem(grade1)
    student.setText(0,"Tom")
    student.setText(1,"1986")
    grade2 =  QTreeWidgetItem(treeWidget, grade1)
    grade2.setText(0,"Grade2")
    treeWidget.show()

    #********************* 3. QTableWidget ********************/
    # 创建表格部件,同时指定行数和列数
Exemplo n.º 52
0
#include <QApplication>

#include <QListView>
#include <QTableView>
#include <QDebug>
import sys
from PyQt4.QtCore import QStringList
from PyQt4.QtGui import QApplication, QListView, QTableView
from stringlistmodel import StringListModel

if __name__ == "__main__":

    app = QApplication(sys.argv)

    qlist = QStringList()
    qlist.append("a")
    qlist.append("b")
    qlist.append("c")
    qlist.append("abcd")

    model = StringListModel(qlist)

    qlistView = QListView()
    qlistView.setModel(model)
    qlistView.show()

    tableView = QTableView()
    tableView.setModel(model)
    tableView.show()

    app.exec_()
Exemplo n.º 53
0
 def accept(self):
     
     if(not self.checkOptions()):
         return
     
     self.resize(520, 610)
     
     if(self.comboBoxSource.currentText() == self.SOURCES[0]):
         if(self.comboBoxMethod == self.METHODS[0]):
             meth_abv = self.METHODS_ABRV[0]
         else:
             meth_abv = self.METHODS_ABRV[1]
         args = QStringList()
         args.append("-i" + self.filePathSource.text())
         args.append("-o" + self.filePathOutput.text())
         args.append("-m" + meth_abv)
         self.proc = QProcess()
         self.proc.start("asc2hasc", args)
         self.proc.setProcessChannelMode(QProcess.MergedChannels);
         QObject.connect(self.proc, SIGNAL("readyReadStandardOutput()"), self, SLOT("readStdOutput()"))
         #self.setGeometry(self._parent.x(), self._parent.y(), self.width(), 610)
         
     if(self.comboBoxSource.currentText() == self.SOURCES[1]):
         args = QStringList()
         args.append("-i" + self.filePathSource.text())
         args.append("-o" + self.filePathOutput.text())
         args.append("-s" + self.cellSide.text())
         self.proc = QProcess()
         self.proc.start("csv2hasc", args)
         self.proc.setProcessChannelMode(QProcess.MergedChannels);
         QObject.connect(self.proc, SIGNAL("readyReadStandardOutput()"), self, SLOT("readStdOutput()"))
         
     if(self.comboBoxSource.currentText() == self.SOURCES[2]):
         args = QStringList()
         args.append("-m" + self.filePathSource.text())
         args.append("-o" + self.filePathOutput.text())
         args.append("-f" + self.pythonFunction.text())
         args.append("-s" + self.cellSide.text())
         args.append("-x" + self.eastingRight.text())
         args.append("-X" + self.eastingLeft.text())
         args.append("-y" + self.northingBottom.text())
         args.append("-Y" + self.northingTop.text())
         self.proc = QProcess()
         self.proc.start("surface2hasc", args)
         self.proc.setProcessChannelMode(QProcess.MergedChannels);
         QObject.connect(self.proc, SIGNAL("readyReadStandardOutput()"), self, SLOT("readStdOutput()"))  
Exemplo n.º 54
0
class CmdProc(QObject):
    'Run mercurial command in separate process'

    started = pyqtSignal()
    commandFinished = pyqtSignal(int)
    outputReceived = pyqtSignal(QString, QString)

    # progress is not supported but needed to be a worker class
    progressReceived = pyqtSignal(QString, object, QString, QString, object)

    def __init__(self, cmdline, parent=None):
        super(CmdProc, self).__init__(parent)
        self.cmdline = cmdline
        self.abortbyuser = False
        self.rawoutput = QStringList()

        self._proc = proc = QProcess(self)
        proc.started.connect(self.started)
        proc.finished.connect(self._finished)
        proc.readyReadStandardOutput.connect(self._stdout)
        proc.readyReadStandardError.connect(self._stderr)
        proc.error.connect(self._handleerror)

    def start(self):
        self._proc.start(_findhgexe(), self.cmdline, QIODevice.ReadOnly)

    def abort(self):
        if not self.isRunning():
            return
        self._proc.close()
        self.abortbyuser = True

    def isRunning(self):
        return self._proc.state() != QProcess.NotRunning

    @pyqtSlot(int)
    def _finished(self, ret):
        if ret:
            msg = _('[command returned code %d %%s]') % int(ret)
        else:
            msg = _('[command completed successfully %s]')
        msg = msg % time.asctime() + '\n'
        self.outputReceived.emit(msg, 'control')
        self.commandFinished.emit(ret)

    def _handleerror(self, error):
        if error == QProcess.FailedToStart:
            self.outputReceived.emit(_('failed to start command\n'),
                                     'ui.error')
            self._finished(-1)
        elif error != QProcess.Crashed:
            self.outputReceived.emit(_('error while running command\n'),
                                     'ui.error')

    def _stdout(self):
        data = self._proc.readAllStandardOutput().data()
        self.rawoutput.append(hglib.tounicode(data))
        self.outputReceived.emit(hglib.tounicode(data), '')

    def _stderr(self):
        data = self._proc.readAllStandardError().data()
        self.outputReceived.emit(hglib.tounicode(data), 'ui.error')
Exemplo n.º 55
0
#!/usr/bin/env python
# coding=utf-8

from PyQt4.QtGui import QApplication, QAbstractItemView, QListView, QTableView
from PyQt4.QtCore import QStringList
import sys
from stringlistmodel import StringListModel

if __name__ == "__main__":
    app = QApplication(sys.argv)

    slist = QStringList()
    slist.append("a")
    slist.append("b")
    slist.append("c")
    slist.append("d")

    listView = QListView()
    '''
    PyQt使用Model时,如果Model创建时未设置parent,则运行完退出时会报错:
    QObject::startTimer: QTimer can only be used with threads started with QThread
    '''
    # model = StringListModel(slist)
    model = StringListModel(slist, listView)

    listView.setModel(model)
    listView.show()

    tableView = QTableView()
    tableView.setModel(model)
    tableView.show()
Exemplo n.º 56
0
    def testTransparency(self):
        myPath = os.path.join(unitTestDataPath('raster'),
                              'band1_float32_noct_epsg4326.tif')
        myFileInfo = QFileInfo(myPath)
        myBaseName = myFileInfo.baseName()
        myRasterLayer = QgsRasterLayer(myPath, myBaseName)
        myMessage = 'Raster not loaded: %s' % myPath
        assert myRasterLayer.isValid(), myMessage

        renderer = QgsSingleBandGrayRenderer(myRasterLayer.dataProvider(), 1)
        myRasterLayer.setRenderer(renderer)
        myRasterLayer.setContrastEnhancement(
            QgsContrastEnhancement.StretchToMinimumMaximum,
            QgsRaster.ContrastEnhancementMinMax)

        myContrastEnhancement = myRasterLayer.renderer().contrastEnhancement()
        #print ("myContrastEnhancement.minimumValue = %.17g" %
        #       myContrastEnhancement.minimumValue())
        #print ("myContrastEnhancement.maximumValue = %.17g" %
        #        myContrastEnhancement.maximumValue())

        # Unfortunately the minimum/maximum values calculated in C++ and Python
        # are slightly different (e.g. 3.3999999521443642e+38 x
        # 3.3999999521444001e+38)
        # It is not clear where the precision is lost.
        # We set the same values as C++.
        myContrastEnhancement.setMinimumValue(-3.3319999287625854e+38)
        myContrastEnhancement.setMaximumValue(3.3999999521443642e+38)
        #myType = myRasterLayer.dataProvider().dataType(1);
        #myEnhancement = QgsContrastEnhancement(myType);

        myTransparentSingleValuePixelList = []
        rasterTransparency = QgsRasterTransparency()

        myTransparentPixel1 = \
            QgsRasterTransparency.TransparentSingleValuePixel()
        myTransparentPixel1.min = -2.5840000772112106e+38
        myTransparentPixel1.max = -1.0879999684602689e+38
        myTransparentPixel1.percentTransparent = 50
        myTransparentSingleValuePixelList.append(myTransparentPixel1)

        myTransparentPixel2 = \
            QgsRasterTransparency.TransparentSingleValuePixel()
        myTransparentPixel2.min = 1.359999960575336e+37
        myTransparentPixel2.max = 9.520000231087593e+37
        myTransparentPixel2.percentTransparent = 70
        myTransparentSingleValuePixelList.append(myTransparentPixel2)

        rasterTransparency.setTransparentSingleValuePixelList(
            myTransparentSingleValuePixelList)

        rasterRenderer = myRasterLayer.renderer()
        assert rasterRenderer

        rasterRenderer.setRasterTransparency(rasterTransparency)

        QgsMapLayerRegistry.instance().addMapLayers([
            myRasterLayer,
        ])

        myMapRenderer = QgsMapRenderer()

        myLayers = QStringList()
        myLayers.append(myRasterLayer.id())
        myMapRenderer.setLayerSet(myLayers)
        myMapRenderer.setExtent(myRasterLayer.extent())

        myChecker = QgsRenderChecker()
        myChecker.setControlName("expected_raster_transparency")
        myChecker.setMapRenderer(myMapRenderer)

        myResultFlag = myChecker.runTest("raster_transparency_python")
        assert myResultFlag, "Raster transparency rendering test failed"
Exemplo n.º 57
0
    def showConfigInfo(self, cf):
        '''显示配置信息'''
        self.tw_config.clear()
        self.et_project_name.setText(cf.project_name)
        self.et_project_location.setText(cf.project_location)
        sr = QStringList()
        sr.append('信息')
        root1 = QTreeWidgetItem(sr)
        sr = QStringList()
        sr.append('Qt库')
        root2 = QTreeWidgetItem(sr)
        sr = QStringList()
        sr.append('模块')
        root3a = QTreeWidgetItem(sr)
        sr = QStringList()
        sr.append('第三方库')
        root3b = QTreeWidgetItem(sr)
        sr = QStringList()
        sr.append('接口')
        root4 = QTreeWidgetItem(sr)

        self.tw_config.addTopLevelItem(root1)
        self.tw_config.addTopLevelItem(root2)
        self.tw_config.addTopLevelItem(root3a)
        self.tw_config.addTopLevelItem(root3b)
        self.tw_config.addTopLevelItem(root4)

        sr1c00 = QStringList()
        sr1c00.append("项目名称")
        sr1c00.append(cf.project_name)
        r1c00 = QTreeWidgetItem(sr1c00)
        root1.addChild(r1c00)

        # sr1c0 = QStringList()
        # sr1c0.append("项目位置")
        # sr1c0.append(cf.project_location)
        # r1c0 = QTreeWidgetItem(sr1c0)
        # root1.addChild(r1c0)

        sr1c1 = QStringList()
        sr1c1.append("组件类型")
        sr1c1.append(cf.component_type)
        r1c1 = QTreeWidgetItem(sr1c1)
        root1.addChild(r1c1)

        sr1c2 = QStringList()
        sr1c2.append("源模板")
        sr1c2.append(cf.template_source)
        r1c2 = QTreeWidgetItem(sr1c2)
        root1.addChild(r1c2)

        sr1c3 = QStringList()
        sr1c3.append("平台类型")
        tmp_pt = ""
        if cf.platform_type & configuration.PT_WIN32:
            tmp_pt += "win32;"
        if cf.platform_type & configuration.PT_LINUX:
            tmp_pt += "linux"

        sr1c3.append(tmp_pt)
        r1c3 = QTreeWidgetItem(sr1c3)
        root1.addChild(r1c3)

        sr1c4 = QStringList()
        sr1c4.append("平台级别")
        sr1c4.append(cf.platform_version)
        r1c4 = QTreeWidgetItem(sr1c4)
        root1.addChild(r1c4)

        sr1c5 = QStringList()
        sr1c5.append("资源文件")
        if cf.resourcesFile == "True":
            sr1c5.append("添加")
        else:
            sr1c5.append("未添加")
        r1c5 = QTreeWidgetItem(sr1c5)
        root1.addChild(r1c5)

        sr1c6 = QStringList()
        sr1c6.append("翻译文件")
        if cf.translateFile == "True":
            sr1c6.append("添加")
        else:
            sr1c6.append("未添加")
        r1c6 = QTreeWidgetItem(sr1c6)
        root1.addChild(r1c6)

        for qt in cf.qt_libs:
            sr2 = QStringList()
            sr2.append(qt['name'])
            sr2.append(qt['qt'])
            r2 = QTreeWidgetItem(sr2)
            root2.addChild(r2)

        for module in cf.modules:
            sr3a = QStringList()
            sr3a.append(module['name'])
            sr3a.append(module['description'])
            r3a = QTreeWidgetItem(sr3a)
            root3a.addChild(r3a)

        # sr3b = QStringList()
        # sr3b.append('ALLONE_DIR')
        # sr3b.append(os.getenv('ALLONEDIR','../..')) # 第二个参数是默认值
        # r3b = QTreeWidgetItem(sr3b)
        # root3b.addChild(r3b)
        for info in cf.thirdpart_lib:
            sr3b = QStringList()
            sr3b.append(info['libname'])
            sr3b.append(info['libpath'])
            r3b = QTreeWidgetItem(sr3b)
            root3b.addChild(r3b)

        for key in cf.interfaces.keys():
            sr4 = QStringList()
            sr4.append(key)
            if cf.interfaces[key]:
                sr4.append('实现')
            else:
                sr4.append('未实现')
            r4 = QTreeWidgetItem(sr4)
            root4.addChild(r4)
        self.tw_config.expandAll()
        self.tw_config.header().resizeSection(0, 300)
        self.tGroup.setEnabled(True)