-
-
Save akiross/e7a6119a7e622bed9477 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python3 | |
import sys | |
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsView, QGraphicsScene, QGraphicsItem, QGraphicsTextItem | |
from PyQt5.QtGui import QPainterPath | |
class StyledItem(QGraphicsTextItem): | |
def __init__(self, parent=None): | |
super().__init__(parent) | |
# Items can be moved and selected | |
self.setFlag(QGraphicsItem.ItemIsMovable) | |
self.setFlag(QGraphicsItem.ItemIsSelectable) | |
def boundingRect(self): | |
m = 10 # Margin | |
br = super().boundingRect() | |
abr = br.adjusted(-m, -m, m, m) | |
return abr | |
def shape(self): | |
ss = QPainterPath() | |
ss.addRect(self.boundingRect()) | |
return ss | |
def paint(self, painter, options, widget=None): | |
# Draw a rectangle around the text | |
br = self.boundingRect() | |
painter.drawRect(br) | |
# Draw the text | |
super().paint(painter, options, widget) | |
class MainWindow(QMainWindow): | |
def __init__(self): | |
super().__init__() | |
# Setup scene and view | |
self._scene = QGraphicsScene() | |
self._view = QGraphicsView(self) | |
self._view.setScene(self._scene) | |
self._view.setDragMode(QGraphicsView.RubberBandDrag) | |
self.setCentralWidget(self._view) | |
self._i = StyledItem() | |
# self._i.setPlainText('foo') ### UNCOMMENT ### | |
self._scene.addItem(self._i) | |
if __name__ == '__main__': | |
app = QApplication(sys.argv) | |
mw = MainWindow() | |
mw.setWindowTitle('Example') | |
mw.show() | |
sys.exit(app.exec_()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment