#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2016/12/03 03:33:28 +0900> u""" QRubberBandの動作確認. 動作確認環境 : Windows10 x64 + Python 2.7.12 + PySide 1.2.4 """ import sys from PySide.QtCore import * # NOQA from PySide.QtGui import * # NOQA class GView(QGraphicsView): """Graphics View.""" def __init__(self, *argv, **keywords): """init.""" super(GView, self).__init__(*argv, **keywords) scene = QGraphicsScene(self) self.setScene(scene) pm = QPixmap("./tmp_bg.png") pm_item = QGraphicsPixmapItem(pm) scene.addItem(pm_item) # ラバーバンドを生成 self.rband = QRubberBand(QRubberBand.Rectangle, self) self.start_pos = QPoint() def mousePressEvent(self, event): u"""マウスボタンが押された.""" if event.button() == Qt.LeftButton: # 左ボタンが押された self.start_pos = event.pos() # クリックした座標を記憶 rect = QRect(self.start_pos, QSize()) self.rband.setGeometry(rect) # ラバーバンドの範囲を設定 self.rband.show() # ラバーバンドを表示 p0 = self.mapToScene(self.start_pos) x0 = p0.x() y0 = p0.y() self.set_status("(%d, %d)" % (x0, y0)) elif event.button() == Qt.RightButton: # 右ボタンが押された self.rband.hide() # ラバーバンドを非表示に def mouseMoveEvent(self, event): u"""マウスカーソルが動いた.""" if not self.start_pos.isNull(): # マウスクリック後の状態 rect = QRect(self.start_pos, QPoint(event.pos())).normalized() self.rband.setGeometry(rect) # ラバーバンドの範囲を再設定 # ステータスバー相当に座標を表示 p0 = self.mapToScene(self.start_pos) x0 = p0.x() y0 = p0.y() p1 = self.mapToScene(event.pos()) x1 = p1.x() y1 = p1.y() dx = abs(x1 - x0) dy = abs(y1 - y0) self.set_status("(%d, %d) - (%d, %d) : (%d x %d)" % (x0, y0, x1, y1, dx, dy)) def mouseReleaseEvent(self, event): u"""マウスボタンが離された.""" if event.button() == Qt.LeftButton: self.start_pos = QPoint() def set_status(self, str): u"""ステータスバー相当のテキストを設定.""" self.parent().set_status(str) class MyWidget(QWidget): u"""メインウインドウ相当.""" def __init__(self, *argv, **keywords): """init.""" super(MyWidget, self).__init__(*argv, **keywords) self.gview = GView(self) self.lbl = QLabel("Ready", self) l = QVBoxLayout() l.addWidget(self.gview) l.addWidget(self.lbl) self.setLayout(l) def set_status(self, str): u"""ステータスバー相当にテキストを設定.""" self.lbl.setText(str) if __name__ == '__main__': app = QApplication(sys.argv) w = MyWidget() w.show() sys.exit(app.exec_())