本文整理汇总了Python中pyqtcore.QMap.insert方法的典型用法代码示例。如果您正苦于以下问题:Python QMap.insert方法的具体用法?Python QMap.insert怎么用?Python QMap.insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyqtcore.QMap
的用法示例。
在下文中一共展示了QMap.insert方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FormatHelper
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
class FormatHelper():
def __init__(self, capabilities, initialFilter):
self.mFilter = initialFilter
self.mFormats = QList()
self.mFormatByNameFilter = QMap()
def t(self, format):
if (format.hasCapabilities(capabilities)):
nameFilter = format.nameFilter()
self.mFilter += ";;"
self.mFilter += nameFilter
self.mFormats.append(format)
self.mFormatByNameFilter.insert(nameFilter, format)
PluginManager.each(self, t)
def filter(self):
return self.mFilter
def formats(self):
return self.mFormats
def formatByNameFilter(self, nameFilter):
return self.mFormatByNameFilter.value(nameFilter)
示例2: FileSystemWatcher
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
class FileSystemWatcher(QObject):
fileChanged = pyqtSignal(str)
directoryChanged = pyqtSignal(str)
def __init__(self, parent = None):
super().__init__(parent)
self.mWatchCount = QMap()
self.mWatcher = QFileSystemWatcher(self)
self.mWatcher.fileChanged.connect(self.onFileChanged)
self.mWatcher.directoryChanged.connect(self.onDirectoryChanged)
def addPath(self, path):
# Just silently ignore the request when the file doesn't exist
if (not QFile.exists(path)):
return
entry = self.mWatchCount.find(path)
if not entry:
self.mWatcher.addPath(path)
self.mWatchCount.insert(path, 1)
else:
# Path is already being watched, increment watch count
self.mWatchCount[path] += 1
def removePath(self, path):
entry = self.mWatchCount.find(path)
if (entry == self.mWatchCount.end()):
if (QFile.exists(path)):
qWarning("FileSystemWatcher: Path was never added:\n"+path)
return
# Decrement watch count
entry -= 1
self.mWatchCount[path] = entry
if (entry == 0):
self.mWatchCount.erase(path)
self.mWatcher.removePath(path)
def onFileChanged(self, path):
# If the file was replaced, the watcher is automatically removed and needs
# to be re-added to keep watching it for changes. This happens commonly
# with applications that do atomic saving.
if (not self.mWatcher.files().__contains__(path)):
if (QFile.exists(path)):
self.mWatcher.addPath(path)
self.fileChanged.emit(path)
def onDirectoryChanged(self, path):
self.directoryChanged.emit(path)
示例3: RandomPicker
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
class RandomPicker():
def __init__(self):
self.mSum = 0.0
self.mThresholds = QMap()
def add(self, value, probability = 1.0):
self.mSum += probability
self.mThresholds.insert(self.mSum, value)
def isEmpty(self):
return self.mThresholds.isEmpty()
def pick(self):
random = (rand() / RAND_MAX) * self.mSum
it = self.mThresholds.lowerBound(random)
if (it != self.mThresholds.end()):
return self.mThresholds.itemByIndex(it)[1]
else:
return self.mThresholds.itemByIndex(-1)[1]
def clear(self):
self.mSum = 0.0
self.mThresholds.clear()
示例4: RangeSet
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
class RangeSet():
# This class is based on std.map rather than QMap since std.map's insert
# method has an overload that takes a hint about where to insert the new
# pair.
def __init__(self):
self.mMap = QMap()
##
# Insert \a value in the set of ranges. Has no effect when the value is
# already part of an existing range. When possible, an existing range is
# extended to include the new value, otherwise a new range is inserted.
##
def insert(self, value):
if (self.mMap.empty()):
self.mMap.insert(value, value)
return
# We can now assume that 'it' will be at most one end of the range
# This is the only full-tree search of the map, everything else is
# relative to this
it = self.mMap.lowerBound(value)
itValue = self.mMap.itemByIndex(it)
begin = self.mMap.begin()
end = self.mMap.end()
if (it == end):
# Check whether the value is included in the last range
# assert: it != begin
it -= 1
itValue = self.mMap.itemByIndex(it)
# assert: it.first < value
if (itValue[1] >= value):
return
# Try to add the value to the end of the previous range
itValue[1] += 1
if (itValue[1] == value):
return
# Didn't work, restore the previous range
itValue[1] -= 1
# We have to insert a new range
self.mMap.insert(it, [value, value])
return
# Now we can dereference 'it' itself
# assert: it.first >= value
if (itValue[0] == value):
return
# Check whether we can extend the range downwards to include value
if (itValue[0] == value + 1):
# When extending the range downwards, it may need to be merged
# with the previous range.
# Remember 'prev' for the insertion hint. It is not necessarily
# before the value, if it == begin.
prev = itValue
if (it != begin):
prev = self.mMap.itemByIndex(prev-1)
if (prev[1] == value - 1):
# The new value fills the gab. Merge the ranges, leaving
# only the first, but with a larger range.
prev[1] = itValue[1]
self.mMap.erase(itValue[0])
return
# No merge needed
# To change the key, we have to both add and remove. Add first,
# then remove, to avoid invalidating the iterator too early.
self.mMap.insert(prev, [value, itValue[1]])
self.mMap.erase(it)
return
# Check if we can grow the previous range upwards to include value
if (it != begin):
it -= 1
itValue = self.mMap.itemByIndex(it)
if (itValue[1] == value - 1):
itValue[1] += 1
return
# 'it' now points below the range, unless it was already begin
# We couldn't increase an existing range
self.mMap.insert(it, [value, value])
##
# Removes all ranges from this set.
##
def clear(self):
self.mMap.clear()
# Only are provided, because it is not safe to modify the
# underlying list. Note that const_iterator is a typedef for Range.
def begin(self):
return self.mMap.begin()
def end(self):
return self.mMap.end()
def isEmpty(self):
return self.mMap.empty()
#.........这里部分代码省略.........
示例5: TilesetManager
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
class TilesetManager(QObject):
mInstance = None
##
# Emitted when a tileset's images have changed and views need updating.
##
tilesetChanged = pyqtSignal(Tileset)
##
# Emitted when any images of the tiles in the given \a tileset have
# changed. This is used to trigger repaints for displaying tile
# animations.
##
repaintTileset = pyqtSignal(Tileset)
##
# Constructor. Only used by the tileset manager it
##
def __init__(self):
super().__init__()
##
# Stores the tilesets and maps them to the number of references.
##
self.mTilesets = QMap()
self.mChangedFiles = QSet()
self.mWatcher = FileSystemWatcher(self)
self.mAnimationDriver = TileAnimationDriver(self)
self.mReloadTilesetsOnChange = False
self.mChangedFilesTimer = QTimer()
self.mWatcher.fileChanged.connect(self.fileChanged)
self.mChangedFilesTimer.setInterval(500)
self.mChangedFilesTimer.setSingleShot(True)
self.mChangedFilesTimer.timeout.connect(self.fileChangedTimeout)
self.mAnimationDriver.update.connect(self.advanceTileAnimations)
##
# Destructor.
##
def __del__(self):
# Since all MapDocuments should be deleted first, we assert that there are
# no remaining tileset references.
self.mTilesets.size() == 0
##
# Requests the tileset manager. When the manager doesn't exist yet, it
# will be created.
##
def instance():
if (not TilesetManager.mInstance):
TilesetManager.mInstance = TilesetManager()
return TilesetManager.mInstance
##
# Deletes the tileset manager instance, when it exists.
##
def deleteInstance():
del TilesetManager.mInstance
TilesetManager.mInstance = None
def findTileset(self, arg):
tp = type(arg)
if tp in [QString, str]:
##
# Searches for a tileset matching the given file name.
# @return a tileset matching the given file name, or 0 if none exists
##
fileName = arg
for tileset in self.tilesets():
if (tileset.fileName() == fileName):
return tileset
return None
elif tp==TilesetSpec:
##
# Searches for a tileset matching the given specification.
# @return a tileset matching the given specification, or 0 if none exists
##
spec = arg
for tileset in self.tilesets():
if (tileset.imageSource() == spec.imageSource
and tileset.tileWidth() == spec.tileWidth
and tileset.tileHeight() == spec.tileHeight
and tileset.tileSpacing() == spec.tileSpacing
and tileset.margin() == spec.margin):
return tileset
return None
##
# Adds a tileset reference. This will make sure the tileset is watched for
# changes and can be found using findTileset().
##
def addReference(self, tileset):
if (self.mTilesets.contains(tileset)):
self.mTilesets[tileset] += 1
else:
self.mTilesets.insert(tileset, 1)
imgSrc = tileset.imageSource()
if (imgSrc != ''):
self.mWatcher.addPath(imgSrc)
#.........这里部分代码省略.........
示例6: MapObjectModel
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
#.........这里部分代码省略.........
if (not index.isValid()):
return None
oog = index.internalPointer()
if oog:
if oog.mGroup:
_x = oog.mGroup
else:
_x = oog.mObject.objectGroup()
return _x
def setMapDocument(self, mapDocument):
if (self.mMapDocument == mapDocument):
return
if (self.mMapDocument):
self.mMapDocument.disconnect()
self.beginResetModel()
self.mMapDocument = mapDocument
self.mMap = None
self.mObjectGroups.clear()
self.mGroups.clear()
self.mGroups.clear()
self.mObjects.clear()
self.mObjects.clear()
if (self.mMapDocument):
self.mMap = self.mMapDocument.map()
self.mMapDocument.layerAdded.connect(self.layerAdded)
self.mMapDocument.layerChanged.connect(self.layerChanged)
self.mMapDocument.layerAboutToBeRemoved.connect(self.layerAboutToBeRemoved)
for og in self.mMap.objectGroups():
if GROUPS_IN_DISPLAY_ORDER:
self.mObjectGroups.prepend(og)
else:
self.mObjectGroups.append(og)
self.mGroups.insert(og, ObjectOrGroup(og))
for o in og.objects():
self.mObjects.insert(o, ObjectOrGroup(o))
self.endResetModel()
def insertObject(self, og, index, o):
if (index >= 0):
_x = index
else:
_x = og.objectCount()
row = _x
self.beginInsertRows(self.index(og), row, row)
og.insertObject(row, o)
self.mObjects.insert(o, ObjectOrGroup(o))
self.endInsertRows()
self.objectsAdded.emit(QList([o]))
def removeObject(self, og, o):
objects = QList()
objects.append(o)
row = og.objects().indexOf(o)
self.beginRemoveRows(self.index(og), row, row)
og.removeObjectAt(row)
self.mObjects.remove(o)
self.endRemoveRows()
self.objectsRemoved.emit(objects)
return row
def moveObjects(self, og, _from, to, count):
parent = self.index(og)
if (not self.beginMoveRows(parent, _from, _from + count - 1, parent, to)):
return
示例7: TileStampManager
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
#.........这里部分代码省略.........
self.mTileStampModel.clear()
self.loadStamps()
def eraseQuickStamp(self, index):
stamp = self.mQuickStamps.at(index)
if (not stamp.isEmpty()):
self.mQuickStamps[index] = TileStamp()
if (not self.mQuickStamps.contains(stamp)):
self.mTileStampModel.removeStamp(stamp)
def setQuickStamp(self, index, stamp):
stamp.setQuickStampIndex(index)
# make sure existing quickstamp is removed from stamp model
self.eraseQuickStamp(index)
self.mTileStampModel.addStamp(stamp)
self.mQuickStamps[index] = stamp
def loadStamps(self):
prefs = preferences.Preferences.instance()
stampsDirectory = prefs.stampsDirectory()
stampsDir = QDir(stampsDirectory)
iterator = QDirIterator(stampsDirectory,
["*.stamp"],
QDir.Files | QDir.Readable)
while (iterator.hasNext()):
stampFileName = iterator.next()
stampFile = QFile(stampFileName)
if (not stampFile.open(QIODevice.ReadOnly)):
continue
data = stampFile.readAll()
document = QJsonDocument.fromBinaryData(data)
if (document.isNull()):
# document not valid binary data, maybe it's an JSON text file
error = QJsonParseError()
document = QJsonDocument.fromJson(data, error)
if (error.error != QJsonParseError.NoError):
qDebug("Failed to parse stamp file:" + error.errorString())
continue
stamp = TileStamp.fromJson(document.object(), stampsDir)
if (stamp.isEmpty()):
continue
stamp.setFileName(iterator.fileInfo().fileName())
self.mTileStampModel.addStamp(stamp)
index = stamp.quickStampIndex()
if (index >= 0 and index < self.mQuickStamps.size()):
self.mQuickStamps[index] = stamp
def stampAdded(self, stamp):
if (stamp.name().isEmpty() or self.mStampsByName.contains(stamp.name())):
# pick the first available stamp name
name = QString()
index = self.mTileStampModel.stamps().size()
while(self.mStampsByName.contains(name)):
name = str(index)
index += 1
stamp.setName(name)
self.mStampsByName.insert(stamp.name(), stamp)
if (stamp.fileName().isEmpty()):
stamp.setFileName(findStampFileName(stamp.name()))
self.saveStamp(stamp)
def stampRenamed(self, stamp):
existingName = self.mStampsByName.key(stamp)
self.mStampsByName.remove(existingName)
self.mStampsByName.insert(stamp.name(), stamp)
existingFileName = stamp.fileName()
newFileName = findStampFileName(stamp.name(), existingFileName)
if (existingFileName != newFileName):
if (QFile.rename(stampFilePath(existingFileName),
stampFilePath(newFileName))):
stamp.setFileName(newFileName)
def saveStamp(self, stamp):
# make sure we have a stamps directory
prefs = preferences.Preferences.instance()
stampsDirectory = prefs.stampsDirectory()
stampsDir = QDir(stampsDirectory)
if (not stampsDir.exists() and not stampsDir.mkpath(".")):
qDebug("Failed to create stamps directory" + stampsDirectory)
return
filePath = stampsDir.filePath(stamp.fileName())
file = QSaveFile(filePath)
if (not file.open(QIODevice.WriteOnly)):
qDebug("Failed to open stamp file for writing" + filePath)
return
stampJson = stamp.toJson(QFileInfo(filePath).dir())
file.write(QJsonDocument(stampJson).toJson(QJsonDocument.Compact))
if (not file.commit()):
qDebug() << "Failed to write stamp" << filePath
def deleteStamp(self, stamp):
self.mStampsByName.remove(stamp.name())
QFile.remove(stampFilePath(stamp.fileName()))
示例8: MapScene
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
#.........这里部分代码省略.........
# Adapts the scene, layers and objects to new map size, orientation or
# background color.
##
def mapChanged(self):
self.updateSceneRect()
for item in self.mLayerItems:
tli = item
if type(tli) == TileLayerItem:
tli.syncWithTileLayer()
for item in self.mObjectItems.values():
item.syncWithMapObject()
map = self.mMapDocument.map()
if (map.backgroundColor().isValid()):
self.setBackgroundBrush(map.backgroundColor())
else:
self.setBackgroundBrush(self.mDefaultBackgroundColor)
def tilesetChanged(self, tileset):
if (not self.mMapDocument):
return
if (contains(self.mMapDocument.map().tilesets(), tileset)):
self.update()
def tileLayerDrawMarginsChanged(self, tileLayer):
index = self.mMapDocument.map().layers().indexOf(tileLayer)
item = self.mLayerItems.at(index)
item.syncWithTileLayer()
def layerAdded(self, index):
layer = self.mMapDocument.map().layerAt(index)
layerItem = self.createLayerItem(layer)
self.addItem(layerItem)
self.mLayerItems.insert(index, layerItem)
z = 0
for item in self.mLayerItems:
item.setZValue(z)
z += 1
def layerRemoved(self, index):
self.mLayerItems.remove(index)
##
# A layer has changed. This can mean that the layer visibility, opacity or
# offset changed.
##
def layerChanged(self, index):
layer = self.mMapDocument.map().layerAt(index)
layerItem = self.mLayerItems.at(index)
layerItem.setVisible(layer.isVisible())
multiplier = 1
if (self.mHighlightCurrentLayer and self.mMapDocument.currentLayerIndex() < index):
multiplier = opacityFactor
layerItem.setOpacity(layer.opacity() * multiplier)
layerItem.setPos(layer.offset())
# Layer offset may have changed, affecting the scene rect and grid
self.updateSceneRect()
if self.mGridVisible:
self.update()
##
# When an object group has changed it may mean its color or drawing order
# changed, which affects all its objects.
##
def objectGroupChanged(self, objectGroup):
示例9: GidMapper
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
class GidMapper():
##
# Default constructor. Use \l insert to initialize the gid mapper
# incrementally.
##
def __init__(self, *args):
self.mInvalidTile = None
self.mTilesetColumnCounts = QMap()
self.mFirstGidToTileset = QMap()
if len(args)==1:
##
# Constructor that initializes the gid mapper using the given \a tilesets.
##
firstGid = 1
tilesets = args[0]
for tileset in tilesets:
self.insert(firstGid, tileset)
firstGid += tileset.tileCount()
##
# Insert the given \a tileset with \a firstGid as its first global ID.
##
def insert(self, firstGid, tileset):
self.mFirstGidToTileset.insert(firstGid, tileset)
##
# Clears the gid mapper, so that it can be reused.
##
def clear(self):
self.mFirstGidToTileset.clear()
##
# Returns True when no tilesets are known to this gid mapper.
##
def isEmpty(self):
return self.mFirstGidToTileset.isEmpty()
##
# Returns the GID of the invalid tile in case decodeLayerData() returns
# the InvalidTile error.
##
def invalidTile(self):
return self.mInvalidTile
##
# Returns the cell data matched by the given \a gid. The \a ok parameter
# indicates whether an error occurred.
##
def gidToCell(self, gid):
result = Cell()
# Read out the flags
result.flippedHorizontally = (gid & FlippedHorizontallyFlag)
result.flippedVertically = (gid & FlippedVerticallyFlag)
result.flippedAntiDiagonally = (gid & FlippedAntiDiagonallyFlag)
# Clear the flags
gid &= ~(FlippedHorizontallyFlag |
FlippedVerticallyFlag |
FlippedAntiDiagonallyFlag)
if (gid == 0):
ok = True
elif (self.isEmpty()):
ok = False
else:
# Find the tileset containing this tile
index = self.mFirstGidToTileset.upperBound(gid)
if index==0:
ok = False
else:
item = self.mFirstGidToTileset.itemByIndex(index-1)
# Navigate one tileset back since upper bound finds the next
tileId = gid - item[0]
tileset = item[1]
columnCount = self.mTilesetColumnCounts.value(tileset, 0)
if (columnCount > 0 and columnCount != tileset.columnCount()):
# Correct tile index for changes in image width
row = int(tileId / columnCount)
column = int(tileId % columnCount)
tileId = row * tileset.columnCount() + column
result.tile = tileset.tileAt(tileId)
ok = True
return result, ok
##
# Returns the global tile ID for the given \a cell. Returns 0 when the
# cell is empty or when its tileset isn't known.
##
def cellToGid(self, cell):
if (cell.isEmpty()):
return 0
tileset = cell.tile.tileset()
# Find the first GID for the tileset
for item in self.mFirstGidToTileset:
if item[1] == tileset:
gid = item[0] + cell.tile.id()
if (cell.flippedHorizontally):
gid |= FlippedHorizontallyFlag
if (cell.flippedVertically):
gid |= FlippedVerticallyFlag
#.........这里部分代码省略.........
示例10: EditPolygonTool
# 需要导入模块: from pyqtcore import QMap [as 别名]
# 或者: from pyqtcore.QMap import insert [as 别名]
#.........这里部分代码省略.........
self.mScreenStart = event.screenPos()
items = self.mapScene().items(self.mStart,
Qt.IntersectsItemShape,
Qt.DescendingOrder,
viewTransform(event))
self.mClickedObjectItem = first(items, MapObjectItem)
self.mClickedHandle = first(items, PointHandle)
elif x==Qt.RightButton:
items = self.mapScene().items(event.scenePos(),
Qt.IntersectsItemShape,
Qt.DescendingOrder,
viewTransform(event))
clickedHandle = first(items)
if (clickedHandle or not self.mSelectedHandles.isEmpty()):
self.showHandleContextMenu(clickedHandle,
event.screenPos())
else:
super().mousePressed(event)
else:
super().mousePressed(event)
def mouseReleased(self, event):
if (event.button() != Qt.LeftButton):
return
x = self.mMode
if x==EditPolygonTool.NoMode:
if (self.mClickedHandle):
selection = self.mSelectedHandles
modifiers = event.modifiers()
if (modifiers & (Qt.ShiftModifier | Qt.ControlModifier)):
if (selection.contains(self.mClickedHandle)):
selection.remove(self.mClickedHandle)
else:
selection.insert(self.mClickedHandle)
else:
selection.clear()
selection.insert(self.mClickedHandle)
self.setSelectedHandles(selection)
elif (self.mClickedObjectItem):
selection = self.mapScene().selectedObjectItems()
modifiers = event.modifiers()
if (modifiers & (Qt.ShiftModifier | Qt.ControlModifier)):
if (selection.contains(self.mClickedObjectItem)):
selection.remove(self.mClickedObjectItem)
else:
selection.insert(self.mClickedObjectItem)
else:
selection.clear()
selection.insert(self.mClickedObjectItem)
self.mapScene().setSelectedObjectItems(selection)
self.updateHandles()
elif (not self.mSelectedHandles.isEmpty()):
# First clear the handle selection
self.setSelectedHandles(QSet())
else:
# If there is no handle selection, clear the object selection
self.mapScene().setSelectedObjectItems(QSet())
self.updateHandles()
elif x==EditPolygonTool.Selecting:
self.updateSelection(event)
self.mapScene().removeItem(self.mSelectionRectangle)
self.mMode = EditPolygonTool.NoMode
elif x==EditPolygonTool.Moving:
self.finishMoving(event.scenePos())