Last active
May 25, 2016 11:25
-
-
Save ZhengRui/12c4bb43ac0d3e0c2e645d2669add76c to your computer and use it in GitHub Desktop.
pyqt4 rectangle select by edge/stroke
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PyQt4 import QtGui, QtCore | |
import sys | |
class QStrokeRect(QtGui.QGraphicsRectItem): | |
def __init__(self, parent=None): | |
super(QStrokeRect, self).__init__(parent) | |
self.strokeWidth = 4 | |
self.setPen(QtGui.QPen(QtGui.QColor(255, 0, 0), 4, QtCore.Qt.SolidLine)) | |
self.setFlags(QtGui.QGraphicsItem.ItemIsSelectable) | |
def setStrokeWidth(self, strokeWidth): | |
self.strokeWidth = strokeWidth | |
def shape(self): | |
path = QtGui.QPainterPath() | |
path.addRect(self.boundingRect()) | |
pStroker = QtGui.QPainterPathStroker() | |
pStroker.setWidth(self.strokeWidth) | |
return pStroker.createStroke(path) | |
class QTestView(QtGui.QGraphicsView): | |
def __init__(self, parent=None): | |
super(QTestView, self).__init__(parent) | |
self.scene = QtGui.QGraphicsScene(self) | |
self.scene.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.darkGray, QtCore.Qt.SolidPattern)) | |
self.setScene(self.scene) | |
class Example(QtGui.QWidget): | |
def __init__(self, parent=None): | |
super(Example, self).__init__(parent) | |
self.initUI() | |
def initUI(self): | |
self.setGeometry(300, 300, 500, 500) | |
self.setWindowTitle('Select by stroke') | |
self.gv = QTestView(self) | |
self.gv.setMouseTracking(True) | |
self.pen = QtGui.QPen(QtGui.QColor(255, 0, 0), 4, QtCore.Qt.SolidLine) | |
self.gv.scene.addRect(QtCore.QRectF(0,0,400,400), self.pen) | |
self.gv.scene.addItem(QStrokeRect(QtCore.QRectF(100,100,100,100))) | |
self.gv.scene.addItem(QStrokeRect(QtCore.QRectF(150,150,100,100))) | |
if __name__ == '__main__': | |
app = QtGui.QApplication(sys.argv) | |
ex = Example() | |
ex.show() | |
app.exec_() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment