Python PyQt5.QtWidgets.QGraphicsRectItem() Examples

The following are 11 code examples of PyQt5.QtWidgets.QGraphicsRectItem(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PyQt5.QtWidgets , or try the search function .
Example #1
Source File: geographical_view.py    From pyNMS with GNU General Public License v3.0 6 votes vote down vote up
def draw_water(self):
        if self.proj in ('Spherical', 'ETRS89 - LAEA Europe'):
            cx, cy = self.to_canvas_coordinates(17, 48)
            # if the projection is ETRS89, we need the diameter and not the radius
            R = 6371000*self.ratio*(1 if self.proj == 'Spherical' else 2)
            earth_water = QtWidgets.QGraphicsEllipseItem(cx - R, cy - R, 2*R, 2*R)
            earth_water.setZValue(0)
            earth_water.setBrush(self.water_brush)
            self.polygons.addToGroup(earth_water)
        else:
            # we compute the projected bounds of the Mercator (3395) projection
            # upper-left corner x and y coordinates:
            ulc_x, ulc_y = self.to_canvas_coordinates(-180, 84)
            # lower-right corner x and y coordinates
            lrc_x, lrc_y = self.to_canvas_coordinates(180, -84.72)
            # width and height of the map (required for the QRectItem)
            width, height = lrc_x - ulc_x, lrc_y - ulc_y
            earth_water = QtWidgets.QGraphicsRectItem(ulc_x, ulc_y, width, height)
            earth_water.setZValue(0)
            earth_water.setBrush(self.water_brush)
            self.polygons.addToGroup(earth_water) 
Example #2
Source File: ZoomableScene.py    From urh with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)
        self.noise_area = None

        self.separation_areas = []  # type: list[QGraphicsRectItem]
        self.captions = []  # type: list[QGraphicsSimpleTextItem]

        self.centers = [0]

        self.always_show_symbols_legend = False

        self.ones_caption = None
        self.zeros_caption = None

        self.ones_arrow = None
        self.zeros_arrow = None
        self.selection_area = HorizontalSelection(0, 0, 0, 0, fillcolor=settings.SELECTION_COLOR,
                                                  opacity=settings.SELECTION_OPACITY)
        self.addItem(self.selection_area) 
Example #3
Source File: view_graph_original.py    From QualCoder with MIT License 6 votes vote down vote up
def __init__(self, app, data):
        super(TextGraphicsItem, self).__init__(None)

        self.app = app
        self.conn = app.conn
        self.settings = app.settings
        self.project_path = app.project_path
        self.data = data
        self.setFlags (QtWidgets.QGraphicsItem.ItemIsMovable | QtWidgets.QGraphicsItem.ItemIsFocusable | QtWidgets.QGraphicsItem.ItemIsSelectable)
        self.setTextInteractionFlags(QtCore.Qt.TextEditable)
        if self.data['cid'] is not None:
            self.font = QtGui.QFont(self.settings['font'], self.data['fontsize'], QtGui.QFont.Normal)
            self.setFont(self.font)
            self.setPlainText(self.data['name'])
        if self.data['cid'] is None:
            self.font = QtGui.QFont(self.settings['font'], self.data['fontsize'], QtGui.QFont.Bold)
            self.setFont(self.font)
            self.setPlainText(self.data['name'])
        self.setPos(self.data['x'], self.data['y'])
        self.document().contentsChanged.connect(self.text_changed)
        #self.border_rect = QtWidgets.QGraphicsRectItem(0, 0, rect.width(), rect.height())
        #self.border_rect.setParentItem(self) 
Example #4
Source File: multiplot.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        QtWidgets.QGraphicsRectItem.__init__(self, self.cursor)
        self.setPen(self.pen)
        self.setZValue(1e9)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIgnoresTransformations) 
