- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一条构成符号的路径,我想知道 QPainter 是否可以绘制该路径。在阅读文档时,我看到有一个与 QPainter
关联的 drawPath
函数,但每次我尝试实现它时,我总是收到一个错误,提示 QPainter::drawPath:画家未激活
。
因为我没有任何成功的尝试,所以我添加了代码的最小化工作版本。它将为您提供一些基本的缩放和平移功能以及选择符号以及按住 Shift 键取消选择符号的功能。
我希望路径在被选择或悬停时改变颜色,并且当前在被选择或悬停时被填充。最终,我希望用户能够从一开始就将路径更改为虚线或颜色。
感谢您的建议和帮助。
代码
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtSvg import *
import sys
from math import sqrt,cos,acos,asin,degrees,pi
class LogObject(QObject):
hovered = pyqtSignal()
notHovered = pyqtSignal()
def figAngle(radius,opposite):
dist = sqrt((radius) ** 2 + (opposite) ** 2)
angle = degrees(asin(opposite/dist))
if angle < 0:
angle = angle + 360
return angle
def create_path():
scale = 250
path = QPainterPath()
path.addEllipse(QPointF(0,0), 0.0268, 0.0268) # Using QPointF will center it
startAngle = figAngle(0.0357/scale,0.0045/scale) # Use the scale so that it will adjust as it is scaled
endAngle = figAngle(0.0357/scale,-0.0092/scale)
path.moveTo((0.0357+0.0821),0.0045 )
path.arcTo(QRectF(-0.0357,-0.0357,(0.0357*2),(0.0357*2)),-startAngle,-endAngle)
path.moveTo(0.0357, -0.0045)
path.lineTo(0.0357 + 0.0821, -0.0045)
path.lineTo(0.0357+0.0821,-0.0045-0.0680)
path.lineTo(0.0357+0.0821+0.1450,-0.0045-0.0680)
path.lineTo(0.0357+0.0821+0.1450,-0.0045-0.0680+0.1450)
path.lineTo(0.0357+0.0821,-0.0045-0.0680+0.1450)
path.lineTo(0.0357+0.0821,-0.0045-0.0680+0.1450-0.0680)
path.moveTo(0.0357+0.0821+0.0090,-0.0045-0.0680+0.1450-0.0090)
path.addRect(0.0357+0.0821+0.0090, -0.0045-0.0680+0.1450-0.0090-0.1270, 0.1270, 0.1270)
tr = QTransform()
tr.scale(scale, scale)
path = tr.map(path)
return path
class Point(QGraphicsPathItem):
def __init__(self, x, y, r, name):
super(Point, self).__init__()
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.setPath(create_path())
self.setScale(1)
self.setRotation(180+r)
self.setAcceptHoverEvents(True)
self.log = LogObject()
self.setPos(x, y)
self.isSelected = False
def itemChange(self, change, value):
if change == self.ItemSelectedChange:
self.setBrush(QBrush(Qt.green) if value else QBrush(Qt.black))
return QGraphicsItem.itemChange(self, change, value)
def hoverEnterEvent(self, event):
self.setBrush(QColor("red"))
self.log.hovered.emit()
QGraphicsItem.hoverMoveEvent(self, event)
def hoverLeaveEvent(self, event):
if self.isSelected == True:
self.setBrush(QBrush(Qt.green))
else:
self.setBrush(QColor("black"))
self.log.notHovered.emit()
QGraphicsItem.hoverMoveEvent(self, event)
class Viewer(QGraphicsView):
photoClicked = pyqtSignal(QPoint)
rectChanged = pyqtSignal(QRect)
def __init__(self, parent):
super(Viewer, self).__init__(parent)
self.setRenderHints(QPainter.Antialiasing)
self._zoom = 0
self._empty = True
self.setScene(QGraphicsScene(self))
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setFrameShape(QFrame.NoFrame)
self.area = float()
self.setPoints()
self.viewport().setCursor(Qt.ArrowCursor)
QTimer.singleShot(0, self.reset_fit)
self.selectedItems = []
def setItems(self):
self.data = {
"x": [
-2414943.8686,
-2417160.6592,
-2417160.6592,
-2416009.9966,
-2416012.5232,
-2416012.5232,
],
"y": [
10454269.7008,
10454147.2672,
10454147.2672,
10453240.2808,
10455255.8752,
10455255.8752,
],
"rotation":[
313.9962,
43.9962,
223.9962,
313.9962,
43.9962,
223.9962,
]
}
for i, (x, y,r) in enumerate(zip(self.data["x"], self.data["y"],self.data["rotation"])):
p = Point(x, y,r, "Point__" + str(i))
p.log.hovered.connect(self.hoverChange)
p.log.notHovered.connect(self.notHoverChange)
self.scene().addItem(p)
def setPoints(self):
self.setItems()
self.setDragMode(self.ScrollHandDrag)
def wheelEvent(self, event):
if event.angleDelta().y() > 0:
factor = 1.25
self._zoom += 1
else:
factor = 0.8
self._zoom -= 1
if self._zoom > 0:
self.scale(factor, factor)
elif self._zoom == 0:
self.reset_fit()
else:
self._zoom = 0
def hoverChange(self):
self.viewport().setCursor(Qt.PointingHandCursor)
def notHoverChange(self):
self.viewport().setCursor(Qt.ArrowCursor)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
singleItem = self.itemAt(event.pos().x(), event.pos().y())
if singleItem != None:
if QApplication.keyboardModifiers() == Qt.ShiftModifier: # This will determine if the shift key is depressed
if singleItem.isSelected == True:
singleItem.setSelected(False)
singleItem.isSelected = False
self.selectedItems.remove(singleItem)
elif singleItem.isSelected == False:
singleItem.setSelected(True)
singleItem.isSelected = True
self.selectedItems.append(singleItem)
return
elif event.button() == Qt.MidButton:
self.viewport().setCursor(Qt.ClosedHandCursor)
self.original_event = event
handmade_event = QMouseEvent(
QEvent.MouseButtonPress,
QPointF(event.pos()),
Qt.LeftButton,
event.buttons(),
Qt.KeyboardModifiers(),
)
QGraphicsView.mousePressEvent(self, handmade_event)
super(Viewer, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.MidButton:
self.viewport().setCursor(Qt.ArrowCursor)
handmade_event = QMouseEvent(
QEvent.MouseButtonRelease,
QPointF(event.pos()),
Qt.LeftButton,
event.buttons(),
Qt.KeyboardModifiers(),
)
QGraphicsView.mouseReleaseEvent(self, handmade_event)
def reset_fit(self):
r = self.scene().itemsBoundingRect()
self.resetTransform()
self.setSceneRect(r)
self.fitInView(r, Qt.KeepAspectRatio)
self._zoom = 0
self.scale(1, -1)
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.viewer = Viewer(self)
VBlayout = QVBoxLayout(self)
VBlayout.addWidget(self.viewer)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 800, 600)
window.show()
sys.exit(app.exec_())
最佳答案
您不必在 QGraphicsPathItem 中使用 QPainter,您必须使用 setPen() 设置 QPen。
<小时/>QGraphicsPathItem已经有一个只能在paint()方法中使用的QPainter,但在这种情况下没有必要,现有的QGraphicsItems如QGraphicsRectItem,QGraphicsEllipseItem等没有必要使用它们,因为这些方法继承自QAbstractGraphicsShapeItem并分别使用 setPen() 和 setBrush() 方法支持 QPen 和 QBrush。
我在代码中看到的另一个问题是,您正在使用 isSelected 属性,但您不应该这样做,已经有一个具有该名称的方法,因此您必须使用 isSelected()。
考虑到之前的解决方案是:
class Point(QGraphicsPathItem):
def __init__(self, x, y, r, name):
super(Point, self).__init__()
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.setPath(create_path())
self.setScale(10)
self.setRotation(180 + r)
self.setAcceptHoverEvents(True)
self.log = LogObject()
self.setPos(x, y)
pen = QPen(Qt.red)
pen.setStyle(Qt.DashLine)
self.setPen(pen)
def itemChange(self, change, value):
if change == self.ItemSelectedChange:
color = QColor(Qt.green) if value else QColor("black")
# self.setBrush(color)
pen = self.pen()
pen.setColor(color)
self.setPen(pen)
return QGraphicsItem.itemChange(self, change, value)
def hoverEnterEvent(self, event):
color = QColor("red")
# self.setBrush(color)
pen = self.pen()
pen.setColor(color)
self.setPen(pen)
self.log.hovered.emit()
QGraphicsItem.hoverMoveEvent(self, event)
def hoverLeaveEvent(self, event):
color = QColor(Qt.green) if self.isSelected() else QColor("black")
# self.setBrush(color)
pen = self.pen()
pen.setColor(color)
self.setPen(pen)
self.log.notHovered.emit()
QGraphicsItem.hoverMoveEvent(self, event)
关于python - PyQt5 QGraphicsPathItem 由 QPainter 绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55754220/
我现在已经用 PyQt 做了几个项目,而且我越来越熟悉 Qt 采用的模型/ View 思想流派。我已经将它用于列表和表格 View 之类的东西,它们背后有一个自定义模型来显示和操作数据。我使用委托(d
import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MainWindow(QMainWindow):
使用下面的示例代码(受 here 的严重影响),右键单击上下文菜单并没有真正正确对齐。 从屏幕截图中可以看出,生成的菜单在鼠标光标上方相当多的位置。我希望菜单的左上角与鼠标指针完全对齐。 有没有办法对
所以我创建了一个自定义上下文菜单,但我想根据某些值将树小部件的某些行中的某些项目灰显。如何禁用菜单上的项目? myUI.setContextMenuPolicy( Qt.CustomContextMe
是否可以禁用 QComboBox在 pyqt 中,就像我们可以在 Win Forms(C#) 中那样做,因为我在 QComboBox 中找不到任何选项手动的。我想启用 QcomboBox仅当管理员登录
我想将 QComboBox 与元组中的“键”和“值”一起使用,该元组类似于 django 模型中使用的元组。例如,我对一个人的性别有以下结构。 SEX_CHOICES = (('M', 'Male')
是否可以让 Altair 或 Vega(-Lite) 渲染到 PyQt 小部件,类似于支持多个后端的 Matplotlib?我知道我可以使用 Qt WebView 小部件来呈现带有 Vega 嵌入的网
在下面的示例代码中(受 here 的影响很大),我希望选择单击单元格的整行而不是单个单元格。如何更改代码以合并它? import re import operator import os import
我正在尝试禁用关闭“x”按钮,并且我认为通过将 DockWidgetFeature 设置为仅可移动和可 float 即可工作。 def CreateDockWidget (self): Pan
我已经按照 Yasin Uludag 的一些有用的在线教程来尝试使用 PyQt(或者更确切地说是 PySide)来创建一个简单的 TreeView ,但是我在使用工具提示时遇到了问题。在以下代码中,工
我正在尝试创建一个场景,我需要从 mousePressEvent 位置画线到最新的鼠标 moveposition 这意味着我需要调用 paintEvent 来自 mousePressEvent ,这可
是Python 3的组合和 PyQt 4受到推崇的?有没有其他选择? 最佳答案 我不明白为什么不,有一个 version available对于正常工作的 Python 3,如果你真的需要 Qt,唯一
我正在尝试显示从二进制文件中读取的图像数据(我编写了用于从文件中检索此数据并将其存储为图像以供 QImage() 使用的代码)。我想做的是将 slider 连接到图形 View 小部件,以便当您移动
我已经准备了很多关于如何在 python 和 pyqt 中将多个信号连接到同一个事件处理程序的帖子。例如,将多个按钮或组合框连接到同一功能。 许多示例展示了如何使用 QSignalMapper 执行此
我有一个 PyQt 主窗口,当用户按下某个按钮时,我需要从中获取一串用户输入。 这是我的用户输入窗口代码: class InputDialog(QtGui.QDialog): ''' t
编辑: 以下 buildout.cfg 用于构建 Qt、PyQt 和 SIP [buildout] parts = pyqt [pyqt] recipe = zc.recipe.cmmi ur
我目前正在开发一个应用程序,该应用程序可以使用 PyQt 访问 sqlalchemy 数据库并将其内容显示到 TableView 或其他一些小部件中。现在为了简单起见,我们只说这是一个电话簿,上面有姓
使用我现在拥有的代码,我可以成功地播放文件中的 .mp3 数据。但是我需要使用 QtCore.QBuffer(不是来自文件)播放相同的数据。当我使用文档的示例时,它会出现意外类型的 QBuffer 错
安装 sip 后,我在尝试安装 PyQt-x11-gpl-4.11 时不断收到这个可爱的错误消息。 mycommandline$ python configure-ng.py --verbose Qu
我正在为一个项目使用 PyQt。但并非突然间我收到一个错误: QPixmap: It is not safe to use pixmaps outside the GUI thread in PyQt
我是一名优秀的程序员,十分优秀!