def __init__(self, signals: ClientSignal, Parent=None): ''' Constructor ''' super().__init__(Parent) self.Signals = signals # 是否是本玩家在画图 # 判断是否需要发送画图信息 self.Painting = False self.BoardSize = QSize(*board_resolution) # 新建QPixmap作为画板,尺寸为size self.Board = QPixmap(self.BoardSize) self.Board.fill(Qt.white) # 用白色填充画板 self.IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.LastPos = QPoint(0, 0) # 上一次鼠标位置 self.CurrentPos = QPoint(0, 0) # 当前的鼠标位置 self.Painter = QPainter() # 新建绘图工具 self.Thickness = default_thickness # 默认画笔粗细为10px self.PenColor = QColor(default_color) # 设置默认画笔颜色为黑色 self.ColorList = QColor.colorNames() # 获取颜色列表 self.set_paint.connect(self.set_painting) self.PaintPoints = [] self.init_view()
def __init_data(self): """ initial the canvas, painter :return: """ self.__size = QSize(420, 420) # create a new canvas by QPixmap, size for self.__size self.__canvas = QPixmap(self.__size) # set the background of the board as white, for better visual effect self.__canvas.fill(Qt.white) # default for none self.__IsEmpty = True # default for no eraser self.EraserMode = False # initial the last mouse position self.__lastPos = QPoint(0, 0) # initial the current mouse position self.__currentPos = QPoint(0, 0) # new a painter for drawing self.__painter = QPainter() # default pen size for 10px self.__thickness = 30 # default pen color for black self.__penColor = QColor("black") # get the color list from library self.colorList = QColor.colorNames()
def mouseReleaseEvent(self, event): ''' @param: event QMouseEvent ''' super().mouseReleaseEvent(event) self._dragStartPosition = QPoint() if gVar.app.plugins().processMouseRelease(const.ON_TabBar, self, event): return if not self.rect().contains(event.pos()): return if event.button() == Qt.MiddleButton: if self.emptyArea(event.pos()): self._tabWidget.addViewByUrl(QUrl(), const.NT_SelectedTabAtTheEnd, True) return id_ = self.tabAt(event.pos()) if id_ != -1: self._tabWidget.requestCloseTab(id_) return
def mouseReleaseEvent(self, mouse_event): if self.span_mouse.is_started(): self.span_mouse.end_drag() elif self.select_mouse.is_started(): self.select_mouse.end_drag() elif self.move_mouse.is_started(): self.move_mouse.end_drag() else: keyboard_modifiers = QApplication.keyboardModifiers() if self.pattern is None or keyboard_modifiers == QtCore.Qt.ControlModifier or keyboard_modifiers == QtCore.Qt.AltModifier: return if self.pattern is not None and self.pattern.is_any_selected(): self.pattern.unselect_all() self._draw_widget.update() return position = QPoint(mouse_event.x(), mouse_event.y()) position = self.mapToGlobal(position) position = self.ui.patternFrame.mapFromGlobal(position) frame_geometry = self.ui.patternFrame.geometry() if position.x() >= 0 and position.x() < frame_geometry.width() and position.y() >= 0 and position.y() < frame_geometry.height(): position = self._transformations.point_from_screen(position) existing_starfish = self.pattern.get_starfish_at_position(position) if existing_starfish is not None: self.pattern.remove_starfish(existing_starfish) else: starfish_type = StarfishType(random.randint(0,1)) self.pattern.add_starfish_at_position(position, starfish_type) self._draw_widget.update()
def test_background_color(self): self.test.wrd_d_click(self.text, "WdItOr") diff(self.text.toHtml()) color = self.editor.view.toolbar.controls["background-color"] with patch.object(color, '_get_color', return_value=QColor("blue")): self.test.mouse_click(color, QPoint(1, 1)) self.test.sleep() self.test.mouse_click(color._colors_widget.clrbtn[-1], QPoint(3, 3)) self.test.sleep() changed = diff(self.text.toHtml()) self.assertTrue("color:" + QColor("blue").name() in changed["add"]) diff(self.text.toHtml()) self.test.wrd_d_click(self.text, "YOU") with patch.object(color, '_get_color', return_value=QColor("yellow")): self.test.mouse_click(color, QPoint(1, 1)) self.test.sleep() color._colors_widget.other_color_() changed = diff(self.text.toHtml()) self.assertTrue("background-color:" + QColor("yellow").name() in changed["add"]) self.test.wrd_click(self.text, "rld", delay=1)
def cursor_track(self,x,SorE): cbSize=self.cursorboxsize current_plot=self.curr_plot_indx array_x=self.main.x_scale[current_plot] x_=self.main.px2pt.transform((x,0))[0] indx = np.searchsorted(array_x, x_) if indx==len(array_x): indx=indx-1 dat_x=array_x[indx] dat_y=self.main.y_scale[current_plot][indx] pos_=self.main.pt2px.transform((dat_x,dat_y)) if SorE == "both": dt_pos=self.tS_pos[0]-self.tE_pos[0] self.draw_cursor_tS(pos_[0],True) self.draw_cursor_vS(pos_[1],True) self.CursorTrackBox_S.setGeometry(QRect(QPoint(pos_[0]-cbSize/2,self.CH-pos_[1]-cbSize/2),QSize(cbSize,cbSize))) dt_x=self.main.px2pt.transform((x-dt_pos,0))[0] indx_dt = np.searchsorted(array_x, dt_x) dat_xdt=array_x[indx_dt] dat_ydt=self.main.y_scale[current_plot][indx_dt] pos_=self.main.pt2px.transform((dat_xdt,dat_ydt)) self.draw_cursor_tE(pos_[0],True) self.draw_cursor_vE(pos_[1],True) self.CursorTrackBox_E.setGeometry(QRect(QPoint(pos_[0]-cbSize/2,self.CH-pos_[1]-cbSize/2),QSize(cbSize,cbSize))) elif SorE =="S": self.draw_cursor_tS(pos_[0],True) self.draw_cursor_vS(pos_[1],True) self.CursorTrackBox_S.setGeometry(QRect(QPoint(pos_[0]-cbSize/2,self.CH-pos_[1]-cbSize/2),QSize(cbSize,cbSize))) elif SorE =="E": self.draw_cursor_tE(pos_[0],True) self.draw_cursor_vE(pos_[1],True) self.CursorTrackBox_E.setGeometry(QRect(QPoint(pos_[0]-cbSize/2,self.CH-pos_[1]-cbSize/2),QSize(cbSize,cbSize)))
def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self.setupUi(self) self.setMouseTracking(True) self.imglist = [] self.ImgFolder = '' self.CurImg = '' #新建QPixmap作为画板,尺寸为__size self.__board = QPixmap() self.__board.fill(Qt.white) #用白色填充画板 self.__IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 self.__painter = QPainter() # 新建绘图工具 self.__thickness = 10 # 默认画笔粗细为10px self.__penColor = QColor("black") # 设置默认画笔颜色为黑色 self.__colorList = QColor.colorNames() # 获取颜色列表 # 按键信号与回调函数连接 self.OpenDir.clicked.connect(self.OpenDirBntClicked) self.NextImg.clicked.connect(self.NextImBntClicked) self.LastImg.clicked.connect(self.PreImBntClicked) self.SaveImg.clicked.connect(self.on_btn_Save_Clicked) self.PenThicknessSpinBox.valueChanged.connect(self.on_PenThicknessChange)
def relative_move(self, dx: int, dy: int, widget: GraphItem): """ Do a relative move of a widget on the grid. """ # When the user switches grid while dragging, start is not # called. Because of that variables must be initialized manually if (not self.__start_called): self.__deviation_x = 0 self.__deviation_y = 0 self.__start_called = True # Calculate the new absolute postion of the widget old_pos = widget.get_center() new_pos = QPoint(old_pos.x() + dx + self.__deviation_x, old_pos.y() + dy + self.__deviation_y) # Calculate absolut position on grid grid_pos = self.get_grid_position(new_pos) # Calculate relative movement to grid position grid_dx = grid_pos.x() - old_pos.x() grid_dy = grid_pos.y() - old_pos.y() # Calculate deviation of relative move caused by grid self.__deviation_x += dx - grid_dx self.__deviation_y += dy - grid_dy return QPoint(grid_dx, grid_dy)
def paintEvent(self, event: QPaintEvent): # Init painter pen = QPen() pen.setWidth(self.__pen_width) pen.setColor(self.__line_color) painter = QPainter() painter.begin(self) painter.setPen(pen) # Horizontal lines start_h = QPoint(0, self.__offset.y()) end_h = QPoint(self.width(), self.__offset.y()) distance_h = QPoint(0, self.__grid_size) # Vertical lines start_v = QPoint(self.__offset.x(), 0) end_v = QPoint(self.__offset.x(), self.height()) distance_v = QPoint(self.__grid_size, 0) while start_h.y() < self.height(): painter.drawLine(start_h, end_h) start_h += distance_h end_h += distance_h while start_v.x() < self.width(): painter.drawLine(start_v, end_v) start_v += distance_v end_v += distance_v painter.end()
def __add_branch(self, branch): widget = BranchWidget(branch, QPoint( branch.spline1_x, branch.spline1_y), QPoint( branch.spline2_x, branch.spline2_y), parent=self) self.__model_widget_map[branch] = widget self.__widget_model_map[widget] = branch widget.show() # Lower branch to ensure it is behind its nodes widget.lower() # Lower grid widget to keep it behind the branches self.__grid_widget.lower() # Register click listener for widget widget.observe(self.__on_branch_click) # Paint widget explicit # because the label positioning needs an existing # Bézier curve widget.repaint() self.__initalize_label(branch)
def isPointInRect(point: QPoint, rect: Tuple[QPoint, QSize]) -> bool: """Checking the position of a point relative to a rectangle.""" return ( rect[0].x() <= point.x() <= rect[0].x() + rect[1].width() and rect[0].y() <= point.y() <= rect[0].y() + rect[1].height() )
def __init__(self, parent=None): super().__init__(parent) self.__parent = parent self.__board = QPixmap(QSize(440, 440)) self.__board.fill(Qt.transparent) self.__board_old = self.__board.copy() self.__board_old_old = self.__board.copy() self.__board_before_dots = self.__board.copy() self.__thickness = 10 # 默认画笔粗细为10px self.__penColor = QColor(0, 0, 0, 128) self.__painter = QPainter() self.__pen = QPen(self.__penColor, self.__thickness) self.__pen_seg = QPen(QColor(0, 0, 0, 128)) self.__brush = QBrush(QColor(0, 0, 0, 128)) self.__pen.setCapStyle(Qt.RoundCap) #self.__painter.setPen(self.__pen) self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 self.__points = [] # dots模式的点集 self.__mouse_pressed = False self.__can_undo = False self.__has_seg = False self.__mode = 1 self.__ERASE = 0 self.__LINE = 1 self.__RECT = 2 self.__CIRCLE = 3 self.__DOTS = 4 self.__transparent = False self.__trans_board = self.__board.copy() self.__trans_board.fill(Qt.transparent)
def verticalGradientHelper(self, painter, spanRect, rect, lightColored=False): ''' @brief: Gradients used for panels @param: painter QPainter @param: spanRect QRect @param: rect QRect @param: lightColored bool ''' highlight = self.highlightColor(lightColored) shadow = self.shadowColor(lightColored) grad = QLinearGradient(spanRect.topRight(), spanRect.topLeft()) grad.setColorAt(0, highlight.lighter(117)) grad.setColorAt(1, shadow.darker(109)) painter.fillRect(rect, grad) light = QColor(255, 255, 255, 80) painter.setPen(light) painter.drawLine(rect.topRight() - QPoint(1, 0), rect.bottomRight() - QPoint(1, 0)) dark = QColor(0, 0, 0, 90) painter.setPen(dark) painter.drawLine(rect.topLeft(), rect.bottomLeft())
def __init__(self, owner: CurvedBranch, spline1: QPoint, spline2: QPoint, *args, ** kwargs): super().__init__(*args, **kwargs) self.__owner = owner self.__start = QPoint(owner.start.x, owner.start.y) self.__end = QPoint(owner.end.x, owner.end.y) self.__spline1 = spline1 self.__spline2 = spline2 self.__branch = QPainterPath() self.__pen_width = 3 # The arrow has the form of a triangle # Half of the width of the arrow (at the back) self.__arrow_height = 9 # Length of the arrow from top to back self.__arrow_length = 27 # The triangle is drawn with 3 bezier curves # These numbers determine the bend of the curves self.__arrow_side_spline_depth = 2 self.__arrow_back_spline_depth = 5.5 # Antialiasing offsets for arrow mask self.__arrow_mask_length_offset = 8 self.__arrow_mask_height_offset = 5 self.__arrow_mask = None self.__arrow = None self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.updateGeometry()
def penMoveEvent(self, pos, pressure): pen_x = pos[0] pen_y = pos[1] pen_pressure = pressure if self.__lastPos is None: self.__lastPos = QPoint(pen_x, pen_y) elif (abs(pen_x - self.__lastPos.x()) > 21 or abs(pen_y - self.__lastPos.y()) > 21): self.__lastPos = QPoint(pen_x, pen_y) self.__currentPos = QPoint(pen_x, pen_y) self.__painter.begin(self.__board) if self.EraserMode == False: #Non-Eraser mode self.__painter.setPen(QPen( self.__penColor, self.__thickness)) #Set pen color, thickness else: #Eraser mode: pen color is white, thickness is 6 self.__painter.setPen(QPen(Qt.white, 6)) self.__painter.drawLine(self.__lastPos, self.__currentPos) self.__painter.end() self.__lastPos = self.__currentPos self.update() #Show updates
def mouseMoveEvent(self, event): try: delta = QPoint(event.globalPos() - self.oldPos) self.move(self.x() + delta.x(), self.y() + delta.y()) self.oldPos = event.globalPos() except: pass
def test_set_bold(self): self.test.wrd_d_click(self.text, "rld") self.test.key_clicks(self.text, "World.upper()=WORLD", delay=1) bold = self.editor.view.toolbar.controls["bold"] self.test.wrd_d_click(self.text, "WdItOr") diff(self.text.toHtml()) self.test.mouse_click(bold, QPoint(1, 1), delay=1) changed = diff(self.text.toHtml()) self.assertTrue("font-weight:600" in changed["add"]) self.assertTrue(bold.isChecked()) self.test.wrd_click(self.text, "llo") self.assertFalse(bold.isChecked()) self.test.wrd_click(self.text, "dItOr") self.assertTrue(bold.isChecked()) diff(self.text.toHtml()) self.test.wrd_d_click(self.text, "WdItOr") self.test.mouse_click(bold, QPoint(1, 1), delay=1) changed = diff(self.text.toHtml()) self.assertFalse(bold.isChecked()) self.assertTrue("font-weight:600" in changed["del"])
def test_show_form(self): self.lbl.setText("CURRENT TEST: show_form") self.select_align.clear() self.cw.show_form(QPoint(100, 100)) self.test.sleep() self.test.mouse_click(self.cw._clrbtn[2], QPoint(1, 1)) self.test.sleep() self.assertEqual(self.select_align[-1][0], Qt.AlignRight)
def test_insert_table(self): diff(self.text.toHtml()) table = self.editor.view.toolbar.controls["table"] self.test.mouse_click(table, QPoint(1, 1)) self.test.mouse_click(table._colors_widget._clrbtn[35], QPoint(1, 1)) changed = diff(self.text.toHtml()) self.test.sleep() self.assertTrue('table' in changed["add"])
def popupAtPosition(self, parent, rect): self.show() if isinstance(rect, QRect): new_pos = parent.mapToGlobal(rect.bottomRight() - QPoint(self.width(), 0)) new_pos = QPoint(max(0, new_pos.x()), new_pos.y()) elif isinstance(rect, QPoint): new_pos = parent.mapToGlobal(rect) self.move(new_pos)
def test_horizontal_line(self): diff(self.text.toHtml()) self.test.mouse_click(self.text.viewport(), QPoint(200, 51)) hline = self.editor.view.toolbar.controls["hline"] self.test.mouse_click(hline, QPoint(1, 1)) changed = diff(self.text.toHtml()) self.assertTrue('background-color:#c1c1c1' in changed["add"]) self.test.sleep()
def paintLine(self, P1_x, P1_y, P2_x, P2_y): P1 = QPoint(P1_x, P1_y) P2 = QPoint(P2_x, P2_y) self.__painter.begin(self.__board) self.__painter.drawLine(P1, P2) self.__painter.end() self.update() #Show updates
def graph_moved_event(self, event: GraphMovedEvent): """ Triggered after the whole graph has been moved. Does not change the geometry but mvoes the widget. """ self.__start = QPoint(self.__owner.start.x, self.__owner.start.y) self.__end = QPoint(self.__owner.end.x, self.__owner.end.y) self.__spline1 = QPoint(self.__owner.spline1_x, self.__owner.spline1_y) self.__spline2 = QPoint(self.__owner.spline2_x, self.__owner.spline2_y) super().graph_moved_event(event)
def __init__(self, size, *args, **kwargs): super().__init__(*args, **kwargs) self.__grid_size = size self.__pen_width = 1 self.__line_color = QColor(192, 192, 192, 255) self.__offset = QPoint(0, 0) # Disable the widgets to ignore all events # Widget should not become mousegrabber self.setDisabled(True)
def test_write_settings(self): x, y = self.m.pos().x(), self.m.pos().y() self.m.move(QPoint(0, 0)) self.m.write_settings() self.assertEqual(self.m.pos().x(), 0) self.m.read_settings() self.assertEqual(self.m.pos().x(), 0) self.m.move(QPoint(x, y)) self.m.write_settings() self.assertEqual(self.m.pos().x(), x)
def __InitData(self): self.__size = QSize(280, 280) self.__board = QPixmap(self.__size) self.__board.fill(Qt.black) self.__isEmpty = True self.__lastPose = QPoint(0, 0) self.__currentPose = QPoint(0, 0) self.__painter = QPainter() self.__thickness = 20 self.__penColor = QColor('white')
def node_moved_event(self, event: PositionedNodeMovedEvent): """ Triggered after the node has been moved. Updates the geometry of the widget if necessary. """ if self.__owner.start is event.node: self.__start = QPoint(event.node.x, event.node.y) self.updateGeometry() if self.__owner.end is event.node: self.__end = QPoint(event.node.x, event.node.y) self.updateGeometry()
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setPen(QPen(Qt.red, 3)) painter.setBrush(Qt.transparent) painter.translate(self.width() / 2, self.height() / 2) painter.drawEllipse(QPoint(0, 0), self.outer_circle, self.outer_circle) painter.drawEllipse(QPoint(self.ball.x, self.ball.y), self.ball.r, self.ball.r)
def __InitData(self): self.__size = QSize(420, 420) # 新建QPixmap作为画板,尺寸为__size self.__board = QPixmap(self.__size) self.__board.fill(Qt.black) # 用黑色填充画板 self.__IsEmpty = True # 默认为空画板 self.EraserMode = False # 默认为禁用橡皮擦模式 self.__lastPos = QPoint(0, 0) # 上一次鼠标位置 self.__currentPos = QPoint(0, 0) # 当前的鼠标位置 self.__painter = QPainter() # 新建绘图工具 self.__thickness = 35 # 默认画笔粗细为35px self.__penColor = QColor("white") # 设置默认画笔颜色为白色 self.__colorList = QColor.colorNames() # 获取颜色列表
def show_error(self): # 窗体抖动效果 animation = QPropertyAnimation(self) animation.setTargetObject(self) animation.setPropertyName(b'pos') animation.setKeyValueAt(0, self.pos()) animation.setKeyValueAt(0.2, self.pos() + QPoint(15, 0)) animation.setKeyValueAt(0.5, self.pos()) animation.setKeyValueAt(0.7, self.pos() + QPoint(-15, 0)) animation.setKeyValueAt(1, self.pos()) animation.setDuration(100) animation.setLoopCount(3) animation.start(QAbstractAnimation.DeleteWhenStopped)
def paintEvent(self, ev): offset = QPoint(0, 0) p = QPainter(self) p.setClipRect(ev.rect()) bottom = self.rect().bottom() if self.results: for i, (prefix, full, text) in enumerate(self.results): size = prefix.size() if offset.y() + size.height() > bottom: break self.max_result = i offset.setX(0) if i in (self.current_result, self.mouse_hover_result): p.save() if i != self.current_result: p.setPen(Qt.DotLine) p.drawLine(offset, QPoint(self.width(), offset.y())) p.restore() offset.setY(offset.y() + self.MARGIN // 2) p.drawStaticText(offset, prefix) offset.setX(self.maxwidth + 5) p.drawStaticText(offset, self.divider) offset.setX(offset.x() + self.divider.size().width()) p.drawStaticText(offset, full) offset.setY(offset.y() + size.height() + self.MARGIN // 2) if i in (self.current_result, self.mouse_hover_result): offset.setX(0) p.save() if i != self.current_result: p.setPen(Qt.DotLine) p.drawLine(offset, QPoint(self.width(), offset.y())) p.restore() else: p.drawText(self.rect(), Qt.AlignCenter, _('No results found')) p.end()
def run(self): time.sleep(0.5) # create hash dict of current list self._hash_item_dict = {} for item in self._item_list: self._hash_item_dict[item.hash] = item # compare and swap between lists if new item is not generated for new_hash in self._hash_item_dict.keys(): if new_hash in self._old_hash_item_dict.keys(): # swap to avoid generating uselessly : self._hash_item_dict[ new_hash] = self._old_hash_item_dict[new_hash] else: # generate _ = self._hash_item_dict[new_hash].image # append generated images # images_list.append() pix_list = [] for new_item in self._item_list: usable_item = self._hash_item_dict[new_item.hash] pix_list.append(usable_item.image) # draw pixmaps in one : image = QImage(20, 20, QImage.Format_ARGB32_Premultiplied) image.fill(Qt.white) point = QPoint(0, 0) width_list = [pix.width() for pix in pix_list] max_width = max(width_list) self._max_width_found = max([max_width, self._max_width_found]) for pix in pix_list: last_image = image image = QImage(self._max_width_found, image.height( ) + pix.height(), QImage.Format_ARGB32_Premultiplied) pix_paint = QPainter(image) image.fill(Qt.white) pix_paint.drawImage(0, 0, last_image) pix_paint.drawImage(point, pix) point = QPoint(0, point.y() + pix.height()) pix_paint.end() ''' pixmap = QImage(21,21, QImage.Format_ARGB32_Premultiplied) # temp pixPaint = QPainter(pixmap) myPen = QPen( Qt.black) pixPaint.setPen(myPen) pixPaint.drawRect(0,0, 20,20); pixPaint.end() image = pixmap painter.drawImage(point, pix) point = QPoint(0, point.y() + pix.height()) painter.end() ''' final_pixmap = QPixmap.fromImage(image, Qt.AutoColor) self.image_generated.emit(final_pixmap) self._old_item_list = self._item_list self._old_hash_item_dict = self._hash_item_dict