Example #5
Source File: landUnit.py    From imperialism-remake with GNU General Public License v3.0 5 votes vote down vote up
def draw(self, defending, status, scene, size):
        """function draw

        :param defending: bool
        :param status: str {'Charge', 'Shoot', 'Stand'}
        :param scene: QGraphicsScene
        :param size: QSize

        no return
        """
        if not isinstance(defending, bool):
            raise ValueError('defending must be a boolean')
        if not isinstance(status, str) or (status != 'Charge' and status != 'Shoot' and status != 'Stand'):
            raise ValueError('status must be a str in {\'Charge\', \'Shoot\', \'Stand\'}')

        self.unitType.draw(defending, status, scene, size)
        flag_width = self.nation.flag.width() * 10 / self.nation.flag.height()
        item = scene.addPixmap(self.nation.flag.scaled(flag_width, 10))
        item.setPos(size.width() - 5 - flag_width, 0)
        # life bar
        item1 = QGraphicsRectItem(0, size.height() - 10, size.width() - 5, 5)
        item1.setBrush(QBrush(Qt.white))
        item2 = QGraphicsRectItem(0, size.height() - 10, self.unitStrength / 100 * (size.width() - 5), 5)
        item2.setBrush(QBrush(Qt.green))
        # moral bar
        item3 = QGraphicsRectItem(0, size.height() - 15, size.width() - 5, 5)
        item3.setBrush(QBrush(Qt.white))
        item4 = QGraphicsRectItem(0, size.height() - 15, self.moral / 100 * (size.width() - 5), 5)
        item4.setBrush(QBrush(Qt.blue))
        scene.addItem(item1)
        scene.addItem(item2)
        scene.addItem(item3)
        scene.addItem(item4) 
Example #6
Source File: ZoomableScene.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def draw_sep_area(self, centers: np.ndarray, show_symbols=False):
        x = self.sceneRect().x()
        y = self.sceneRect().y()
        h = self.sceneRect().height()
        w = self.sceneRect().width()

        num_areas = len(centers) + 1
        if num_areas != len(self.separation_areas):
            for area in self.separation_areas:
                self.removeItem(area)
            self.separation_areas.clear()

            for i in range(num_areas):
                area = QGraphicsRectItem(0, 0, 0, 0)
                if i % 2 == 0:
                    area.setBrush(settings.ZEROS_AREA_COLOR)
                else:
                    area.setBrush(settings.ONES_AREA_COLOR)
                area.setOpacity(settings.SEPARATION_OPACITY)
                area.setPen(QPen(settings.TRANSPARENT_COLOR, 0))
                self.addItem(area)
                self.separation_areas.append(area)

        start = y + h

        for i, area in enumerate(self.separation_areas):
            area.show()
            try:
                self.separation_areas[i].setRect(x, start, w, -(start - centers[i]))
                start -= (start - centers[i])
            except IndexError:
                self.separation_areas[i].setRect(x, start, w, -(start - y))

        if self.noise_area is not None:
            self.noise_area.hide()

        self.centers = centers
        self.redraw_legend(show_symbols) 
Example #7
Source File: codescene.py    From CodeAtlasSublime with Eclipse Public License 1.0 5 votes vote down vote up
def __init__(self, *args):
		super(CodeScene, self).__init__(*args)
		self.itemDict = {}
		self.edgeDict = {}
		self.stopItem = {}		# 不显示的符号
		self.scheme = {}		# 保存的call graph,
								# {'schemeName': {'node':[node1, node2,...], 'edge':{(node3, node5):{'customEdge':True}, ...}}, ...}
		self.curValidScheme = []# 选中物体有关的scheme
		self.curValidSchemeColor = []
		self.candidateEdge = [] # candidate edge up/down/left/right will select
		self.isSourceCandidate = True
		self.edgeDataDict = {}  # 存放需要保存的边用户数据
		self.itemDataDict = {}	# 存放需要保存的点用户数据

		self.itemLruQueue = []
		self.lruMaxLength = 100
		self.isLayoutDirty = False

		self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)
		self.lock = RecursiveLock()
		self.updateThread = SceneUpdateThread(self, self.lock)
		self.updateThread.start()

		self.cornerItem = []
		self.autoFocus = True
		self.autoFocusToggle = True
		self.selectTimeStamp = 0
		for i in range(4):
			item = QtWidgets.QGraphicsRectItem(0,0,5,5)
			item.setPen(QtGui.QPen(QtGui.QColor(0,0,0,0)))
			item.setBrush(QtGui.QBrush())
			self.cornerItem.append(item)
			self.addItem(item)
		# self.connect(self, QtCore.SIGNAL('selectionChanged()'), self, QtCore.SLOT('onSelectItems()'))
		self.selectionChanged.connect(self.onSelectItems)

	# 添加或修改call graph 
