我有先建一個QPushButton
然後幫他建了一個menu
self.menu=QMenu()
self.menu.addAction('編輯', self.Action1)
self.menu.addAction('連接', self.Action2)
self.menu.addAction('刪除',self..deleteLater)
self.button.setMenu(self.menu)
self.button.show()
接著我想在Action1裡面可以回傳一下這個QPushButton的位置
def Action1(self):
print ('You selected Action 1')
print(self.sender())
print(self.pos())
print(script)
但我看了一下sender
好像這時候的self是存menu的
<PyQt5.QtWidgets.QAction object at 0x000001B5874369D8>
請問有什麼方法可以往上找物件的位置嗎?
self.menu=QMenu()
self.menu.addAction('編輯', self.Action1)
self.menu.addAction('連接', self.Action2)
self.menu.addAction('刪除',self..deleteLater)
self.button.setMenu(self.menu)
self.button.show()
看起來你是把上面這些code加到你的View?你這樣2個btn不就要加2次?
你對物件導向的掌握還不夠,我不覺得你這樣學QT能學的成...
PyQT我也才剛學而已...
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
self.view = View(self)
self.button = QPushButton('Clear View', self)
self.button.clicked.connect(self.handleClearView)
layout = QVBoxLayout(self)
layout.addWidget(self.view)
layout.addWidget(self.button)
def handleClearView(self):
self.view.scene().clear()
class DragButton(QPushButton):
def __init__(self, title, parent=None):
super().__init__(title, parent)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showMenu)
def showMenu(self):
menu=QMenu()
menu.addAction('連接', self.connectLine)
menu.addAction('刪除', self.deleteLine)
menu.exec_(self.cursor().pos())
def connectLine(self):
view = self.parent()
view.createLineItem()
def deleteLine(self):
view = self.parent()
view.clearScene()
def mouseMoveEvent(self, e):
if e.buttons() != Qt.LeftButton:
return
mimeData = QMimeData()
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.pos() - self.rect().topLeft())
dropAction = drag.exec_(Qt.MoveAction)
class View(QGraphicsView):
def __init__(self, parent):
QGraphicsView.__init__(self, parent)
self.setScene(QGraphicsScene(self))
self.setAcceptDrops(True)
self.setSceneRect(QtCore.QRectF(self.viewport().rect()))
self.btn1=DragButton('Test1', self)
self.btn2=DragButton('Test2', self)
self.line = None
def _createLineF(self):
start = QtCore.QPointF(self.mapToScene(self.btn1.pos()))
end = QtCore.QPointF(self.mapToScene(self.btn2.pos()))
return QtCore.QLineF(start, end)
def createLineItem(self):
self.line = QGraphicsLineItem(self._createLineF())
self.scene().addItem(self.line)
def clearScene(self):
self.scene().clear()
self.line = None
def dragEnterEvent(self, e):
e.accept()
def dragMoveEvent(self, e):
e.accept()
def dropEvent(self, e):
btn = e.source()
position = e.pos()
btn.move(position)
if self.line:
self.line.setLine(self._createLineF())
e.setDropAction(Qt.MoveAction)
e.accept()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())