def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.graphicsView = QGraphicsView() scene = QGraphicsScene(self.graphicsView) scene.setSceneRect(0, 0, MainWindow.WINDOW_WIDTH, MainWindow.WINDOW_HEIGHT) self.graphicsView.setScene(scene) self.screen = Screen(MainWindow.WINDOW_WIDTH, MainWindow.WINDOW_HEIGHT) scene.addItem(self.screen) mainLayout = QHBoxLayout() mainLayout.setAlignment(Qt.AlignTop) mainLayout.addWidget(self.graphicsView) self.setLayout(mainLayout) self.setWindowTitle("Coup") self.updating_rule = False self.show() # タイマースタート self.timer = QTimer() self.timer.setInterval(int(1000 / MainWindow.FPS)) self.timer.timeout.connect(self.timeout) self.timer.start()
def initialize_loading_page(self): svg_container = QGraphicsScene(self.window().loading_svg_view) svg_item = QGraphicsSvgItem() svg = QSvgRenderer(get_image_path("loading_animation.svg")) svg.repaintNeeded.connect(svg_item.update) svg_item.setSharedRenderer(svg) svg_container.addItem(svg_item) self.window().loading_svg_view.setScene(svg_container) self.window().core_manager.events_manager.upgrader_tick.connect(self.set_loading_text) self.window().core_manager.events_manager.upgrader_started.connect( lambda: self.set_loading_text("Upgrading...")) self.window().core_manager.events_manager.upgrader_finished.connect(lambda: self.loading_label.hide()) # Create a loading label that displays the status during upgrading self.loading_label = QLabel(self) self.loading_label.setStyleSheet("color: #ddd; font-size: 22px;") self.loading_label.setAlignment(Qt.AlignCenter) self.on_window_resize() self.loading_label.hide() # Hide the force shutdown button initially. Should be triggered by shutdown timer from main window. self.window().force_shutdown_btn.hide()
def __init__(self, map, *args): super().__init__(*args) self.map = map self.position = map.center self.providers = deque([ 'osm', 'stamen-terrain', 'stamen-toner-lite', 'stamen-toner', 'stamen-watercolor', 'ms-aerial', 'ms-hybrid', 'ms-road', 'bluemarble', ]) self.refresh_map = asyncio.Event() scene = QGraphicsScene() self.scene = scene self.setScene(scene) self.map_layer = QGraphicsPixmapItem() scene.addItem(self.map_layer) self.circle = QGraphicsEllipseItem(0, 0, 20, 20) pen = QPen(QColor(255, 0, 0, 128)) pen.setWidth(2) self.circle.setPen(pen) scene.addItem(self.circle) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
class CameraWidget(QWidget): def __init__(self, background_color): QWidget.__init__(self) self.scene = QGraphicsScene(self) self.scene.setBackgroundBrush(QBrush(background_color)) self.graphics_view = QGraphicsView(self.scene) self.graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setFrameStyle(0) self.graphics_view.setStyleSheet("QGraphicsView {background: transparent; border: 3px; outline: none;}") self.graphics_view.scale(-1, 1) # this make live video from camero mirror. self.video_item = QGraphicsVideoItem() self.scene.addItem(self.video_item) self.layout = QVBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.graphics_view) self.available_cameras = QCameraInfo.availableCameras() # Set the default camera. self.select_camera(0) def resizeEvent(self, event): self.video_item.setSize(QSizeF(event.size().width(), event.size().height())) QWidget.resizeEvent(self, event) def select_camera(self, i): self.camera = QCamera(self.available_cameras[i]) self.camera.setViewfinder(self.video_item) self.camera.setCaptureMode(QCamera.CaptureStillImage) self.camera.start()
def update_package_view(self): package = self.current_package try: mod = importlib.import_module('packages.{}'.format(package['type'])) except ImportError: return # Draw package # f = tempfile.NamedTemporaryFile() f = open('tmp.svg', 'wb') import target_svg target = target_svg.get_target() target.add_package(package) process = { 'F': TolLen(0, 0.05, 1), 'P': TolLen(0, 0.05, 1) } pac = mod.get_package(package['values'], 'IPC7351-B', process) pac.gen(target) target.output(f) f.flush() # Draw SVG output svg = QGraphicsSvgItem(f.name) scene = QGraphicsScene() scene.addItem(svg) self.package_ui.graphicsView.setScene(scene) f.close()
class PlotView(QGraphicsView): def __init__(self, clrs=colours, parent=None): QGraphicsView.__init__(self, parent) self.scene = QGraphicsScene(self) self.scene.setSceneRect(QtCore.QRectF(0, 0, 440, 340)) self.setScene(self.scene) self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0, 0))) self.setMinimumSize(100, 100) self.colours = clrs def setBackground(self, colour): self.setBackgroundBrush(QtGui.QBrush(colour)) def addLinePlot(self): self.plot = LinePlot(self.colours) self.scene.addItem(self.plot) def addHHeaders(self, headers): self.plot.addHHeaders(headers) def addSeries(self, series, label): self.plot.plot(series, label) def clearPlotContents(self): self.plot.clearPlotContents() def addLimit(self, value): self.plot.addLimitLine(value) def resizeEvent(self, event): self.scene.setSceneRect(QtCore.QRectF( 0, 0, event.size().width(), event.size().height())) if self.plot: self.plot.updatePlot()
def __init__(self, *args): super(Demo, self).__init__(*args) loadUi('MainWindow.ui', self) scene = QGraphicsScene() rectItem = QGraphicsRectItem(QRectF(0, 0, 320, 240)) rectItem.setBrush(Qt.red) #rectItem.setPen(Qt.NoPen) rectItem.setFlag(QGraphicsItem.ItemIsMovable) scene.addItem(rectItem) ellipseItem = QGraphicsEllipseItem(QRectF(0, 0, 200, 200)) ellipseItem.setBrush(Qt.blue) #ellipseItem.setPen(Qt.NoPen) ellipseItem.setFlag(QGraphicsItem.ItemIsMovable) scene.addItem(ellipseItem) rectSizeGripItem = SizeGripItem(SimpleResizer(rectItem), rectItem) ellipseSizeGripItem = SizeGripItem(SimpleResizer(ellipseItem), ellipseItem) graphicsView = QGraphicsView(self) graphicsView.setScene(scene) self.setCentralWidget(graphicsView)
def __init__(self): super(VideoSortApp, self).__init__() self.setupUi(self) self.filename = None self.directory = None self.sort.setEnabled(False) self.fileOpen.clicked.connect(self.fileDialog) self.dirOpen.clicked.connect(self.folderDialog) self.sort.clicked.connect(self.sortVideo) self.results.setViewMode(self.results.IconMode) self.results.setResizeMode(self.results.Adjust) self.features = [] self.sorted = None #player properties self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.playlist = QMediaPlaylist(self.player) self.videoItem = QGraphicsVideoItem() self.videoItem.setSize(QtCore.QSizeF(640, 480)) scene = QGraphicsScene(self) scene.addItem(self.videoItem) self.graphicsView.setScene(scene) self.player.setVideoOutput(self.videoItem) self.graphicsView.resize(640,480) self.graphicsView.show() self.results.itemDoubleClicked.connect(self.seekVideo) self.videoLoaded = False
class ImageView(QGraphicsView): def __init__(self, width=200, height=300): super().__init__() self.setFixedSize(QSize(width, height)) self.image = None self.scene = QGraphicsScene() self.setScene(self.scene) """ファイル名より取得した画像表示""" def setImage(self, imageName): self.setCvImage(cv2.imread(imageName)) """numpy配列より取得した画像表示""" def setCvImage(self, cvImage): cvImage = cv2.cvtColor(cvImage, cv2.COLOR_BGR2RGB) height, width, channel = cvImage.shape bytesPerLine = width * channel self.image = QImage(cvImage.data, width, height, bytesPerLine, QImage.Format_RGB888) item = QGraphicsPixmapItem(QPixmap.fromImage(self.image)) self.scene = QGraphicsScene() self.scene.addItem(item) self.setScene(self.scene) """ビューワクリア処理""" def clear(self): self.scene.clear()
def __init__(self, parent=None, display_status=False): super(VideoPlayer, self).__init__(parent) self.display_status = display_status self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.videoItem = QGraphicsVideoItem() scene = QGraphicsScene(self) graphicsView = QGraphicsView(scene) scene.addItem(self.videoItem) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) if self.display_status: self.status_mapping = { QMediaPlayer.UnknownMediaStatus: "UnknownMediaStatus", QMediaPlayer.NoMedia: "NoMedia", QMediaPlayer.LoadingMedia: "LoadingMedia", QMediaPlayer.LoadedMedia: "LoadedMedia", QMediaPlayer.StalledMedia: "StalledMedia", QMediaPlayer.BufferingMedia: "BufferingMedia", QMediaPlayer.BufferedMedia: "BufferedMedia", QMediaPlayer.EndOfMedia: "EndOfMedia", QMediaPlayer.InvalidMedia: "InvalidMedia" } self.statusText = QPlainTextEdit() self.statusText.setReadOnly(True) self.statusText.setFixedHeight(25) self.statusText.setFixedWidth(150) self.mediaPlayer.mediaStatusChanged.connect(self.mediaStatusChanged) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) if self.display_status: controlLayout.addWidget(self.statusText) layout = QVBoxLayout() layout.addWidget(graphicsView) layout.addLayout(controlLayout) self.setFixedWidth(WIDTH + WIGGLE) self.setLayout(layout) self.mediaPlayer.setVideoOutput(self.videoItem) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged)
class MainWindow(QMainWindow): #somewhere in constructor: def __init__(self): super(MainWindow, self).__init__() uic.loadUi('ui_window.ui', self) self.setupUI() def setupUI(self): root = QFileInfo(__file__).absolutePath() self.actionOpen.setIcon(QIcon(root+'/images/Live Mail.ico')) self.actionSave.setIcon(QIcon(root+'/images/489751-Floppy_Disk-128.png')) self.actionSelect.setIcon(QIcon(root+'/images/mouse.png')) self.actionRip_off.setIcon(QIcon(root+'/images/rip_off.png')) self.setWindowTitle('AnimDNA') self.actionAnalyze_structure.setIcon(QIcon(root+'/images/transformation.png')) self.setWindowIcon((QIcon(root+'/images/bug.png'))) from PyQt5 import QtCore, QtGui, QtWidgets self.main_splitter = QtWidgets.QSplitter(self.centralwidget) self.path_splitter = QtWidgets.QSplitter(self.main_splitter) self.renderView = CustomQGraphicsView(self.path_splitter) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.renderView.sizePolicy().hasHeightForWidth()) self.renderView.setSizePolicy(sizePolicy) self.renderView.setMinimumSize(QtCore.QSize(0, 0)) self.renderView.setMouseTracking(True) self.renderView.setFocusPolicy(QtCore.Qt.WheelFocus) self.renderView.setFrameShadow(QtWidgets.QFrame.Plain) self.renderView.setLineWidth(0) self.renderView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.renderView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.renderView.setRenderHints(QtGui.QPainter.Antialiasing|QtGui.QPainter.HighQualityAntialiasing|QtGui.QPainter.TextAntialiasing) self.renderView.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.renderView.setObjectName("renderView") self.renderView.setupGL(self) self.gridLayout.addWidget(self.main_splitter, 0, 0, 1, 1) self.action_modify = QtWidgets.QAction(self) self.action_modify.setCheckable(True) def updateRenderView(self,doc_ctrl): doc = doc_ctrl._document self.pathscene = QGraphicsScene(parent=self.renderView) self.pathroot = PathRootItem(rect=self.pathscene.sceneRect(),\ parent=None,\ window=self,\ document= doc_ctrl._document) self.pathroot.setFlag(QGraphicsItem.ItemHasNoContents) self.pathscene.addItem(self.pathroot) self.pathscene.setItemIndexMethod(QGraphicsScene.NoIndex) assert self.pathroot.scene() == self.pathscene self.renderView.setScene(self.pathscene) self.renderView.scene_root_item = self.pathroot self.renderView._scale_fit_factor = 0.9 self.renderView._name = 'renderView' self.path_tool_manager = PathToolManager(self,self.path_toolbar)
def __init__(self): super(MainWindow, self).__init__() scene = QGraphicsScene(self) self.tic_tac_toe = TicTacToe() scene.addItem(self.tic_tac_toe) scene.setSceneRect(0, 0, 300, 300) self.setScene(scene) self.setCacheMode(QGraphicsView.CacheBackground) self.setWindowTitle("Tic Tac Toe")
class AnimatedClock(QGraphicsView): def __init__(self, parent=None): QGraphicsView.__init__(self, parent) self.updateSecs = 0.5 # Border self.setLineWidth(0) self.setFrameShape(QtWidgets.QFrame.NoFrame) # Size sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHeightForWidth(True) self.setSizePolicy(sizePolicy) # No scrollbars self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Scene self.scene = QGraphicsScene() self.setScene(self.scene) self.setBackgroundBrush(QColor("black")) # Text of clock self.textItem = QGraphicsTextItem() self.textItem.color = QColor(QColor("black")) self.textItem.setFont(QFont("Segoe UI", 80)) self.textItem.setDefaultTextColor(QColor("white")) self.textItem.setHtml("") self.textItem.setZValue(20) self.scene.addItem(self.textItem) # Start ticking self.start() def sizeHint(self): return QSize(300, 150) def start(self): self.updateTimer = QTimer() self.updateTimer.setInterval(self.updateSecs * 990) self.updateTimer.timeout.connect(self.updateClock) self.updateTimer.start() print("Animated clock - starting") def stop(self): if self.updateTimer != None: self.updateTimer.stop() print("Animated clock - stopping") def updateClock(self): localtime = time.localtime() timeString = time.strftime("%H:%M:%S", localtime) self.textItem.setHtml(timeString) width = self.frameGeometry().width() self.textItem.setFont(QFont("Segoe UI", width / 8)) self.textItem.update() def heightForWidth(self, width): return width * .32 def keyPressEvent(self, event): #QKeyEvent event.ignore()
class Graphics(QGraphicsView): def __init__(self): super(Graphics, self).__init__() self.scene = QGraphicsScene(self) self.setScene(self.scene) def read(self,fn): self.fn = fn self.pic_Item = QGraphicsPixmapItem(QPixmap(fn)) self.scene.addItem(self.pic_Item)
def main(argv): signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) scene = QGraphicsScene() view = QGraphicsView() thumbnails = [] for filename in os.listdir(argv[1]): filename = os.path.join(argv[1], filename) print(filename) thumbnails.append(DBusThumbnailer.thumbnail_from_filename(filename, "large")) count = 0 items = [] for y in range(0, 100000, 150): for x in range(0, 2500, 150): scene.addRect(x, y, 128, 128) # image = QImage(128, 128, QImage.Format_RGB32) if count < len(thumbnails): print(thumbnails[count]) image = QImage(thumbnails[count]) else: arr = numpy.random.randint(0, 2**32, (128, 128), dtype=numpy.uint32) image = QImage(arr, 128, 128, 128 * 4, QImage.Format_ARGB32) pixmap = QPixmap.fromImage(image) item = QGraphicsPixmapItem(pixmap) scene.addItem(item) text = scene.addText("Test Textual: {}".format(count)) item.setPos(x, y) text.setPos(x, y + 128) count += 1 item.setFlags(QGraphicsItem.ItemIsSelectable) item.setAcceptHoverEvents(True) items.append([item, text]) print(count) if False: random.shuffle(items) i = 0 for y in range(0, 100000, 150): for x in range(0, 2500, 150): for item in items[i]: item.setPos(x, y) i += 1 view.setScene(scene) view.resize(800, 600) view.show() app.exec()
class QNEMainWindow(QMainWindow): def __init__(self, parent): super(QNEMainWindow, self).__init__(parent) quitAct = QAction("&Quit", self, shortcut="Ctrl+Q", statusTip="Exit the application", triggered=self.close) addAct = QAction("&Add", self, statusTip="Add a block", triggered=self.addBlock) fileMenu = self.menuBar().addMenu("&File") fileMenu.addAction(addAct) fileMenu.addSeparator() fileMenu.addAction(quitAct) self.setWindowTitle("Node Editor") self.scene = QGraphicsScene(self) self.view = QGraphicsView(self) self.view.setScene(self.scene) self.view.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(self.view) self.nodesEditor = QNodesEditor(self) self.nodesEditor.install(self.scene) block = QNEBlock(None) self.scene.addItem(block) block.addPort("test", 0, QNEPort.NamePort) block.addPort("TestBlock", 0, QNEPort.TypePort) block.addInputPort("in1"); block.addInputPort("in2"); block.addInputPort("in3"); block.addOutputPort("out1"); block.addOutputPort("out2"); block.addOutputPort("out3"); block = block.clone() block.setPos(150,0) block = block.clone() block.setPos(150,150) def addBlock(self): import random import math block = QNEBlock(None) self.scene.addItem(block) names = ["Vin", "Voutsadfasdf", "Imin", "Imax", "mul", "add", "sub", "div", "Conv", "FFT"] for i in range(0,math.floor(random.uniform(3,8))): block.addPort(random.choice(names), random.random()>0.5) block.setPos(self.view.sceneRect().center().toPoint())
def applyEffectToPixmap(pixmap, effect): scene = QGraphicsScene() item = QGraphicsPixmapItem() item.setPixmap(pixmap) item.setGraphicsEffect(effect) scene.addItem(item) res = QPixmap(pixmap.size()) res.fill(Qt.transparent) painter = QPainter(res) scene.render(painter) return res
class VideoPlayerWidget(QWidget): def __init__(self, parent=None): super(VideoPlayerWidget, self).__init__(parent) self.scene = QGraphicsScene(self) self.scene.setBackgroundBrush(QBrush(QColor(0, 0, 0, 255))) self.graphics_view = QGraphicsView(self.scene) self.graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setFrameStyle(0) self.graphics_view.setStyleSheet("QGraphicsView {background: transparent; border: 3px; outline: none;}") self.video_item = QGraphicsVideoItem() self.scene.addItem(self.video_item) self.layout = QVBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.graphics_view) self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.media_player.setVideoOutput(self.video_item) self.video_need_replay = False self.video_seek_durcation = 3000 # in milliseconds def resizeEvent(self, event): self.video_item.setSize(QSizeF(event.size().width(), event.size().height())) QWidget.resizeEvent(self, event) def play(self, url): self.media_player.setMedia(QMediaContent(QUrl.fromLocalFile(url))) self.media_player.play() def seek_forward(self): video_position = self.media_player.position() self.media_player.setPosition(video_position + self.video_seek_durcation) def seek_backward(self): video_position = self.media_player.position() self.media_player.setPosition(max(video_position - self.video_seek_durcation, 0)) def keyPressEvent(self, event): if event.key() == Qt.Key_Space: if self.media_player.state() == QMediaPlayer.PlayingState: self.media_player.pause() self.video_need_replay = False else: self.media_player.play() self.video_need_replay = True elif event.key() == Qt.Key_H: self.seek_backward() elif event.key() == Qt.Key_L: self.seek_forward()
def setBlank(self): # Set the blank tile. When you load a new map, the tilemap will give a # default tile for the blank map. r = str(self.resourceView.currentRow()) c = str(self.resourceView.currentColumn()) file = c + '-' + r pixmap = QPixmap(os.path.join(self.tmp_dir, file + '.png')) pixmapitem = QGraphicsPixmapItem(pixmap) scene = QGraphicsScene() scene.addItem(pixmapitem) self.tileView.setScene(scene) self.blankTile = file
def initialize_discovering_page(self): svg_container = QGraphicsScene(self.window().discovering_svg_view) svg_item = QGraphicsSvgItem() svg = QSvgRenderer(get_image_path("loading_animation.svg")) svg.repaintNeeded.connect(svg_item.update) svg_item.setSharedRenderer(svg) svg_container.addItem(svg_item) self.window().discovering_svg_view.setScene(svg_container) self.window().core_manager.events_manager.discovered_channel.connect(self.on_discovered_channel)
def __display_result_image(self, file_path): image_reader = QImageReader(file_path) if image_reader.canRead() is True: widget_height = self.resultView.height() widget_width = self.resultView.width() image = image_reader.read().scaled(widget_width, widget_height, Qt.KeepAspectRatio) item = QGraphicsPixmapItem(QPixmap.fromImage(image)) scene = QGraphicsScene() scene.addItem(item) self.resultView.setScene(scene) else: scene = QGraphicsScene() self.resultView.setScene(scene)
def generateData(self, canvas, lines, params): scene = QGraphicsScene() scene.setSceneRect(canvas) group = scene.createItemGroup([]) for line in lines: clone = QGraphicsLineItem(line) clone.setLine(line.line()) clone.setPen(line.pen()) scene.addItem(clone) group.addToGroup(clone) pixmaps = [] for i in xrange(params.count): pixmaps.append(self.generateRandom(scene, group, canvas, params)) return pixmaps
def __changed_image_line_edit(self): file_path = self.lineEdit_image.text() image_reader = QImageReader(file_path) if image_reader.canRead() is True: widget_height = self.queryView.height() widget_width = self.queryView.width() image = image_reader.read().scaled(widget_width, widget_height, Qt.KeepAspectRatio) item = QGraphicsPixmapItem(QPixmap.fromImage(image)) scene = QGraphicsScene() scene.addItem(item) self.queryView.setScene(scene) else: scene = QGraphicsScene() self.queryView.setScene(scene)
def __init__(self, size, scene: QGraphicsScene): self.rectItems = [] self.pixmap = QPixmap(QSize(820,820)) self.painter = QPainter(self.pixmap) self.scene = scene self.owners = None self.values = None pen = QPen() pen.setStyle(Qt.NoPen) for index in range(size**2): item = QGraphicsRectItem() item.setRect(int(index/size), int(index%size), 0.9, 0.9) item.setPen(pen) scene.addItem(item) self.rectItems.append(item)
def __init__(self, parent=None): super(VideoPlayer, self).__init__(parent) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.videoItem = QGraphicsVideoItem() self.videoItem.setSize(QSizeF(640, 480)) scene = QGraphicsScene(self) graphicsView = QGraphicsView(scene) scene.addItem(self.videoItem) rotateSlider = QSlider(Qt.Horizontal) rotateSlider.setRange(-180, 180) rotateSlider.setValue(0) rotateSlider.valueChanged.connect(self.rotateVideo) openButton = QPushButton("Open...") openButton.clicked.connect(self.openFile) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(openButton) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) layout = QVBoxLayout() layout.addWidget(graphicsView) layout.addWidget(rotateSlider) layout.addLayout(controlLayout) self.setLayout(layout) self.mediaPlayer.setVideoOutput(self.videoItem) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged)
def main(): app = QApplication(sys.argv) grview = QGraphicsView() scene = QGraphicsScene() scene.setSceneRect(0, 0, 680, 459) scene.addPixmap(QPixmap('../images/phototest.tif')) grview.setScene(scene) item = AreaItem(0, 0, 300, 150) item.areaColor = QColor(155, 155, 0, 75) scene.addItem(item) grview.fitInView(scene.sceneRect(), Qt.KeepAspectRatio) grview.show() sys.exit(app.exec_())
class TmxViewer(QGraphicsView): def __init__(self, parent = None): super().__init__(parent) self.mScene = QGraphicsScene(self) self.mMap = None self.mRenderer = None self.setWindowTitle(self.tr("TMX Viewer")) self.setScene(self.mScene) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setDragMode(QGraphicsView.ScrollHandDrag) self.setOptimizationFlags(QGraphicsView.DontAdjustForAntialiasing | QGraphicsView.DontSavePainterState) self.setBackgroundBrush(Qt.black) self.setFrameStyle(QFrame.NoFrame) self.viewport().setAttribute(Qt.WA_StaticContents) def __del__(self): if (self.mMap): self.mMap.tilesets().clear() del self.mMap del self.mRenderer def viewMap(self, fileName): del self.mRenderer self.mRenderer = None self.mScene.clear() self.centerOn(0, 0) reader = MapReader() self.mMap = reader.readMap(fileName) if (not self.mMap): qWarning("Error:"+reader.errorString()) return False x = self.mMap.orientation() if x==Map.Orientation.Isometric: self.mRenderer = IsometricRenderer(self.mMap) elif x==Map.Orientation.Staggered: self.mRenderer = StaggeredRenderer(self.mMap) elif x==Map.Orientation.Hexagonal: self.mRenderer = HexagonalRenderer(self.mMap) else: self.mRenderer = OrthogonalRenderer(self.mMap) self.mScene.addItem(MapItem(self.mMap, self.mRenderer)) return True
def __init__(self, pomodoro_control, parent=None): super(PomodoroClockView, self).__init__(parent) self.dragPosition = None self.pomodoro_control = pomodoro_control # Hide scrollbars self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setStyleSheet("background: transparent") self.setRenderHint(QPainter.Antialiasing) # A scene containing all the parts of the clock scene = QGraphicsScene() self.setScene(scene) self.clock_back = ClockBack(100) self.hour_hand = SynchronizedClockHand("hour", 50, 50, 37*0.66, 2.3) self.minute_hand = SynchronizedClockHand("minute", 50, 50, 37, 2) self.time_elapsed_view = TimeElapsedView(100, 15, self.pomodoro_control) self.obstruction = CircleObstruction(100, 0) scene.addItem(self.clock_back) scene.addItem(self.hour_hand) scene.addItem(self.minute_hand) scene.addItem(self.time_elapsed_view) scene.addItem(self.obstruction) self.set_color(QColor(0,0,0), QColor(0,0,0)) """ Turns out I can't use a QStateMachine. Why? - I want this class to be *completely* subservient to the internal state of the PomodoroControl. When that changes its state, this class *reacts* to that change. - QStateMachine runs in its own event loop, which does not start until after the app's event loop runs. The state machine will refuse to catch signals until the app is already running. This means that *this class* must know whether it's starting at a started or stopped state. """ self.pomodoro_control.pomodoro_begin.connect(self.pomodoro_begin) self.pomodoro_control.pomodoro_complete.connect(self.pomodoro_complete) if self.pomodoro_control.is_running: self.pomodoro_begin() else: self.pomodoro_complete()
def test(self): raw = numpy.load(os.path.join(volumina._testing.__path__[0], "lena.npy")).astype(numpy.uint32) ars = _ArraySource2d(raw) ims = DummyItemSource(ars) req = ims.request(QRect(0, 0, 256, 256)) item = req.wait() assert isinstance(item, QGraphicsItem) DEBUG = False if DEBUG: from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene app = QApplication([]) scene = QGraphicsScene() scene.addItem(item) view = QGraphicsView(scene) view.show() view.raise_() app.exec_()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.scene = QGraphicsScene() self.scene.setSceneRect(QRectF(0, 0, 1000, 1000)) item = FlumeObject("source", "r1") self.scene.addItem(item.pictogram) item.pictogram.setPos(200, 200) layout = QHBoxLayout() self.view = QGraphicsView(self.scene) layout.addWidget(self.view) self.view.setAlignment(Qt.AlignLeft | Qt.AlignTop) # FIXME doesn't work as needed self.widget = QWidget() self.widget.setLayout(layout) self.setCentralWidget(self.widget) self.setWindowTitle("The Flume Illustrator")
class ImageViewer(QWidget): """ The main window of the GUI. """ def __init__(self): """ Initiate the GUI with some text-format data. @param text: data text (comma or tab delimited string) """ # GUI constructor super().__init__() # graphics scene #self.scene = RoiScene(500, 200) #self.scene.add_roi(QGraphicsEllipseItem(0, 0, 60, 30), 20, 30) #self.scene.add_roi(QGraphicsRectItem(0, 0, 60, 20), 300, 40) #self.scene.add_roi(RoiSelection(400, 150), 400, 150) self.scene = QGraphicsScene(0, 0, 500, 200) self.scene.addItem(RoiSelection(100, 100)) self.scene.addItem(RoiSelection(400, 150)) #self.scene.addItem(RoiSelection(20, 50)) #self.scene.addItem(RoiSelection(200, 50)) #self.scene.focusItemChanged.connect(lambda: self.scene_focus_item_changed()) #self.scene.changed.connect(lambda: self.scene_changed()) # graphics view self.viewer = QGraphicsView(self.scene) self.viewer.setSceneRect(0, 0, self.scene.width(), self.scene.height()) self.viewer.setInteractive(True) self.viewer.show() # layout layout = QVBoxLayout() layout.addWidget(self.viewer) self.setLayout(layout) self.resize(self.scene.width(), self.scene.height())
class CameraWidget(QWidget): def __init__(self, background_color): QWidget.__init__(self) self.scene = QGraphicsScene(self) self.scene.setBackgroundBrush(QBrush(background_color)) self.graphics_view = QGraphicsView(self.scene) self.graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setFrameStyle(0) self.graphics_view.setStyleSheet( "QGraphicsView {background: transparent; border: 3px; outline: none;}" ) self.graphics_view.scale(-1, 1) # this make live video from camero mirror. self.video_item = QGraphicsVideoItem() self.scene.addItem(self.video_item) self.layout = QVBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.graphics_view) self.available_cameras = QCameraInfo.availableCameras() # Set the default camera. self.select_camera(0) def resizeEvent(self, event): self.video_item.setSize( QSizeF(event.size().width(), event.size().height())) QWidget.resizeEvent(self, event) def select_camera(self, i): self.camera = QCamera(self.available_cameras[i]) self.camera.setViewfinder(self.video_item) self.camera.setCaptureMode(QCamera.CaptureStillImage) self.camera.start()
class ImageWidget(QGraphicsView): def __init__(self, *args, **kwargs): super(ImageWidget, self).__init__(*args, **kwargs) self.resize(800, 600) # 设置背景颜色 self.setBackgroundBrush(QColor(31, 31, 47)) # 去掉滚动条 # self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 设置变换中心为鼠标所在位置 self.setTransformationAnchor(self.AnchorUnderMouse) # 不保证painter的状态 self.setOptimizationFlags(self.DontSavePainterState) self.setViewportUpdateMode(self.SmartViewportUpdate) self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) # 场景 self._scene = QGraphicsScene(0, 0, self.width(), self.height()) self.setScene(self._scene) self._scene.addItem(MoveableItem(100, 100, 200, 200))
class ImageGraphicsEffect(QObject): """ Applies a QGraphicsEffect to a QImage """ def __init__(self, parent: QObject, effect: QGraphicsEffect): super().__init__(parent) assert effect, 'effect must be set' self.effect = effect self.graphics_scene = QGraphicsScene() self.graphics_item = QGraphicsPixmapItem() self.graphics_item.setGraphicsEffect(effect) self.graphics_scene.addItem(self.graphics_item) def apply(self, image: QImage): assert image, 'image must be set' result = QImage(image.size(), QImage.Format_ARGB32) result.fill(Qt.transparent) painter = QPainter(result) self.graphics_item.setPixmap(QPixmap.fromImage(image)) self.graphics_scene.render(painter) self.graphics_item.setPixmap(QPixmap()) return result
def draw_denoised(self, idx): try: dcm_path = self.save_path + '\\' + self.denoised_dcm_list[idx - 1] except: return ds = dcmread(dcm_path) img = ds.pixel_array img = np.clip(img, self.CTmin, self.CTmax) img = img.astype(np.int16) img = ((img - self.CTmin) / self.WW) * 255 img = img.astype(np.int8) image = QImage(img, img.shape[1], img.shape[0], img.shape[1], QImage.Format_Grayscale8) pix = QPixmap.fromImage(image) pix = pix.scaled(self.matrix, self.matrix, Qt.KeepAspectRatio, Qt.SmoothTransformation) item = QGraphicsPixmapItem(pix) scene = QGraphicsScene() scene.addItem(item) self.graphicsViewProcessing.setScene(scene)
def on_button_open_image_clicked(self): """ Slot documentation goes here. """ try: dlg = win32ui.CreateFileDialog(1) dlg.SetOFNInitialDir(os.getcwd()) dlg.DoModal() filename = dlg.GetPathName() img = cv2.imread(filename) if img is None: QMessageBox.information(self, "提示", "打开图片失败,请检查路径中是否有中文", QMessageBox.Yes) return self.cartoon.raw_img = img pix = self.cvimg2pix(img) item = QGraphicsPixmapItem(pix) # 创建像素图元 scene = QGraphicsScene() # 创建场景 scene.addItem(item) self.graphicsView.setScene(scene) except Exception as e: print(e) return
def _initGridview(self, doc: DocT) -> GraphicsViewT: """Initializes Grid View. Args: doc: The :class:`Document` corresponding to the design Returns: :class:`CustomQGraphicsView` """ grid_scene = QGraphicsScene(parent=self.grid_graphics_view) grid_root = GridRootItem(rect=grid_scene.sceneRect(), parent=None, window=self, document=doc) grid_scene.addItem(grid_root) grid_scene.setItemIndexMethod(QGraphicsScene.NoIndex) assert grid_root.scene() == grid_scene ggv = self.grid_graphics_view ggv.setScene(grid_scene) ggv.scene_root_item = grid_root ggv.setName("GridView") self.grid_tool_manager = GridToolManager(self, grid_root) return ggv
def _initPathview(self, doc: DocT) -> GraphicsViewT: """Initializes Path View. Args: doc: The :class:`Document` corresponding to the design Returns: :class:`CustomQGraphicsView` """ path_scene = QGraphicsScene(parent=self.path_graphics_view) path_root = PathRootItem(rect=path_scene.sceneRect(), parent=None, window=self, document=doc) path_scene.addItem(path_root) path_scene.setItemIndexMethod(QGraphicsScene.NoIndex) assert path_root.scene() == path_scene pgv = self.path_graphics_view pgv.setScene(path_scene) pgv.scene_root_item = path_root pgv.setScaleFitFactor(0.7) pgv.setName("PathView") return pgv
def get_image( self ): # p.s. изображение желательно кидать в папку с проектом, для удобства file = QFileDialog.getOpenFileName()[ 0] # откроется папка, в которой лежит проект self.path = file # в path пропишется путь к изображению, которое мы выбрали self.im = Image.open( self.path) # в im будет лежать открытое изображение pix = QtGui.QPixmap(self.path) # в pix грузим путь scene = QGraphicsScene() # создаём сцену для обозревателя graphicsView item = QGraphicsPixmapItem( pix) # создаём объект, в который загружаем pix scene.addItem(item) # добавляем в сцену объект item self.ui.graphicsView.mousePressEvent = self.mpe # функция для мыши self.ui.graphicsView.mouseMoveEvent = self.mme # функция для мыши self.ui.graphicsView.mouseReleaseEvent = self.mre # функция для мыши self.ui.graphicsView.setScene( scene) # устанавливаем сцену в обозреватель graphicsView self.ui.label.setText("Формат: {}".format(self.im.format)) self.ui.label_2.setText("Размеры: {}x{}".format( int(self.im.size[0]), int(self.im.size[1]))) self.ui.label_3.setText("Глубина цвета: {}-bit".format( self.depthc(self.im.mode)))
class EasyScaleView(QGraphicsView): def __init__(self, parent=None): self.__scene = QGraphicsScene(parent) super().__init__(self.__scene) self.currentScale = 1.0 def zoom(self, mul): self.currentScale *= mul self.update_scale() def resizeEvent(self, event): super().resizeEvent(event) # if self.__item is not None: self.update_scale() def update_scale(self): for i in self.items(): self.update_item_scale(i) def update_item_scale(self, item): scale = self.width() / (item.pixmap().width() + 1) * self.currentScale item.setScale(scale) rect = item.boundingRect() rect.setSize(rect.size() * scale) self.setSceneRect(rect) def scroll(self, offset): scroll = self.verticalScrollBar() scroll.setValue(scroll.value() + offset) def display_image(self, image_path): print(image_path) self.__scene.clear() item = QGraphicsPixmapItem(QPixmap(image_path)) self.__scene.addItem(item) self.verticalScrollBar().setValue(0) self.update_scale()
def draw_line(self, line_tuple): self.view.setStyleSheet('background: transparent; border-style: none') del self.view self.view = QGraphicsView(self) x = self.x() y = self.y() width = self.width() height = self.height() scene = QGraphicsScene(QRectF(x, y, width, height)) self.view.setStyleSheet('background: transparent; border-style: none') self.view.setFixedSize(width, height) self.view.setScene(scene) pen = QPen() pen.setColor(QColor(65, 105, 225)) pen.setWidth(10) line_coordinates = self.get_line_coordinates(line_tuple) scene.addLine(line_coordinates[0], line_coordinates[1], line_coordinates[2], line_coordinates[3], pen) winner_label = self.create_winner_label() scene.addItem(winner_label) self.view.show() timer = QTimer(self.view) timer.timeout.connect(winner_label.show) timer.start(1000)
class ImageDialogViewer(QGraphicsView): def __init__(self, parent=None): super(ImageDialogViewer, self).__init__(parent) self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) # self.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setDragMode(QGraphicsView.ScrollHandDrag) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self._scene = QGraphicsScene(self) self.setScene(self._scene) self._pixmap = None @property def pixmap(self): return self._pixmap @pixmap.setter def pixmap(self, value: QPixmap): self._pixmap = value self._pixmap = QGraphicsPixmapItem() self._pixmap.setPixmap(value) size = 300 w = value.width() h = value.height() scale = size / w new_w, new_h = w * scale, h * scale self._pixmap.setOffset(-value.width() / 2, -value.height() / 2) self._pixmap.setTransformationMode(QtCore.Qt.SmoothTransformation) self._scene.addItem(self._pixmap) self.scale(scale, scale) def wheelEvent(self, event: QWheelEvent): adj = (event.angleDelta().y() / 120) * 0.1 self.scale(1 + adj, 1 + adj)
def initialize_loading_page(self): svg_container = QGraphicsScene(self.window().loading_svg_view) svg_item = QGraphicsSvgItem() svg = QSvgRenderer(get_image_path("loading_animation.svg")) svg.repaintNeeded.connect(svg_item.update) svg_item.setSharedRenderer(svg) svg_container.addItem(svg_item) self.window().loading_svg_view.setScene(svg_container) self.window().core_manager.events_manager.upgrader_tick.connect( self.set_loading_text) self.window().core_manager.events_manager.upgrader_started.connect( lambda: self.set_loading_text("Upgrading...")) self.window().core_manager.events_manager.upgrader_finished.connect( lambda: self.loading_label.hide()) # Create a loading label that displays the status during upgrading self.loading_label = QLabel(self) self.loading_label.setStyleSheet("color: #ddd; font-size: 22px;") self.loading_label.setAlignment(Qt.AlignCenter) self.on_window_resize() self.loading_label.hide()
def __setup_interface(self): """ Initialise user interface elements """ theme = "light_theme.qss" if GWASMiner.config.get(section="preferences", option="theme").lower() == "dark": theme = "dark_theme.qss" self.__load_style(theme) self.form.stackedWidget.setGeometry(0, 0, self.window.width(), self.window.height()) self.navigate_to_page(0) self.form.status_lbl.setHidden(True) self.set_loading_visible(True) splash_loading_scene = QGraphicsScene() main_loading_scene = QGraphicsScene() splash_loading_svg = QGraphicsSvgItem("res/loading.svg") splash_loading_svg.setScale(0.4) main_loading_svg = QGraphicsSvgItem("res/loading.svg") main_loading_svg.setScale(0.4) splash_loading_scene.addItem(splash_loading_svg) main_loading_scene.addItem(main_loading_svg) self.form.test_loading_graphicsview.setScene(splash_loading_scene) self.form.loading_svg.setScene(main_loading_scene)
def __init__(self): super(MainWindow, self).__init__() #self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers | QGL.DirectRendering))) settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) settings.setAttribute(QWebSettings.WebGLEnabled, True) scene = QGraphicsScene(self) w = QGraphicsWebView() w.page().settings().setAttribute( QWebSettings.AcceleratedCompositingEnabled, True) w.page().settings().setAttribute(QWebSettings.WebGLEnabled, True) w.resize(900, 700) plot_content = plots.plot3d() w.setHtml(html % {'plot_content': plot_content}) scene.addItem(w) scene.setSceneRect(0, 0, 900, 700) self.setScene(scene) #self.setCacheMode(QGraphicsView.CacheBackground) self.setWindowTitle("Plot 3D")
def AddPictureAnswer6(self): try: id = self.lineEdit_tmbs.text() if id == "": reply = QMessageBox.information(self, "标题", "试题标识不能为空,请先添加试题!", QMessageBox.Yes) return else: fileName, filetype = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "图片文件(*.jpg);") # 将选中的文件入库 self.m_db.WriteFileToBlob("TPDA6", "XXFZK.TKB", "where ID='" + id + "'", fileName) # 显示图片 image = QPixmap() image.load(fileName) scene = QGraphicsScene() self.picture_answer_item6 = QGraphicsPixmapItem(image) scene.addItem(self.picture_answer_item6) self.graphicsView_da6.setScene(scene) self.picture_answer_zoomscale6 = 1 except: print("添加图片答案6时发错误!")
def ShowImageOnGraphicsView(self, count, pixmap, isPreview): pixmapItem = QGraphicsPixmapItem(pixmap) image_scene = QGraphicsScene() image_scene.addItem(pixmapItem) if isPreview == False: self.statusBar().showMessage("总计图片: {} 张,正在处理第 {} 张".format(len(self.current_image_list),count)) self.progressBar.show() self.progressBar.setMaximum(len(self.current_image_list)) self.progressBar.setValue(count) self.graphicsView.setScene(image_scene) self.graphicsView.fitInView(pixmapItem,QtCore.Qt.AspectRatioMode.KeepAspectRatio) if len(self.current_image_list) == count: self.statusBar().showMessage("图片处理完成。") self.progressBar.hide() self.previewBtn.setEnabled(True) self.textWatermarkContentsLineEdit.setEnabled(True) self.fontSizeSlideBar.setEnabled(True) self.defaultCurrentDateCb.setEnabled(True) self.realtimePreviewCb.setEnabled(True) self.spinBox.setEnabled(True) self.radioGrey.setEnabled(True) self.radioBlack.setEnabled(True) self.radioWhite.setEnabled(True) self.addWatermarksBtn.setEnabled(True)
class MainWindow(QtWidgets.QWidget): def __init__(self): super(MainWindow, self).__init__() self.view = QGraphicsView() self.scene = QGraphicsScene() self.view.setScene(self.scene) self.view.setViewport(QGLWidget()) self.button_nodes = QtWidgets.QPushButton('Add Node') self.button_wires = QtWidgets.QPushButton('Add Wire') self.button_vis = QtWidgets.QPushButton('Toggle Visibility') mainLayout = QtWidgets.QHBoxLayout() mainLayout.addWidget(self.view) button_layout = QtWidgets.QVBoxLayout() mainLayout.addLayout(button_layout) button_layout.addWidget(self.button_nodes) button_layout.addWidget(self.button_wires) button_layout.addWidget(self.button_vis) self.setLayout(mainLayout) self.view.show() self.click_positions = [] self.button_nodes.clicked.connect(self.add_node) self.button_wires.clicked.connect(self.add_wire) self.button_vis.clicked.connect(self.toggle_vis) self.first_node = True self.vis = True def add_node(self): if self.first_node: self.node1 = Node(QColor("#93b0ff"), "Node 1") self.scene.addItem(self.node1) self.first_node = False else: self.node2 = Node(QColor("#9effa1"), "Node 2") self.scene.addItem(self.node2) self.first_node = True def add_wire(self): start = self.node1 end = self.node2 bc = BezierCurve(start, end, self.scene, self) self.scene.addItem(bc) start.add_wire(bc) end.add_wire(bc) def toggle_vis(self): scene_items = self.scene.items() if self.vis: scene_items[1].setVisible(False) scene_items[2].setVisible(False) self.vis = False else: scene_items[1].setVisible(True) scene_items[2].setVisible(True) self.vis = True
def _initSliceview(self, doc: DocT) -> GraphicsViewT: """Initializes Slice View. Args: doc: The :class:`Document` corresponding to the design Returns: :class:`CustomQGraphicsView` """ slice_scene = QGraphicsScene(parent=self.slice_graphics_view) slice_root = SliceRootItem(rect=slice_scene.sceneRect(), parent=None, window=self, document=doc) slice_scene.addItem(slice_root) slice_scene.setItemIndexMethod(QGraphicsScene.NoIndex) assert slice_root.scene() == slice_scene sgv = self.slice_graphics_view sgv.setScene(slice_scene) sgv.scene_root_item = slice_root sgv.setName("SliceView") sgv.setScaleFitFactor(0.7) self.slice_tool_manager = SliceToolManager(self, slice_root) return sgv
def Show_Img(self,img,Viewer): #img_name = self.Choose_Img() #self.Ui.File_Edit.setText(img_name) #config_data.set('path','original',img_name)# write the path to config with open(config_file,'w') as config: config_data.write(config) config.close() #img = cv.imread(img_name) img_RGB = cv.cvtColor(img,cv.COLOR_BGR2RGB) img_resized = cv.resize(img_RGB,(Viewer.height(),Viewer.width())) Show_image = QtGui.QImage(img_resized, img_resized.shape[1], img_resized.shape[0], img_resized.shape[1]*img_resized.shape[2], # Linewidth four-byte alignment, it must be done if the width can't be divided by 4 QtGui.QImage.Format_RGB888)# convert the img format to the qt format pix = QtGui.QPixmap.fromImage(Show_image) item = QGraphicsPixmapItem(pix) # create pix metas scene = QGraphicsScene() scene.addItem(item) Viewer.setScene(scene)
class RollingGame(QMainWindow): """GUI of Dice Rolling""" def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.scene = QGraphicsScene(self) self.scene2 = QGraphicsScene(self) self.pixmap = QtGui.QPixmap() self.pixmap.load(DicePicture.Dice[1]) self.pixmap2 = QtGui.QPixmap() self.pixmap2.load(DicePicture.Dice[1]) item = QGraphicsPixmapItem(self.pixmap) item2 = QGraphicsPixmapItem(self.pixmap2) self.scene.addItem(item) self.scene2.addItem(item2) self.ui.graphicsView.setScene(self.scene) self.ui.graphicsView_2.setScene(self.scene2) self.ui.RollDice.clicked.connect(self.roller) self.Dice = Dice(2, 6) self.show() def roller(self): """Roll Dice""" Roll = self.Dice.Roll() self.pixmap.load(DicePicture.Dice[Roll[0]]) self.pixmap2.load(DicePicture.Dice[Roll[1]]) item = QGraphicsPixmapItem(self.pixmap) item2 = QGraphicsPixmapItem(self.pixmap2) self.scene.addItem(item) self.scene2.addItem(item2) self.ui.graphicsView.setScene(self.scene) self.ui.graphicsView_2.setScene(self.scene2)
def __init__(self, parent=None): QGraphicsView.__init__(self, parent=parent) self.setBackgroundBrush(QColor(125, 255, 125)) player = Player() computer = Computer() board = Board(computer) dropArea = DropArea(board) scene = QGraphicsScene(self) scene.addItem(board) scene.addItem(dropArea) scene.addItem(player) self.setScene(scene)
def __init__(self, parent): super().__init__(parent) self.uas = None svgRenderer = QSvgRenderer('res/compass.svg') self.compass = QGraphicsSvgItem() self.compass.setSharedRenderer(svgRenderer) self.compass.setCacheMode(QGraphicsItem.NoCache) self.compass.setElementId('needle') center = self.compass.boundingRect().center() self.compass.setTransformOriginPoint(center.x(), center.y()) bkgnd = QGraphicsSvgItem() bkgnd.setSharedRenderer(svgRenderer) bkgnd.setCacheMode(QGraphicsItem.NoCache) bkgnd.setElementId('background') self.compass.setPos( bkgnd.boundingRect().width() / 2 - self.compass.boundingRect().width() / 2, bkgnd.boundingRect().height() / 2 - self.compass.boundingRect().height() / 2) self.compass.setTransformOriginPoint( self.compass.boundingRect().width() / 2, self.compass.boundingRect().height() / 2) fregnd = QGraphicsSvgItem() fregnd.setSharedRenderer(svgRenderer) fregnd.setCacheMode(QGraphicsItem.NoCache) fregnd.setElementId('foreground') scene = QGraphicsScene() scene.addItem(bkgnd) scene.addItem(self.compass) scene.addItem(fregnd) scene.setSceneRect(bkgnd.boundingRect()) view = QGraphicsView(scene) view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) layout = QVBoxLayout() layout.addWidget(view) super().setLayout(layout)
def init_ui(self): scene = QGraphicsScene() scene.setBackgroundBrush(QColor(100, 100, 100)) scene.setItemIndexMethod(QGraphicsScene.BspTreeIndex) scene.setSceneRect(scene.itemsBoundingRect()) self.setDragMode(QGraphicsView.RubberBandDrag) self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) self.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing) self.frame_item = QGraphicsPixmapItem() self.text_item_offset = 0 self.rect_item_array = [] self.text_item_array = [] for i in range(0, 5): rect_item = QGraphicsRectItem() rect_item.setVisible(False) rect_item.setZValue(20.0) rect_item.setPen(QPen(Qt.red, 5)) rect_item.setRect(20, 20, 20, 20) scene.addItem(rect_item) self.rect_item_array.append(rect_item) text_item = QGraphicsSimpleTextItem("") text_item.setBrush(QBrush(Qt.red)) text_item.setZValue(20.0) text_item.setPos(10, 50) text_item.setFont(QFont("黑体", 32)) text_item.setVisible(False) scene.addItem(text_item) self.text_item_array.append(text_item) scene.addItem(self.frame_item) self.curr_factor = 1.0 self.setScene(scene)
class MainWindow(QMainWindow, Ui_MainWindow): PREDICT_PATH = "predict_images/" # 设置计数器的值为 10 sem = Semaphore(10) cwd = None image_list = [] image_path = None def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) # 图像显示区相关初始化 self._scene = QGraphicsScene() # 创建场景,用于显示图片 self.graphicsView.setScene(self._scene) # 将场景添加至视图 self.currentImage = None self.zoom_scale = 1 # 图像的缩放比例 self.imageGraphicItem = QGraphicsPixmapItem() # 用于在scene中显示Image self.imageGraphicItem.setZValue(0) # 设置显示在0层 self._scene.addItem(self.imageGraphicItem) # 图片列表相关操作 self.importButton.clicked.connect(self._import_image) self._init_image_list() self.imageList.itemDoubleClicked.connect(self._image_select) # 关闭按钮位置设置 self.closeButton.move(self.graphicsView.width() / 2, 10) self.closeButton.setVisible(False) self.closeButton.clicked.connect(self._close_image) self.removeImageButton.clicked.connect(self._delete_image) self.cleanListButton.clicked.connect(self._clear_image_list) def _init_image_list(self): for file_name in os.listdir(self.PREDICT_PATH): if file_name.endswith('.jpg'): image = cv2.imread(self.PREDICT_PATH + file_name) self.image_list.append([file_name, image]) self.add_image_item(file_name, image) def add_image_item(self, file_name, image): item = QListWidgetItem() item.setText(file_name) item.image = image self.imageList.addItem(item) def show_message(self, msg): QApplication.processEvents() self.resultView.append(msg) self.resultView.moveCursor( self.resultView.textCursor().End) def _image_select(self, selected_item): self.selectedImageItem = selected_item self.image_path = self.PREDICT_PATH + selected_item.text() self.closeButton.setVisible(True) self.closeButton.setEnabled(True) self.removeImageButton.setEnabled(True) self.show_image(selected_item.image) def show_image(self, image): self.imageGraphicItem.setVisible(True) # 关闭键按钮在视图界面居中,注:46是button长度的一半 self.closeButton.move((self.graphicsView.width() / 2) - 46, 10) self.currentImage = image image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 转换图像通道 image_width = image.shape[1] # 获取图像大小 image_height = image.shape[0] frame = QImage(image, image_width, image_height, QImage.Format_RGB888) pix = QPixmap.fromImage(frame) self.imageGraphicItem.setPixmap(pix) # 根据graphicsView的大小,调整图片的比例 scale_x = self.graphicsView.width() / image_width scale_y = self.graphicsView.height() / image_height if scale_x < scale_y: self.zoom_scale = scale_x else: self.zoom_scale = scale_y self.imageGraphicItem.setScale(self.zoom_scale) def _import_image(self): files, file_type = QtWidgets.QFileDialog.getOpenFileNames(self, '图片选择', self.cwd, # 起始路径 'All Files (*);;Image Files (*.jpg)') for file in files: # 获取一个 semaphore self.sem.acquire() import_thread = Thread( target=self._copy_image, args=(file, self.PREDICT_PATH)) import_thread.start() QApplication.processEvents() def _copy_image(self, source_file, target_folder): shutil.copy(source_file, target_folder) file_name = os.path.basename(source_file) if file_name not in self.image_list: self.image_list.append(file_name) image = cv2.imread(self.PREDICT_PATH + file_name) self.add_image_item(file_name, image) # 关闭标准图片,并完成相应的UI界面变化 def _close_image(self): self.imageGraphicItem.setVisible(False) self.selectedImageItem = None self.removeImageButton.setEnabled(False) self.closeButton.setEnabled(False) self.closeButton.setVisible(False) def _delete_image(self): self.remove(self.selectedImageItem.text()) self._remove_image_item() def _clear_image_list(self): shutil.rmtree(self.PREDICT_PATH) os.mkdir(self.PREDICT_PATH) self.image_list.clear() self.imageList.clear() def _remove_image_item(self): row = self.imageList.row(self.selectedImageItem.image) self.imageList.takeItem(row) self._close_image() def remove(self, file_name): for image in self.image_list: if image[0] == file_name: self.image_list.remove(image) break os.remove(self.PREDICT_PATH + file_name)
class APISRepresentativeImage(QDialog, FORM_CLASS): def __init__(self, dbm, imageRegistry, currentPath, filmNumber, parent=None): """Constructor.""" super(APISRepresentativeImage, self).__init__(parent) self.dbm = dbm self.imageRegistry = imageRegistry self.currentPath = currentPath self.filmNumber = filmNumber self.newPath = currentPath self.setupUi(self) if GetWindowSize("representative_image"): self.resize(GetWindowSize("representative_image")) self.settings = QSettings(QSettings().value("APIS/config_ini"), QSettings.IniFormat) # Signals/Slot Connections self.rejected.connect(self.onReject) self.buttonBox.rejected.connect(self.onReject) self.buttonBox.accepted.connect(self.onAccept) self.uiSelectImageFromSystem.clicked.connect( self.selectImageFromSystem) self.graphicLoaded = False self.scene = QGraphicsScene() self.uiRepresentativeImageView.setScene(self.scene) # ist FilmProjekt ein FILM? if IsFilm(self.dbm.db, self.filmNumber): self.populateFilmCombo(self.filmNumber) else: self.populateFilmCombo() # wenn nein self.populateFilmCombo() self.uiAvailableImagesCombo.currentIndexChanged.connect( self.loadNewImageByFilm) def populateFilmCombo(self, filmNumber=None): editor = self.uiFilmNumberCombo model = QSqlQueryModel(self) model.setQuery( "SELECT DISTINCT {0} FROM {1} ORDER BY {2}".format( 'filmnummer', 'film', 'filmnummer'), self.dbm.db) tv = QTableView() editor.setView(tv) tv.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) tv.setSelectionMode(QAbstractItemView.SingleSelection) tv.setSelectionBehavior(QAbstractItemView.SelectRows) tv.setAutoScroll(False) editor.setModel(model) editor.setModelColumn(0) editor.setInsertPolicy(QComboBox.NoInsert) tv.resizeColumnsToContents() tv.resizeRowsToContents() tv.verticalHeader().setVisible(False) tv.horizontalHeader().setVisible(True) # tv.setMinimumWidth(tv.horizontalHeader().length()) tv.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) #FIXME PyQt5 AutoCompletion #editor.setAutoCompletion(True) if filmNumber: editor.setCurrentIndex(editor.findText(filmNumber)) self.populateAvailableImagesCombo() else: editor.setCurrentIndex(-1) editor.currentIndexChanged.connect(self.populateAvailableImagesCombo) def populateAvailableImagesCombo(self, idx=None): self.filmNumber = self.uiFilmNumberCombo.currentText() # query image registry availableImages = self.imageRegistry.getImageRegistryForFilm( self.filmNumber) self.uiAvailableImagesCombo.clear() self.uiAvailableImagesCombo.addItems(availableImages) self.uiAvailableImagesCombo.setCurrentIndex(-1) def showEvent(self, event): if self.currentPath: self.uiImagePathLbl.setText(self.currentPath) self.loadImage(self.currentPath) else: self.uiImagePathLbl.setText("--") self.loadText() self.graphicLoaded = True def loadText(self): self.scene.clear() noImageTxt = QGraphicsTextItem() noImageTxt.setPlainText( u"Wählen Sie ein repräsentatives Luftbild aus ...") self.rect = noImageTxt.boundingRect() self.scene.addItem(noImageTxt) self.scene.setSceneRect(self.rect) self.uiRepresentativeImageView.fitInView(self.rect, Qt.KeepAspectRatio) def loadImage(self, path): self.scene.clear() image = QImage(path) size = image.size() self.rect = QRectF(0, 0, size.width(), size.height()) self.scene.addPixmap(QPixmap.fromImage(image)) self.scene.setSceneRect(self.rect) self.uiRepresentativeImageView.fitInView(self.rect, Qt.KeepAspectRatio) def loadNewImageByFilm(self): # generatePath imgDir = self.settings.value("APIS/image_dir") filmDir = self.filmNumber self.newPath = os.path.normpath( imgDir + "\\" + filmDir + "\\" + self.uiAvailableImagesCombo.currentText().replace('.', '_') + ".jpg") self.uiImagePathLbl.setText(self.newPath) self.loadImage(self.newPath) def resizeEvent(self, event): if self.graphicLoaded: self.uiRepresentativeImageView.fitInView(self.rect, Qt.KeepAspectRatio) def selectImageFromSystem(self): dir = self.settings.value("APIS/image_dir") fileName, _filter = QFileDialog.getOpenFileName( self, u"Repräsentatives Luftbild auswählen", dir, "Bild Dateien (*.jpg)") if fileName: self.uiFilmNumberCombo.setCurrentIndex(-1) self.newPath = fileName self.uiImagePathLbl.setText(self.newPath) self.loadImage(self.newPath) def onAccept(self): ''' Check DB Save options when pressing OK button Update Plugin Status ''' SetWindowSize("representative_image", self.size()) self.accept() def onReject(self): ''' Run some actions when the user closes the dialog ''' SetWindowSize("representative_image", self.size()) self.close()
class Graph(object): def __init__(self,graphView,doubleView): self.scene =QGraphicsScene() self.GraphViewGraphImg = graphView #graphview Tab self.DoubleViewGraphImg = doubleView #doubleview Tab self.GraphViewGraphImg.setScene(self.scene) self.DoubleViewGraphImg.setScene(self.scene) # Generate Graph def createGraph(self, nodeList): for i in range(len(nodeList)): self.createGraphHelper(nodeList[i]) def createGraphHelper(self, nodeItem): G = pydot.Dot(graph_type="digraph") node = pydot.Node(nodeItem) G.add_node(node) _bytes = G.create(format='png') image = QPixmap() image.loadFromData(_bytes) node1 = self.scene.addPixmap(image) node1.setFlag(QGraphicsItem.ItemIsMovable) node1.setFlag(QGraphicsItem.ItemIsSelectable) im = Image(G.create_png()) #display(im) # Add New Node to graph def addNewNode(self): global x x += 1 G = pydot.Dot(graph_type="digraph") node = pydot.Node("Node #" + str(x)) G.add_node(node) _bytes = G.create(format='png') image = QPixmap() image.loadFromData(_bytes) node1 = self.scene.addPixmap(image) node1.setFlag(QGraphicsItem.ItemIsMovable) node1.setFlag(QGraphicsItem.ItemIsSelectable) im = Image(G.create_png()) #display(im) # Delete Node from Graph def deleteNode(self): selectedNode = self.scene.selectedItems() if(len(selectedNode) == 0): print("Nothing selected") else: self.scene.removeItem(selectedNode[0]) # Add Relationship def addRelationship(self): selectedNode = self.scene.selectedItems() if(len(selectedNode) < 2): print("Not enough nodes selected") elif(len(selectedNode) > 2): print("Too many nodes selected") elif(len(selectedNode) == 2): print(selectedNode[0].pos(), selectedNode[1].pos()) qitem = QGraphicsLineItem(QLineF(selectedNode[0].pos(), selectedNode[1].pos())) self.scene.addItem(qitem) def ExportGraphJPEG(self): # with open("GraphEXPORTED.png", "wb") as f: # f.write(self._bytes) pixmap = self.GraphViewGraphImg.grab() pixmap.save("GraphEXPORTED.jpeg") def ExportGraphPNG(self): # with open("GraphEXPORTED.png", "wb") as f: # f.write(self._bytes) pixmap = self.GraphViewGraphImg.grab() pixmap.save("GraphEXPORTED.png")
def run(): app = QApplication(sys.argv) scene = QGraphicsScene() # adding scene background scene.setBackgroundBrush(QBrush(QImage('./imgs/background.png'))) player = Player() # add the item to the scene scene.addItem(player) # make player focusable player.setFlag(QGraphicsItem.ItemIsFocusable) player.setFocus() # add a view, widget(invisible) view = QGraphicsView(scene) view.setFixedSize(800, 600) # horizontal and vertical scroll bar has benn disabled view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scene.setSceneRect(0, 0, 800, 600) player.setPos(view.width() / 2 - player.pixmap().width() / 2, view.height() - player.pixmap().height()) view.show() global score score = Score() scene.addItem(score) global health health = Health() scene.addItem(health) # spawn enemies timer = QTimer() def spawn(): enemy = Enemy() scene.addItem(enemy) timer.timeout.connect(spawn) timer.start(1000) # play background music url = QUrl.fromLocalFile("./sounds/intro.ogg") media = M.QMediaContent(url) playlist = M.QMediaPlaylist() playlist.addMedia(media) playlist.setPlaybackMode(M.QMediaPlaylist.Loop) music = M.QMediaPlayer() music.setPlaylist(playlist) music.setVolume(10) music.play() # media = M.QMediaContent(url) # music = M.QMediaPlayer() # music.setMedia(media) # music.setVolume(20) # music.play() sys.exit(app.exec_())
class Game(QGraphicsView): end_signal = pyqtSignal(int) score_signal = pyqtSignal(int) def __init__(self): """ Function creates MyView object. """ QGraphicsView.__init__(self) self.__init_game() self.__init_ui() def __init_game(self): """ Function initializes all backend game fields. :return: """ self.bombs = [] self.timer = QTimer() self.player = Player.Player(1, 1, 0) self.bots = [ Bot.Bot(10 + (i + 1) * 6, 10 + (i + 1) * 6, i + 1) for i in range(num_of_bots) ] self.score = 0 self.create_board() self.move_dict = { Qt.Key_Left: self.move_left, Qt.Key_Right: self.move_right, Qt.Key_Up: self.move_up, Qt.Key_Down: self.move_down, Qt.Key_Space: self.add_bomb } for bot in self.bots: bot.remember_board(self.board) bot.remember_player_pos([self.player]) bot.remember_bombs(self.bombs) def __init_ui(self): """ Function initializes User Interface and Map view. :return: """ self.scene = QGraphicsScene(0, 0, WINDOW_HEIGHT, WINDOW_WIDTH) self.view = QGraphicsView(self.scene) self.draw_board() self.setScene(self.scene) self.timer.timeout.connect(self.update) self.timer.start(10) self.timer_bots = QTimer() self.timer_bots.timeout.connect(self.move_bot) self.timer_bots.start(200) self.items = self.scene.items() def reinit_game(self): """ Function gets game to init state. :return: """ self.__init_game() self.__init_ui() def get_obj(self, x, y): """ Function returns object in a map by coordinates. :param x: x coordinate of an object :param y: y coordiate of an object :return: Object. """ for item in self.items: if item.x == x and item.y == y: return item else: return None def update(self): """ Function handles all games parameters such as bombs boom, player death etc. Should be called periodically. :return: """ for bomb in self.bombs: self.board[bomb.x][bomb.y] = 'XX' # Add bomb to the board. self.draw_image(bomb.x, bomb.y, path_bomb) if self.player.alive: self.board[self.player.x][ self.player.y] = 'OO' # Add player to the board. self.draw_image(self.player.last_x, self.player.last_y, path_road) self.draw_image(self.player.x, self.player.y, path_bomberman) for bot in self.bots: if bot.alive: self.board[bot.x][bot.y] = 'BB' self.draw_image(bot.last_x, bot.last_y, path_road) self.draw_image(bot.x, bot.y, path_bot) self.score_signal.emit(self.score) self.boom() def read_board_xml(self, filename="map.xml"): """ Function reads game map from the XML file. :param filename: Name of xml file. :return: """ xmldoc = xm.parse(filename) rowslist = xmldoc.getElementsByTagName('row') for i in range(len(rowslist)): obj = rowslist[i].getElementsByTagName('obj') for j in range(len(obj)): self.board[i][j] = obj[j].firstChild.data def write_board_xml(self, filename="map.xml"): """ Function writes game map to the XML file. :param filename: Name of xml file. :return: """ doc = xm.Document() map_elem = doc.createElement("mapa") for i in range(len(self.board)): row_elem = doc.createElement("row") for j in range(len(self.board[0])): obj_elem = doc.createElement("obj") row_elem.appendChild(obj_elem) obj_elem.appendChild(doc.createTextNode(self.board[i][j])) map_elem.appendChild(row_elem) doc.appendChild(map_elem) with open(filename, 'w') as the_file: the_file.write(doc.toprettyxml()) def draw_board(self): """ Function draw whole game map. :return: """ self.scene.clear() for bomba in self.bombs: self.board[bomba.X][bomba.Y] = 'XX' if self.player.alive: self.board[self.player.x][self.player.y] = 'OO' for bot in self.bots: if bot.alive: self.board[bot.x][bot.y] = 'BB' for i in range(len(self.board)): for j in range(len(self.board[i])): if self.board[i][j] == '##': self.draw_image(i, j, path_cant_destroy) elif self.board[i][j] == '**': self.draw_image(i, j, path_can_destroy) elif self.board[i][j] == ' ': self.draw_image(i, j, path_road) elif self.board[i][j] == 'OO': self.draw_image(i, j, path_bomberman) elif self.board[i][j] == 'XX': self.draw_image(i, j, path_bomb) elif self.board[i][j] == 'BB': self.draw_image(i, j, path_bot) def create_board(self): """ Function creates game map. It's based on creating maze algorithm. :return: """ temp = numpy.zeros((MAP_WIDTH, MAP_HEIGHT), dtype=bool) temp = temp.astype(str) for x in range(MAP_WIDTH): for y in range(MAP_HEIGHT): if x == 0 or y == 0 or x == MAP_WIDTH - 1 or y == MAP_HEIGHT - 1: temp[x][y] = "##" elif x % 2 == 0 and y % 2 == 0: temp[x][y] = "##" else: temp[x][y] = "**" if temp[self.player.x + 1][self.player.y] != "##": temp[self.player.x + 1][self.player.y] = " " if temp[self.player.x][self.player.y + 1] != "##": temp[self.player.x][self.player.y + 1] = " " if temp[self.player.x + 2][self.player.y] != "##": temp[self.player.x + 2][self.player.y] = " " if temp[self.player.x][self.player.y + 2] != "##": temp[self.player.x][self.player.y + 2] = " " for i in range(len(self.bots)): if temp[self.bots[i].x - 1][self.bots[i].y] != "##": temp[self.bots[i].x - 1][self.bots[i].y] = " " if temp[self.bots[i].x][self.bots[i].y - 1] != "##": temp[self.bots[i].x][self.bots[i].y - 1] = " " if temp[self.bots[i].x - 2][self.bots[i].y] != "##": temp[self.bots[i].x - 2][self.bots[i].y] = " " if temp[self.bots[i].x][self.bots[i].y - 2] != "##": temp[self.bots[i].x][self.bots[i].y - 2] = " " temp[14][16] = " " temp[16][14] = " " temp[14][15] = " " temp[15][17] = " " temp[15][15] = " " temp[15][14] = " " self.board = temp def draw_image(self, x, y, path): """ Function draw single image on game map. :param x: X coordinate of an image. :param y: Y coordinate of an image. :param path: path with an image to be printed. :return: """ # Remove items from scene. self.items = self.scene.items() item = self.get_obj(x, y) if len(self.items) > MAP_HEIGHT * MAP_WIDTH: if item is not None: self.scene.removeItem(item) item = MyRect.MyRect(x, y, path) item.setAcceptHoverEvents(True) item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable) self.scene.addItem(item) def keyPressEvent(self, event): """ Key press event. :param event: :return: """ self.move_dict[event.key()](self.player) def move_up(self, player): """ Function checks if player can go up. If can it moves, if can't it does nothing. :param player: Player to be moved. :return: """ if player.y < MAP_HEIGHT - 1 and self.board[player.x][player.y + 1] != '**'\ and self.board[player.x][player.y + 1] != '##': self.board[player.x][player.y] = ' ' player.move('u') def move_down(self, player): """ Function checks if player can go down. If can it moves, if can't it does nothing. :param player: Player to be moved. :return: """ if player.y > 1 and self.board[player.x][player.y - 1] != '**'\ and self.board[player.x][player.y - 1] != '##': self.board[player.x][player.y] = ' ' player.move('d') def move_left(self, player): """ Function checks if player can go left. If can it moves, if can't it does nothing. :param player: Player to be moved. :return: """ if player.x > 1 and self.board[player.x - 1][player.y] != '**'\ and self.board[player.x - 1][player.y] != '##': self.board[player.x][player.y] = ' ' player.move('l') def move_right(self, player): """ Function checks if player can go right. If can it moves, if can't it does nothing. :param player: Player to be moved. :return: """ if player.x < MAP_HEIGHT - 1 and self.board[player.x + 1][player.y] != '**'\ and self.board[player.x + 1][player.y] != '##': self.board[player.x][player.y] = ' ' player.move('r') def add_bomb(self, player): """ Function adds bomb to bombs list. :param player: Player which left the bomb. :return: """ self.bombs.append( Bomb.Bomb(player.x, player.y, time.time(), player.ind)) def boom(self): """ Function handles bombs explosion. :return: """ end = False for bomb in self.bombs: if time.time() - bomb.start > 3: self.clean_fields_after_boom(bomb) end = self.kill_players(bomb) self.bombs.remove(bomb) if bomb.owner == self.player.ind: self.score += bomb_range if end: self.end_signal.emit(1) def clean_fields_after_boom(self, bomb): """ Function cleans fields after bomb explosion. :param bomb: :return: """ for field in bomb.get_cords_in_range(): if 0 < field[0] < MAP_WIDTH and \ 0 < field[1] < MAP_HEIGHT and \ self.board[field[0]][field[1]] != "##": self.board[field[0]][field[1]] = " " self.draw_image(field[0], field[1], path_road) self.board[bomb.x][bomb.y] = " " self.draw_image(bomb.x, bomb.y, path_road) def kill_players(self, bomb): """ Function checks if player is killed by bomb. If is it returns True else returns False :param bomb: Bomb object :return: """ for cords in bomb.get_cords_in_range(): if (self.player.x, self.player.y) == cords: self.player.alive = False for bot in self.bots: if (bot.x, bot.y) == cords: bot.alive = False return not self.player.alive def move_bot(self): """ Function handles bot move. :return: """ for bot in self.bots: old_x = bot.x old_y = bot.y bot.move() if bot.is_bomb_left(): self.bombs.append(Bomb.Bomb(old_x, old_y, time.time(), 1)) self.board[bot.last_x][bot.last_y] = "XX" else: self.board[old_x][old_y] = " " self.board[bot.x][bot.y] = "BB" bot.remember_player_pos([self.player]) bot.remember_board(self.board) bot.remember_bombs(self.bombs)
class BrushingModel(QObject): brushSizeChanged = pyqtSignal(int) brushColorChanged = pyqtSignal(QColor) brushStrokeAvailable = pyqtSignal(QPointF, object) drawnNumberChanged = pyqtSignal(int) minBrushSize = 1 maxBrushSize = 61 defaultBrushSize = 3 defaultDrawnNumber = 1 defaultColor = Qt.white erasingColor = Qt.black erasingNumber = 100 def __init__(self, parent=None): QObject.__init__(self, parent=parent) self.sliceRect = None self.bb = QRect() #bounding box enclosing the drawing self.brushSize = self.defaultBrushSize self.drawColor = self.defaultColor self._temp_color = None self._temp_number = None self.drawnNumber = self.defaultDrawnNumber self.pos = None self.erasing = False self._hasMoved = False self.drawOnto = None #an empty scene, where we add all drawn line segments #a QGraphicsLineItem, and which we can use to then #render to an image self.scene = QGraphicsScene() def toggleErase(self): self.erasing = not (self.erasing) if self.erasing: self.setErasing() else: self.disableErasing() def setErasing(self): self.erasing = True self._temp_color = self.drawColor self._temp_number = self.drawnNumber self.setBrushColor(self.erasingColor) self.brushColorChanged.emit(self.erasingColor) self.setDrawnNumber(self.erasingNumber) def disableErasing(self): self.erasing = False self.setBrushColor(self._temp_color) self.brushColorChanged.emit(self.drawColor) self.setDrawnNumber(self._temp_number) def setBrushSize(self, size): self.brushSize = size self.brushSizeChanged.emit(self.brushSize) def setDrawnNumber(self, num): self.drawnNumber = num self.drawnNumberChanged.emit(num) def getBrushSize(self): return self.brushSize def brushSmaller(self): b = self.brushSize if b > self.minBrushSize: self.setBrushSize(b - 1) def brushBigger(self): b = self.brushSize if self.brushSize < self.maxBrushSize: self.setBrushSize(b + 1) def setBrushColor(self, color): self.drawColor = QColor(color) self.brushColorChanged.emit(self.drawColor) def beginDrawing(self, pos, sliceRect): ''' pos -- QPointF-like ''' self.sliceRect = sliceRect self.scene.clear() self.bb = QRect() self.pos = QPointF(pos.x(), pos.y()) self._hasMoved = False def endDrawing(self, pos): has_moved = self._hasMoved # _hasMoved will change after calling moveTo if has_moved: self.moveTo(pos) else: assert (self.pos == pos) self.moveTo(QPointF(pos.x() + 0.0001, pos.y() + 0.0001)) # move a little # Qt seems to use strange rules for determining which pixels to set when rendering a brush stroke to a QImage. # We seem to get better results if we do the following: # 1) Slightly offset the source window because apparently there is a small shift in the data # 2) Render the scene to an image that is MUCH larger than the scene resolution (4x by 4x) # 3) Downsample each 4x4 patch from the large image back to a single pixel in the final image, # applying some threshold to determine if the final pixel is on or off. tempi = QImage(QSize(4 * self.bb.width(), 4 * self.bb.height()), QImage.Format_ARGB32_Premultiplied) #TODO: format tempi.fill(0) painter = QPainter(tempi) # Offset the source window. At first I thought the right offset was 0.5, because # that would seem to make sure points are rounded to pixel CENTERS, but # experimentation indicates that 0.25 is slightly better for some reason... source_rect = QRectF(QPointF(self.bb.x() + 0.25, self.bb.y() + 0.25), QSizeF(self.bb.width(), self.bb.height())) target_rect = QRectF(QPointF(0, 0), QSizeF(4 * self.bb.width(), 4 * self.bb.height())) self.scene.render(painter, target=target_rect, source=source_rect) painter.end() # Now downsample: convert each 4x4 patch into a single pixel by summing and dividing ndarr = qimage2ndarray.rgb_view(tempi)[:, :, 0].astype(int) ndarr = ndarr.reshape((ndarr.shape[0], ) + (ndarr.shape[1] // 4, ) + (4, )) ndarr = ndarr.sum(axis=-1) ndarr = ndarr.transpose() ndarr = ndarr.reshape((ndarr.shape[0], ) + (ndarr.shape[1] // 4, ) + (4, )) ndarr = ndarr.sum(axis=-1) ndarr = ndarr.transpose() ndarr //= 4 * 4 downsample_threshold = (7. / 16) * 255 labels = numpy.where(ndarr >= downsample_threshold, numpy.uint8(self.drawnNumber), numpy.uint8(0)) labels = labels.swapaxes(0, 1) assert labels.shape[0] == self.bb.width() assert labels.shape[1] == self.bb.height() ## ## ensure that at least one pixel is label when the brush size is 1 ## ## this happens when the user just clicked without moving ## in that case the lineitem will be so tiny, that it won't be rendered ## into a single pixel by the code above if not has_moved and self.brushSize <= 1 and numpy.count_nonzero( labels) == 0: labels[labels.shape[0] // 2, labels.shape[1] // 2] = self.drawnNumber self.brushStrokeAvailable.emit(QPointF(self.bb.x(), self.bb.y()), labels) def dumpDraw(self, pos): res = self.endDrawing(pos) self.beginDrawing(pos, self.sliceRect) return res def moveTo(self, pos): #data coordinates oldX, oldY = self.pos.x(), self.pos.y() x, y = pos.x(), pos.y() line = QGraphicsLineItem(oldX, oldY, x, y) line.setPen( QPen(QBrush(Qt.white), self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.scene.addItem(line) self._hasMoved = True #update bounding Box if not self.bb.isValid(): self.bb = QRect(QPoint(oldX, oldY), QSize(1, 1)) #grow bounding box self.bb.setLeft( min(self.bb.left(), max(0, x - self.brushSize // 2 - 1))) self.bb.setRight( max(self.bb.right(), min(self.sliceRect[0] - 1, x + self.brushSize // 2 + 1))) self.bb.setTop(min(self.bb.top(), max(0, y - self.brushSize // 2 - 1))) self.bb.setBottom( max(self.bb.bottom(), min(self.sliceRect[1] - 1, y + self.brushSize // 2 + 1))) #update/move position self.pos = pos