Example #8
Source File: view_image.py    From QualCoder with MIT License 5 votes vote down vote up
def draw_coded_areas(self):
        """ Draw coded areas with scaling. This coder is shown in dashed rectangles.
        Other coders are shown via dotline rectangles.
        Remove items first, as this is called after a coded area is unmarked. """

        if self.file_ is None:
            return
        for item in self.code_areas:
            if item['id'] == self.file_['id']:
                color = QtGui.QColor('#AA0000')  # Default color
                color = None
                tooltip = ""
                for c in self.codes:
                    if c['cid'] == item['cid']:
                        tooltip = c['name'] + " (" + item['owner'] + ")"
                        tooltip += "\nMemo: " + item['memo']
                        color = QtGui.QColor(c['color'])
                x = item['x1'] * self.scale
                y = item['y1'] * self.scale
                width = item['width'] * self.scale
                height = item['height'] * self.scale
                rect_item = QtWidgets.QGraphicsRectItem(x, y, width, height)
                rect_item.setPen(QtGui.QPen(color, 2, QtCore.Qt.DashLine))
                rect_item.setToolTip(tooltip)
                if item['owner'] == self.app.settings['codername']:
                    self.scene.addItem(rect_item)
                if self.ui.checkBox_show_coders.isChecked() and item['owner'] != self.app.settings['codername']:
                    rect_item.setPen(QtGui.QPen(color, 2, QtCore.Qt.DotLine))
                    self.scene.addItem(rect_item) 
Example #9
Source File: game.py    From imperialism-remake with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Sets up the graphics view.
        """
        super().__init__(*args, **kwargs)
        self.setObjectName('mini-map-widget')

        layout = QtWidgets.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        # the content is a scene
        self.scene = QtWidgets.QGraphicsScene()

        # tracker rectangle that tracks the view of the map, initially hidden
        self.tracker = QtWidgets.QGraphicsRectItem()
        self.tracker.setCursor(QtCore.Qt.PointingHandCursor)
        self.tracker.setZValue(1000)
        self.tracker.hide()
        self.scene.addItem(self.tracker)

        # the view on the scene (no scroll bars)
        self.view = QtWidgets.QGraphicsView(self.scene)
        self.view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        layout.addWidget(self.view)

        # the width and height (fixed width throughout the game)
        # TODO make this adjustable
        self.view.setFixedWidth(self.VIEW_WIDTH)
        view_height = math.floor(0.6 * self.VIEW_WIDTH)
        self.view.setFixedHeight(view_height)

        # tool bar below the mini map
        self.toolbar = QtWidgets.QToolBar()
        self.toolbar.setIconSize(QtCore.QSize(20, 20))

        # action group (only one of them can be checked at each time)
        action_group = QtWidgets.QActionGroup(self.toolbar)
        # political view in the beginning
        a = qt.create_action(tools.load_ui_icon('icon.mini.political.png'), 'Show political view', action_group,
                             toggle_connection=self.switch_to_political_view, checkable=True)
        self.toolbar.addAction(a)
        # geographical view
        a = qt.create_action(tools.load_ui_icon('icon.mini.geographical.png'), 'Show geographical view', action_group,
                             toggle_connection=self.switch_to_geographical_view, checkable=True)
        self.toolbar.addAction(a)
        self.mode = constants.OverviewMapMode.POLITICAL

        # wrap tool bar into horizontal layout with stretch
        l = QtWidgets.QHBoxLayout()
        l.setContentsMargins(0, 0, 0, 0)
        l.addWidget(self.toolbar)
        l.addStretch()

        # add layout containing tool bar
        layout.addLayout(l)

        # graphics items in scene (except the tracker)
        self.scene_items = [] 
Example #10
Source File: editor.py    From imperialism-remake with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Sets up the graphics view, the toolbar and the tracker rectangle.
        """
        super().__init__(*args, **kwargs)
        self.setObjectName('mini-map-widget')

        layout = QtWidgets.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        # the content is a scene
        self.scene = QtWidgets.QGraphicsScene()

        # tracker rectangle that tracks the view of the map, initially hidden
        self.tracker = QtWidgets.QGraphicsRectItem()
        self.tracker.setCursor(QtCore.Qt.PointingHandCursor)
        self.tracker.setZValue(1000)
        self.tracker.hide()
        self.scene.addItem(self.tracker)

        # the view on the scene (no scroll bars)
        self.view = QtWidgets.QGraphicsView(self.scene)
        self.view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        layout.addWidget(self.view)

        # the width and height (fixed width throughout the game)
        # TODO make this adjustable
        self.view.setFixedWidth(self.VIEW_WIDTH)
        view_height = math.floor(0.6 * self.VIEW_WIDTH)
        self.view.setFixedHeight(view_height)

        # tool bar below the mini map
        self.toolbar = QtWidgets.QToolBar()
        self.toolbar.setIconSize(QtCore.QSize(20, 20))

        # action group (only one of them can be checked at each time)
        action_group = QtWidgets.QActionGroup(self.toolbar)
        # political view in the beginning
        a = qt.create_action(tools.load_ui_icon('icon.mini.political.png'), 'Show political view', action_group,
                             toggle_connection=self.switch_to_political_view, checkable=True)
        self.toolbar.addAction(a)
        # geographical view
        a = qt.create_action(tools.load_ui_icon('icon.mini.geographical.png'), 'Show geographical view', action_group,
                             toggle_connection=self.switch_to_geographical_view, checkable=True)
        self.toolbar.addAction(a)
        self.mode = constants.OverviewMapMode.POLITICAL

        # wrap tool bar into horizontal layout with stretch
        l = QtWidgets.QHBoxLayout()
        l.setContentsMargins(0, 0, 0, 0)
        l.addWidget(self.toolbar)
        l.addStretch()

        # add layout containing tool bar
        layout.addLayout(l)

        # graphics items in scene (except the tracker)
        self.scene_items = [] 
Example #11
Source File: view_image.py    From QualCoder with MIT License 4 votes vote down vote up
def code_area(self, p1):
        """ Created coded area coordinates from mouse release.
        The point and width and height mush be based on the original image size,
        so add in scale factor. """

        code_ = self.ui.treeWidget.currentItem()
        if code_ is None:
            return
        if code_.text(1)[0:3] == 'cat':
            return
        cid = code_.text(1)[4:]
        x = self.selection.x()
        y = self.selection.y()
        #print("x", x, "y", y, "scale", self.scale)
        width = p1.x() - x
        height = p1.y() - y
        if width < 0:
            x = x + width
            width = abs(width)
        if height < 0:
            y = y + height
            height = abs(height)
        #print("SCALED x", x, "y", y, "w", width, "h", height)
        # outside image area, do not code
        for item in self.scene.items():
            if type(item) == QtWidgets.QGraphicsPixmapItem:
                if x + width > item.boundingRect().width() or y + height > item.boundingRect().height():
                    self.selection = None
                    return

        x_unscaled = x / self.scale
        y_unscaled = y / self.scale
        width_unscaled = width / self.scale
        height_unscaled = height / self.scale
        #print("UNSCALED x", x, "y", y, "w", width, "h", height)
        item = {'imid': None, 'id': self.file_['id'], 'x1': x_unscaled, 'y1': y_unscaled,
        'width': width_unscaled, 'height':height_unscaled, 'owner': self.app.settings['codername'],
         'date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'cid': cid,'memo': ''}
        cur = self.app.conn.cursor()
        cur.execute("insert into code_image (id,x1,y1,width,height,cid,memo,date,owner) values(?,?,?,?,?,?,?,?,?)"
            , (item['id'], item['x1'], item['y1'], item['width'], item['height'], cid, item['memo'],
            item['date'],item['owner']))
        self.app.conn.commit()
        cur.execute("select last_insert_rowid()")
        imid = cur.fetchone()[0]
        item['imid'] = imid
        self.code_areas.append(item)
        rect_item = QtWidgets.QGraphicsRectItem(x, y, width, height)
        color = None
        for i in range(0, len(self.codes)):
            if self.codes[i]['cid'] == int(cid):
                color = QtGui.QColor(self.codes[i]['color'])
        if color is None:
            print("ERROR")
            return
        rect_item.setPen(QtGui.QPen(color, 2, QtCore.Qt.DashLine))
        rect_item.setToolTip(code_.text(0))
        self.scene.addItem(rect_item)
        self.selection = None