def __init__(self, *args): QGraphicsScene.__init__(self, *args) # Add a graphic item, not responsive to gestures?? text = QGraphicsTextItem("Test") text.setTextInteractionFlags(Qt.TextEditorInteraction) self.addItem(text)
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 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 GraphInstanceVM(BTreeInstanceVM): @classmethod def get_full_path(cls, file_name): file_path = os.path.join(config.src_path, file_name) return file_path @classmethod def get_model(cls, full_path): if os.path.exists(full_path): model = BTreeModel.load_file(full_path) return model else: return None def init_view(self): self.btree_scene = QGraphicsScene() self.btree_view = NodeEditorView(self.btree_scene) self.btree_view.setAttribute(Qt.WA_DeleteOnClose) self.btree_scene.setSceneRect(AREA) self.vm = NodeObserverVM(self.model, self.btree_view, self.btree_scene, self) def close_handler(self, ev): self.parent.remove_instance(self) def set_dirty(self): pass
class SampleImageWidget(QWidget): def __init__(self, parent=None): super(SampleImageWidget, self).__init__(parent) self.graphicsScene = QGraphicsScene(self) self.graphicsView = SampleGraphicsView(self.graphicsScene) def setSampleImage(self, pathToFile): self.graphicsView.hide() #clear scene self.graphicsScene.clear() #load file tmpImage = QImage(pathToFile) self.originalHeight = tmpImage.height() self.originalWidth = tmpImage.width() tmpPixmap = QPixmap(1) tmpPixmap.convertFromImage(tmpImage.scaledToWidth(300)) self.scaledHeight = tmpPixmap.height() self.scaledWidth = tmpPixmap.width() #add to scene and show self.graphicsScene.addPixmap(tmpPixmap) self.graphicsView.show()
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, 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)
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): 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 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 __init__(self, pickerView): scene = QGraphicsScene() scene.addText("QGraphicsItem in QGraphicsView. Press mouse to mock pick, key to open dialog.") QGraphicsView.__init__(self, scene) # Accept touch on both this widget and viewport (abstract scroll area) # Touch engenders LMB mouse press event since app attribute for that is set. self.setAttribute(Qt.WA_AcceptTouchEvents) self.viewport().setAttribute(Qt.WA_AcceptTouchEvents) self.qmlMaster = QmlMaster() """ See the QML, created there? " A Person model which is mock-picked" self.model = Person() """ if pickerView is not None: self.pickerView = pickerView self.pickDelegate = self.qmlMaster.findComponent( self.pickerView, className=model.person.Person, objectName="person" ) self.dialogDelegate = self.qmlMaster.findComponent( self.pickerView, className=model.qmlDelegate.QmlDelegate, objectName="dialogDelegate" ) else: self.pickDelegate = None self.dialogDelegate = None
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 initUI(self): self.scene1=QGraphicsScene() self.scene2=QGraphicsScene() self.scene3=QGraphicsScene() self.scene4=QGraphicsScene() self.actionOpen.triggered.connect(self.imageOpen) self.histogram.clicked.connect(self.imageHistogram) self.GrayvalueScrollBar.valueChanged.connect(self.sliderval) self.OTSU.clicked.connect(self.OTSUThreshold) self.MedianFilter.clicked.connect(self.medianfilter) self.MeanFilter.clicked.connect(self.meanfilter) self.GaussianFilter.clicked.connect(self.gaussianfilter) self.CoustomizedFilter.clicked.connect(self.coustomizefilter) self.BinaryErosion.clicked.connect(self.binaryerosion) self.BinaryDilation.clicked.connect(self.binarydilation) self.actionClear_All.triggered.connect(self.clearall) self.DistanceTransform.clicked.connect(self.distancetransform) self.Skeleton.clicked.connect(self.skeleton) self.SkeletonRestoration.clicked.connect(self.skeletonrestoration) self.GrayErosion.clicked.connect(self.grayerosion) self.GrayDilation.clicked.connect(self.graydilation) self.EdgeDetection.clicked.connect(self.edgedetection) self.Gradient.clicked.connect(self.gradient) self.Reconstraction_Binary.clicked.connect(self.reconstruction_binary) self.Reconstraction_Gray.clicked.connect(self.reconstruction_gray)
def set_signal(self): indx = self.ui.combobox_signals.currentIndex() if indx != 0: self.ui.inpt.setReadOnly(True) else: self.ui.inpt.setReadOnly(False) self.ui.inpt.setText("10010110") self.decoder_update() return signal = self.signals[indx - 1] pa = ProtocolAnalyzer(signal) pa.get_protocol_from_signal() self.ui.inpt.setText("".join(pa.decoded_proto_bits_str)) tmp_scene = QGraphicsScene() tmp_scene.addText(self.tr("Loading Signal...")) QApplication.instance().setOverrideCursor(Qt.WaitCursor) self.ui.graphicsView_signal.setScene(tmp_scene) if signal is not None: last_message = pa.messages[-1] lookup = {i: msg.bit_sample_pos for i, msg in enumerate(pa.messages)} plot_data = signal.qad[lookup[0][0]:lookup[pa.num_messages - 1][len(last_message) - 1]] self.ui.graphicsView_signal.plot_data(plot_data) self.ui.graphicsView_signal.centerOn(0, 0) QApplication.instance().restoreOverrideCursor()
def showogrenci(self): try: ogrenci = OgrenciGoster(self.parent) self.parent.mdi.addSubWindow(ogrenci) ogrenci.show() data = self.sender().data ogrenci.ad.setText(data[1]) ogrenci.soyad.setText(data[2]) ogrenci.anneadi.setText(data[4]) ogrenci.babaadi.setText(data[5]) gp = QGraphicsScene(self) ogrenci.graphicsView.setScene(gp) ogrenci.graphicsView.setFixedHeight(100) ogrenci.graphicsView.setFixedWidth(100) if data[8] is not None: gp.addPixmap(QPixmap("db/%s" % data[8])) ogrenci.graphicsView.show() nots = self.parent.db.getNot(data[0]) ogrenci.tableWidget.setRowCount(len(nots)) ogrenci.tableWidget.setColumnCount(1) ogrenci.tableWidget.setHorizontalHeaderLabels(["Notlar"]) z = 0 for i in nots: ogrenci.tableWidget.setItem(z,0,QTableWidgetItem(i[2])) z +=1 except Exception as e: print(e)
def imgInit(self): self.cv_img = cv2.imread(os.path.join(sampleDataPath,"color_filter_test.png")) self.frameBuffer = Queue() self.frameBufferItemGroup = QGraphicsItemGroup() self.frameBufferItemGroup.hide() self.inputPixmapRenderScene = QGraphicsScene() self.inputPixmapRenderScene.addItem(self.frameBufferItemGroup) self.inputScene = QGraphicsScene() self.inputGraphicsView.setScene(self.inputScene) self.inputGraphicsView.resizeEvent = self.graphicsViewResized # self.inputScene.addItem(self.frameBufferItemGroup) qimg = misc.cvMatToQImage(self.cv_img) self.inputPixmap = QPixmap.fromImage(qimg) self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap) self.inputScene.addItem(self.inputPixmapItem) self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self.inputGraphicsView) self.inputGraphicsView.mousePressEvent = self.inputGraphicsViewMousePressEvent self.inputGraphicsView.mouseMoveEvent = self.inputGraphicsViewMouseMoveEvent self.inputGraphicsView.mouseReleaseEvent = self.inputGraphicsViewMouseReleaseEvent self.inputGraphicsView.viewport().installEventFilter(self) self.inputGraphicsView.setMouseTracking(True) self.overlayScene = QGraphicsScene() self.inputGraphicsView.setOverlayScene(self.overlayScene) self.zoomedGraphicsView.setScene(self.inputScene) self.zoomedGraphicsView.setOverlayScene(self.overlayScene)
def on_imagesTree_currentItemChanged(self, current, previous): """ Private slot to show a preview of the selected image. @param current current image entry (QTreeWidgetItem) @param previous old current entry (QTreeWidgetItem) """ if current is None: return imageUrl = QUrl(current.text(1)) if not imageUrl.host(): imageUrl.setHost(QUrl(self.siteAddressLabel.text()).host()) imageUrl.setScheme(QUrl(self.siteAddressLabel.text()).scheme()) import Helpviewer.HelpWindow cache = Helpviewer.HelpWindow.HelpWindow.networkAccessManager().cache() if cache: cacheData = cache.data(imageUrl) else: cacheData = None pixmap = QPixmap() invalidPixmap = False scene = QGraphicsScene(self.imagePreview) if not cacheData: invalidPixmap = True else: pixmap.loadFromData(cacheData.readAll()) if pixmap.isNull(): invalidPixmap = True if invalidPixmap: scene.addText(self.tr("Preview not available.")) else: scene.addPixmap(pixmap) self.imagePreview.setScene(scene)
def mousePressEvent(self, event): QGraphicsScene.mousePressEvent(self, event) if not (any(key.pressed for key in self.piano_keys) or any(note.pressed for note in self.notes)): for note in self.selected_notes: note.setSelected(False) self.selected_notes = [] if event.button() == Qt.LeftButton: if self.insert_mode: self.place_ghost = True else: self.marquee_select = True self.marquee_rect = QRectF(event.scenePos().x(), event.scenePos().y(), 1, 1) self.marquee = QGraphicsRectItem(self.marquee_rect) self.marquee.setBrush(QColor(255, 255, 255, 100)) self.addItem(self.marquee) else: for s_note in self.notes: if s_note.pressed and s_note in self.selected_notes: break elif s_note.pressed and s_note not in self.selected_notes: for note in self.selected_notes: note.setSelected(False) self.selected_notes = [s_note] break for note in self.selected_notes: if not self.velocity_mode: note.mousePressEvent(event)
class OverlaidGraphicsView(QGraphicsView): def __init__(self, parent=None): super(OverlaidGraphicsView, self).__init__(parent) self.m_overlayScene = QGraphicsScene() def setOverlayScene(self, scene): if scene is self.m_overlayScene: return self.m_overlayScene = scene scene.changed.connect(self.overlayChanged) self.update() def overlayScene(self): return self.m_overlayScene def paintEvent(self, ev): super(OverlaidGraphicsView, self).paintEvent(ev) if self.m_overlayScene is not None: self.paintOverlay() def paintOverlay(self): p = QPainter(self.viewport()) p.setRenderHints(self.renderHints()) sourceRect = self.scene().sceneRect() targetRect = self.mapFromScene(sourceRect).boundingRect() self.m_overlayScene.render(p, QRectF(targetRect), QRectF(sourceRect), QtCore.Qt.IgnoreAspectRatio) @pyqtSlot() def overlayChanged(self): self.update()
def mouseMoveEvent(self, event): QGraphicsScene.mouseMoveEvent(self, event) self.mousePos = event.scenePos() if not (any((key.pressed for key in self.piano_keys))): m_pos = event.scenePos() if self.insert_mode and self.place_ghost: #placing a note m_width = self.ghost_rect.x() + self.ghost_rect_orig_width if m_pos.x() > m_width: m_new_x = self.snap(m_pos.x()) self.ghost_rect.setRight(m_new_x) self.ghost_note.setRect(self.ghost_rect) #self.adjust_note_vel(event) else: m_pos = self.enforce_bounds(m_pos) if self.insert_mode: #ghostnote follows mouse around (m_new_x, m_new_y) = self.snap(m_pos.x(), m_pos.y()) self.ghost_rect.moveTo(m_new_x, m_new_y) try: self.ghost_note.setRect(self.ghost_rect) except RuntimeError: self.ghost_note = None self.makeGhostNote(m_new_x, m_new_y) elif self.marquee_select: marquee_orig_pos = event.buttonDownScenePos(Qt.LeftButton) if marquee_orig_pos.x() < m_pos.x() and marquee_orig_pos.y() < m_pos.y(): self.marquee_rect.setBottomRight(m_pos) elif marquee_orig_pos.x() < m_pos.x() and marquee_orig_pos.y() > m_pos.y(): self.marquee_rect.setTopRight(m_pos) elif marquee_orig_pos.x() > m_pos.x() and marquee_orig_pos.y() < m_pos.y(): self.marquee_rect.setBottomLeft(m_pos) elif marquee_orig_pos.x() > m_pos.x() and marquee_orig_pos.y() > m_pos.y(): self.marquee_rect.setTopLeft(m_pos) self.marquee.setRect(self.marquee_rect) self.selected_notes = [] for item in self.collidingItems(self.marquee): if item in self.notes: self.selected_notes.append(item) for note in self.notes: if note in self.selected_notes: note.setSelected(True) else: note.setSelected(False) elif self.velocity_mode: if Qt.LeftButton == event.buttons(): for note in self.selected_notes: note.updateVelocity(event) elif not self.marquee_select: #move selected if Qt.LeftButton == event.buttons(): x = y = False if any(note.back.stretch for note in self.selected_notes): x = True elif any(note.front.stretch for note in self.selected_notes): y = True for note in self.selected_notes: note.back.stretch = x note.front.stretch = y note.moveEvent(event)
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): QGraphicsScene.__init__(self) self.jatkoPiste = QPointF(1,1) self.jatkoKulma = 0.0 self.valittu = None self.valittuVanha = None
def __init__(self, time_sig = '4/4', num_measures = 4, quantize_val = '1/8'): QGraphicsScene.__init__(self) self.setBackgroundBrush(QColor(50, 50, 50)) self.mousePos = QPointF() self.notes = [] self.selected_notes = [] self.piano_keys = [] self.marquee_select = False self.insert_mode = False self.velocity_mode = False self.place_ghost = False self.ghost_note = None self.default_ghost_vel = 100 self.ghost_vel = self.default_ghost_vel ## dimensions self.padding = 2 ## piano dimensions self.note_height = 10 self.start_octave = -2 self.end_octave = 8 self.notes_in_octave = 12 self.total_notes = (self.end_octave - self.start_octave) \ * self.notes_in_octave + 1 self.piano_height = self.note_height * self.total_notes self.octave_height = self.notes_in_octave * self.note_height self.piano_width = 34 ## height self.header_height = 20 self.total_height = self.piano_height - self.note_height + self.header_height #not sure why note_height is subtracted ## width self.full_note_width = 250 # i.e. a 4/4 note self.snap_value = None self.quantize_val = quantize_val ### dummy vars that will be changed self.time_sig = 0 self.measure_width = 0 self.num_measures = 0 self.max_note_length = 0 self.grid_width = 0 self.value_width = 0 self.grid_div = 0 self.piano = None self.header = None self.play_head = None self.setTimeSig(time_sig) self.setMeasures(num_measures) self.setGridDiv() self.default_length = 1. / self.grid_div
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()
def __init__(self, _, lang, areaType): QGraphicsScene.__init__(self) self.language = lang self.areaType = areaType self.first = True self.areas = [] self.ocrImage = None self.isModified = None
def drawBackground(self, painter, rect): if self.backgroundBrush().style() == Qt.NoBrush: # Fill the fbo with the transparent color as there won't # be a window or graphics item drawing a previous background. painter.save() painter.setCompositionMode(QPainter.CompositionMode_Source) painter.fillRect(rect, Qt.transparent) painter.restore() else: QGraphicsScene.drawBackground(painter, rect)
def imgInit(self): self.inputScene = QGraphicsScene() self.inputGraphicsView.setScene(self.inputScene) self.inputGraphicsView.resizeEvent = self.inputGraphicsViewResized self.outputScene = QGraphicsScene() self.outputGraphicsView.setScene(self.outputScene) self.outputGraphicsView.resizeEvent = self.outputGraphicsViewResized self.fgbg = None
class cardTableWidget(QWidget): server_receivedSig = pyqtSignal(str) """ main widget for handling the card table """ def __init__(self, parent=None): super(QWidget, self).__init__(parent) # init is done in start_server.py def initUI(self, path_to_options): """ initialize the view-scene graphic environment """ self.scene = QGraphicsScene() #self.scene.setSceneRect(0, 0, 640, 480) self.view = QGraphicsViewExtend(self.scene) self.view.setSceneRect(QRectF(self.view.viewport().rect())) self.view.setSceneRect(QRectF(0, 0, 850, 900)) self.view.setRenderHint(QPainter.Antialiasing) layout = QGridLayout() layout.addWidget(self.view) self.setLayout(layout) self.setBackgroundColor(QColor('green')) # special properties self.svgCardsPath = "../cards" self.cardsGraphItems = [] #holds all the cards items self.defInsertionPos = QPointF(0, 0) self.defAngle = 0 self.defScale = 0.5 self.deckBackSVG = 'back_1' self.numOfPlayers = 4 self.playersHandsPos = [(75, 50, 0), (210, 50, 180), (680, 50, 0), (210, 385, 0)] #(x,y,angle) self.defHandSpacing = 24 self.midCards = [] self.options_file_path = path_to_options # Card fields pen = QPen() brush = QBrush() self.scene.addRect(QRectF(200, 230, 100, 80), pen, brush) self.scene.addRect(QRectF(200 + 120, 230, 100, 80), pen, brush) self.scene.addRect(QRectF(200 + 120 * 2, 230, 100, 80), pen, brush) self.scene.addRect(QRectF(200 + 120 * 3, 230, 100, 80), pen, brush) # Player Names self.player1_label = self.addPlayerLabel(425, 350, "Player 1") self.player2_label = self.addPlayerLabel(0, 240, "Player 2") self.player3_label = self.addPlayerLabel(425, 20, "Player 3") self.player4_label = self.addPlayerLabel(782, 240, "Player 4") self.card1_label = self.addPlayerLabel(200, 210, "") self.card2_label = self.addPlayerLabel(200 + 120, 210, "") self.card3_label = self.addPlayerLabel(200 + 120 * 2, 210, "") self.card4_label = self.addPlayerLabel(200 + 120 * 3, 210, "") self.card_label_l = [ self.card1_label, self.card2_label, self.card3_label, self.card4_label ] self.card_label_pla = [ self.player1_label, self.player2_label, self.player3_label, self.player4_label ] self.play_1_state = self.addPlayerLabel(200, 250, "") self.play_2_state = self.addPlayerLabel(200 + 120, 250, "") self.play_3_state = self.addPlayerLabel(200 + 120 * 2, 250, "") self.play_4_state = self.addPlayerLabel(200 + 120 * 3, 250, "") self.game_indicator = self.addPlayerLabel(650, 5, "Game: ") self.mode_label = self.addPlayerLabel(150, 5, "Mode: ") playbtn = QPushButton('Start', self) playbtn.resize(50, 32) playbtn.move(10, 10) playbtn.clicked.connect(self.start_clicked) options = QPushButton('Options', self) options.resize(80, 32) options.move(65, 10) options.clicked.connect(self.options_clicked) nextRound = QPushButton('nextRound', self) nextRound.resize(80, 32) nextRound.move(150, 10) nextRound.setVisible(False) nextRound.clicked.connect(self.nextRound_clicked) self.scene.addWidget(playbtn) self.scene.addWidget(nextRound) self.scene.addWidget(options) self.my_game = None # Testing tree: self.my_tree = None # Storing game_play self.game_play = {} self.corrString = "" # emit signal: self.server_receivedSig.connect(self.parseClient) ### Client stuff: self.clientTimer = QTimer(self) self.tcpSocket = None self.games_played = 0 self.reset_client() self.server_thread = None def reset_client(self): # used also in "Restart" self.removeAll() self.deckBackSVG = 'back_1' # in shifting phase soll man karten sehen! self.clientCards = None self.ClientName = "" self.dealAgain = False self.GameOver = False self.gotCards = 0 self.rounds_played = 1 self.nuSend = 0 self.nuReceived = 0 self.wantPlay = "" self.games_played += 1 def options_clicked(self): ''' Read in json, modify, write it read it in as dict again! ''' with open(self.options_file_path) as json_file: test = json.load(json_file) txt = prettyjson(test) text = easygui.textbox("Contents of file:\t" + self.options_file_path, "Adjust your options", txt) if text is not None: # Cancel pressed (None case) dict = (json.loads(text)) with open(self.options_file_path, 'w') as outfile: json.dump(dict, outfile) def nextRound_clicked(self): ''' Reset the game with the same options as before! ''' print("This option is not available!") #########################CLIENT ################################# #########################CLIENT ################################# #########################CLIENT ################################# def convertCardsArray(self, stringArray): cards = [] for ele in ast.literal_eval(stringArray): cards.append(self.convertCardString2Card(ele)) return cards def convertCardString2Card(self, cardmsg): tmp = cardmsg.split("of") value = int(tmp[0].replace("'", "")) color = str(tmp[1].replace("of", "").replace(" ", "").replace("'", "")) return card(color, value) def send_msgClient(self, msg): self.tcpSocket.waitForBytesWritten( 100) # waitForBytesWritten waitForConnected self.tcpSocket.write(bytes(str(msg), encoding='ascii')) def displayErrorClient(self, socketError): self.changePlayerName( self.mode_label, "Wait for server your ip: " + str(self.options["open_ip"])) if socketError == QAbstractSocket.RemoteHostClosedError: pass else: print("Server does not seem to be open or wrong open_ip!") if not self.clientTimer.isActive(): print("The following error occurred: %s." % self.tcpSocket.errorString()) self.clientTimer.timeout.connect(self.clientReconnectTimer) self.clientTimer.start(2000) def applyOneState(self, state): # only for single message res = [] for i in state: res.append(ast.literal_eval(i)) try: player_idx, my_card, shifting, nu_shift_cards, on_table_cards, endround, gameOver = int( res[0]), self.convertCardString2Card(res[1]), str(res[2]), int( res[3]), int(res[4]), res[6], res[7] except: print("Could not parse ERRROR") return print("apply Board state:", res, self.gotCards) #Do not play if card is already deleted or in the mid item = self.findGraphicsCardItem_(my_card) if item is None or item.isPlayed: return if "False" in shifting: shifting = False else: shifting = True if not shifting: on_table_cards = len(self.midCards) if "True" in str(gameOver): self.GameOver = True # If cards are dealt again do not apply shifted states again (they still might be contained in board state) if shifting and self.gotCards >= 2: return self.playCardClient(item, player_idx, on_table_cards, player_idx, shifting, nu_shift_cards) def applyBoardState(self, msg): if len(msg) == 0: return for i in msg: self.applyOneState(i) @pyqtSlot(str) def parseClient(self, inMsg): self.nuReceived += 1 #self.clientTimer.stop() print("\nReceived::", inMsg) name, command, msg, tmp, outMsg = "", "", "", "", "" try: tmp = inMsg.split(";") except Exception as e: print(e) outMsg = name + ";" + "Error;" + "Server could not parse Message split fails" if len(tmp) == 3: name, command, msg = tmp[0], tmp[1], tmp[2] else: print("Not enough ;") outMsg = name + ";" + "Error;" + "Server could not parse Message not enough args found" + str( len(tmp)) + " should be 3" #### TODO #### Achtung wenn gleiche Nachricht 2 mal kommt soll nichts gemacht werden #### Warte bis timer fertig bevor neuen starten!!! if command == "InitClientSuccess" or command == "WaitUntilConnected": self.changePlayerName(self.mode_label, "Mode: Shift, WAIT FOR OTHERS") self.send2Server("GetCards", "Server give me my cards and the game state", once=False) elif command == "GetCardsSuccess": self.gotCards += 1 # Wende nur zwei mal an!!! if self.gotCards <= 2: try: ttmp = msg.split("--") names, typee, cards, deck = ttmp[0], ttmp[1], ttmp[ 2:6], ttmp[6] except: print("Could not parse ERRROR") return self.options["names"] = ast.literal_eval(names) self.options["type"] = ast.literal_eval(typee) self.setNames() for i, c in enumerate(cards): if self.options["names"][i] == self.clientName: self.clientCards = self.convertCardsArray(c) self.deal_cards(self.convertCardsArray(c), i, fdown=False) else: self.deal_cards(self.convertCardsArray(c), i, fdown=True) self.deckBackSVG = str(ttmp[6]) self.send2Server("WantPlay", str(self.wantPlay), once=False) elif command == "WrongCard": self.applyBoardState(ast.literal_eval(msg)) if self.dealAgain: self.send2Server("GetCards", str(self.wantPlay), once=False) self.dealAgain = False elif self.GameOver: self.send2Server("GameOver", "game is over", once=False) self.GameOver = False else: ########### random card for testing: # item = None # if len(self.clientCards)>0: # while item is None: # number = random.randrange(len(self.clientCards)) # my_card = self.clientCards[number] # item = self.findGraphicsCardItem_(my_card) # self.wantPlay = my_card ######### self.send2Server("WantPlay", str(self.wantPlay), once=False) elif command == "PlayedCard": self.wantPlay = "" try: ttmp = msg.split("--") player_idx, card, shifting, nu_shift_cards, on_table_cards, endround, gameover = int( ttmp[0]), self.convertCardString2Card( ttmp[1]), ast.literal_eval(ttmp[2]), int(ttmp[3]), int( ttmp[4]), ttmp[6], ttmp[7] except: print("Could not parse ERRROR") return #Do not play if card is already deleted or in the mid item = self.findGraphicsCardItem_(card) if item is None or item.isPlayed: print("ERROR CARD NOT FOUND!!!! \n\n") self.send2Server("WantPlay", str(self.wantPlay), once=False) return if not shifting: on_table_cards = len(self.midCards) try: self.playCardClient(item, player_idx, on_table_cards, player_idx, shifting, nu_shift_cards) except: self.send2Server("WantPlay", str(self.wantPlay), once=False) return if self.dealAgain: self.send2Server("GetCards", str(self.wantPlay), once=False) self.dealAgain = False elif "True" in gameover: self.send2Server("GameOver", "game is over", once=False) else: self.send2Server("WantPlay", str(self.wantPlay), once=False) elif command == "GameOver": # do this only once: if not self.dealAgain: self.removeAll() self.dealAgain = True try: ttmp = msg.split("--") offhandCards, rewards, total_rewards = ttmp[0], ttmp[ 1], ttmp[2] except Exception as e: print("Could not parse ERRROR", e) return offhandCards = ast.literal_eval(offhandCards) rewards = ast.literal_eval(rewards) total_rewards = ast.literal_eval(total_rewards) for i in range(len(offhandCards)): self.showResultClient( i, str(rewards[i]), str(total_rewards[i]), self.convertCardsArray(str(offhandCards[i]))) print("CLIENT GAME OVERRRRR") self.send2Server("Restart", "Server Please Restart me", once=False) elif command == "Restart": print("Inside client restart and reset now") self.reset_client() #about to restart..... time.sleep(self.options["sleepTime"] * 4) # wait some time before starting new! self.send2Server("GetCards", "Server give me my cards for the new game", once=False) def receivedMsgClient(self): inMsg = str(self.tcpSocket.readAll(), encoding='utf8') if ";Ende" in inMsg: a = (inMsg.split(";Ende")) self.corrString += a[0] self.server_receivedSig.emit(self.corrString) self.corrString = "" else: self.corrString += inMsg def sendServer(self, msg): # wait for answer here: https://stackoverflow.com/questions/23265609/persistent-connection-in-twisted # see also this https://stackoverflow.com/questions/23265609/persistent-connection-in-twisted (send to multiple....) print(">>>Client sends:", msg) msg = msg.encode("utf8") self.tcpSocket.write(msg) self.nuSend += 1 self.tcpSocket.waitForBytesWritten() def send2Server(self, cmd, msg, once=True, delimiter=";"): msg = self.clientName + delimiter + cmd + delimiter + msg + delimiter + "Ende" if once: self.sendServer(msg) else: # Send after a while to minimize the traffic QTimer.singleShot(100, lambda: self.sendServer(msg)) def openClient(self): self.tcpSocket = QTcpSocket(self) print("I client connect now with:", self.options["open_ip"]) self.changePlayerName( self.mode_label, "Client Connect with: " + str(self.options["open_ip"])) self.tcpSocket.connectToHost(self.options["open_ip"], 8000, QIODevice.ReadWrite) self.tcpSocket.readyRead.connect(self.receivedMsgClient) self.tcpSocket.error.connect(self.displayErrorClient) # send start message: connected = self.tcpSocket.waitForConnected(1000) if connected: self.clientTimer.stop() self.send2Server("InitClient", "Server please init me with my name") else: print( "Not connected, Server not open?, open_ip wrong? Try to reconnect in 2sec" ) def is_valid_ipv4(self, ip): """Validates IPv4 addresses. """ pattern = re.compile( r""" ^ (?: # Dotted variants: (?: # Decimal 1-255 (no leading 0's) [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2} | 0x0*[0-9a-f]{1,2} # Hexadecimal 0x0 - 0xFF (possible leading 0's) | 0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's) ) (?: # Repeat 0-3 times, separated by a dot \. (?: [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2} | 0x0*[0-9a-f]{1,2} | 0+[1-3]?[0-7]{0,2} ) ){0,3} | 0x0*[0-9a-f]{1,8} # Hexadecimal notation, 0x0 - 0xffffffff | 0+[0-3]?[0-7]{0,10} # Octal notation, 0 - 037777777777 | # Decimal notation, 1-4294967295: 429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}| 42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}| 4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8} ) $ """, re.VERBOSE | re.IGNORECASE) return pattern.match(ip) is not None #########################CLIENT ################################# #########################CLIENT ################################# #########################CLIENT ################################# #########################SERVER ################################# #########################SERVER ################################# #########################SERVER ################################# def start_server(self): import server def getIP(self): hostname = socket.gethostname() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] return ip_address, hostname def getNuClients(self, list): u = 0 for i in list: if "Client" in i: u += 1 return u def findFirstClient(self, list): for j, i in enumerate(list): if "Client" in i: return j return 0 #########################SERVER ################################# #########################SERVER ################################# #########################SERVER ################################# def start_clicked(self): #1. Load Options with open(self.options_file_path) as json_file: self.options = json.load(json_file) #2. Create Game: print("Online_type:", self.options["online_type"]) if "Client" in self.options["online_type"]: self.changePlayerName(self.mode_label, "Mode: Client") valid_ip = self.is_valid_ipv4(self.options["open_ip"]) if len(self.options["names"]) > 1 or len( self.options["type"]) > 1 or (not valid_ip) or ( "Client" not in self.options["type"]): print( "Error use only one unique name in options. names: ['YourName']" ) print( "Error use only one type in options. type: ['Client']" ) print( "Error use only IPV4 as open_ip in options. open_ip: 172.20.80.10" ) return self.clientName = self.options["names"][0] self.openClient() elif "Server" in self.options["online_type"]: self.changePlayerName(self.mode_label, "Mode: Server") #1. Open Server in seperate Thread page = str( urllib.request.urlopen("http://checkip.dyndns.org/").read()) print(">>>THIS IS SERVER OPEN IP ADDRESS:", re.search(r'.*?<body>(.*).*?</body>', page).group(1)) print(">>>LOCAL IP OF THIS PC IN LAN :", self.getIP()) self.server_thread = threading.Thread(target=self.start_server, ) self.server_thread.start() #2. Open Client self.options["online_type"] = "Client" # give it the name of the first found Client self.clientName = self.options["names"][self.findFirstClient( self.options["type"])] self.openClient() elif "Local" in self.options["online_type"]: clients = self.getNuClients(self.options["type"]) if clients != 1: self.changePlayerName( self.mode_label, "Error use only 1 client \"type\": [\"Client\", \"RL0\", \"RL0\", \"RL1\"],\" " ) time.sleep(1) self.changePlayerName(self.mode_label, "Please close app and restart it!") self.changePlayerName(self.mode_label, "Mode: LocalHost - Play against other ai's") self.view.viewport().repaint() time.sleep(1) ip, host = self.getIP() self.changePlayerName(self.mode_label, str(host) + " " + " IP:" + str(ip)) #1. Open Server in seperate Thread self.options["open_ip"] = ip self.server_thread = threading.Thread(target=self.start_server, ) self.server_thread.start() # #2. Open Client self.options["online_type"] = "Client" # give it the name of the first found Client self.clientName = self.options["names"][self.findFirstClient( self.options["type"])] self.openClient() else: self.changePlayerName( self.mode_label, "Error: choose Local, Server or Client as online type") def clientReconnectTimer(self): self.openClient() def getHighlight(self, playeridx): try: if playeridx == self.my_game.active_player: return 1 else: return 0 except: return 0 def setNames(self): self.changePlayerName(self.player1_label, self.options["names"][0] + " (" + self.options["type"][0] + ")", highlight=self.getHighlight(0)) self.changePlayerName(self.player2_label, self.options["names"][1] + " (" + self.options["type"][1] + ")", highlight=self.getHighlight(1)) self.changePlayerName(self.player3_label, self.options["names"][2] + " (" + self.options["type"][2] + ")", highlight=self.getHighlight(2)) self.changePlayerName(self.player4_label, self.options["names"][3] + " (" + self.options["type"][3] + ")", highlight=self.getHighlight(3)) def showResultClient(self, i, reward, total_reward, offhandCards): labels1 = [ self.card1_label, self.card2_label, self.card3_label, self.card4_label ] labels2 = [ self.play_1_state, self.play_2_state, self.play_3_state, self.play_4_state ] label1 = labels1[i] label2 = labels2[i] self.changePlayerName(label1, self.options["names"][i] + " (" + self.options["type"][i] + ")", highlight=0) self.changePlayerName(label2, reward + " [" + total_reward + "]", highlight=0) self.deal_cards(offhandCards, i) self.view.viewport().repaint() def getNextPlayer(self, currPlayer): if currPlayer < len(self.options["names"]) - 1: return currPlayer + 1 else: return 0 def getPreviousPlay(self, input_number, nuPlayers=4): if input_number == 0: prev_player = nuPlayers - 1 else: prev_player = input_number - 1 return prev_player def getInColorOfCards(self, cards): # returns the leading color of the on_table_cards # if only joker are played None is returned for i, card in enumerate(cards): if card is not None: if card.value < 15: return card.color return None def getWinnerForCards(self, cards, active_player, nu_players=4): # Not this function is used at the client side! highest_value = 0 winning_card = cards[0] incolor = self.getInColorOfCards(cards) on_table_win_idx = 0 if incolor is not None: for i, card in enumerate(cards): # Note 15 is a Jocker if card is not None and (card.value > highest_value and card.color == incolor and card.value < 15): highest_value = card.value winning_card = card on_table_win_idx = i player_win_idx = active_player for i in range(nu_players - on_table_win_idx - 1): player_win_idx = self.getPreviousPlay(player_win_idx, nuPlayers=nu_players) return winning_card, on_table_win_idx, player_win_idx def playCardClient(self, graphic_card_item, current_player, label_idx, player_name, shifting, shifted_cards): print(graphic_card_item, current_player, label_idx, player_name, shifting, shifted_cards) self.setNames() if shifting: card_label = self.card_label_l[graphic_card_item.player] self.changePlayerName( card_label, self.options["names"][graphic_card_item.player], highlight=0) self.view.viewport().repaint() shift_round = int(shifted_cards / 4) graphic_card_item.setPos( card_label.pos().x(), card_label.pos().y() + 20 + shift_round * 50) else: card_label = self.card_label_l[label_idx] self.changePlayerName( card_label, self.options["names"][graphic_card_item.player], highlight=0) self.view.viewport().repaint() graphic_card_item = self.changeCard(graphic_card_item, faceDown=False) graphic_card_item.setPos(card_label.pos().x(), card_label.pos().y() + 20) self.midCards.append(graphic_card_item) self.view.viewport().repaint() graphic_card_item.isPlayed = True if len(self.midCards) == 8: # remove all Client Cards (are dealt again!) print("Remove all cards now") self.removeAll() self.removeMidNames() self.midCards = [] self.dealAgain = True self.changePlayerName(self.mode_label, "Mode: Play") if len(self.midCards) == 4 and shifted_cards > 10: print("Remove Mid Cards now") ttmp = self.midCards time.sleep(self.options["sleepTime"]) for i in self.midCards: self.removeCard(i) self.midCards = [] self.removeMidNames() # TODO mark next player (may set trick winner etc.) lll = [] for i in ttmp: lll.append(i.card) winning_card, on_table_win_idx, player_win_idx = self.getWinnerForCards( lll, int(current_player), nu_players=4) self.changePlayerName(self.card_label_pla[player_win_idx], self.options["names"][player_win_idx], highlight=1) self.changePlayerName( self.game_indicator, "Game: " + str(self.games_played) + " Round: " + str(self.rounds_played)) self.rounds_played += 1 self.view.viewport().repaint() else: # mark next player: self.changePlayerName( self.card_label_pla[self.getNextPlayer(current_player)], self.options["names"][self.getNextPlayer(current_player)], highlight=1) self.view.viewport().repaint() # TODO Game indicator round etc. return 1 # card played! def getGraphicCard(self, label_idx, player_name, graphic_card_item): self.setNames() if self.my_game.shifting_phase: card_label = self.card_label_l[self.my_game.active_player] self.changePlayerName(card_label, player_name, highlight=0) self.view.viewport().repaint() shift_round = int(self.my_game.shifted_cards / self.my_game.nu_players) graphic_card_item.setPos( card_label.pos().x(), card_label.pos().y() + 20 + shift_round * 50) else: card_label = self.card_label_l[label_idx] self.changePlayerName(card_label, player_name, highlight=0) self.view.viewport().repaint() graphic_card_item = self.changeCard(graphic_card_item, faceDown=False) graphic_card_item.setPos(card_label.pos().x(), card_label.pos().y() + 20) return graphic_card_item def findGraphicsCardItem_(self, my_card): for i in self.getCardsList(): try: if (i.card == my_card) or ((i.card.value == my_card.value) and (i.card.color == my_card.color)): return i except: pass return None def findGraphicsCardItem(self, action_idx, player_idx): try: card_to_play = self.my_game.players[player_idx].hand[action_idx] except: print("Error no card left anymore!") return None for i in self.getCardsList(): if i.card == card_to_play: return i def removeMidNames(self): self.card1_label.setPlainText("") self.card2_label.setPlainText("") self.card3_label.setPlainText("") self.card4_label.setPlainText("") def addPlayerLabel(self, x_pos, y_pos, name, highlight=0, font=QFont.Bold): item = self.scene.addText(name, QFont('Arial Black', 11, font)) if highlight: item.setDefaultTextColor(Qt.yellow) item.setPos(x_pos, y_pos) return item def changePlayerName(self, text_item, name, highlight=0): text_item.setPlainText(name) if highlight: text_item.setDefaultTextColor(Qt.yellow) else: text_item.setDefaultTextColor(Qt.black) def mousePressEvent(self, event): try: # check if item is a CardGraphicsItem p = event.pos() p -= QPoint( 10, 10) #correction to mouse click. not sure why this happen itemAt = self.view.itemAt(p) if isinstance(itemAt, CardGraphicsItem): self.cardPressed(itemAt) except Exception as e: print(e) def checkCard(self, cardStr): for i in self.clientCards: if str(cardStr) in str(i): return True return False def cardPressed(self, card): #remove these lines if Problems.... core dumped occurs... for i in self.clientCards: item = self.findGraphicsCardItem_(i) if item is not None and not item.isPlayed: item.setScale(self.defScale) card.setScale(self.defScale + 0.08) if "Client" in self.options["online_type"]: # check if it is your card! if (self.checkCard(card.card)): self.wantPlay = str(card.card) else: print(self.clientName + " This is not your card!") self.changePlayerName(self.mode_label, "Not your card!") if self.gotCards <= 1: self.changePlayerName( self.mode_label, "Mode: Shift " + str(self.wantPlay).replace("of", "")) else: self.changePlayerName( self.mode_label, "Mode: Play " + str(self.wantPlay).replace("of", "")) else: print("other not allowed currently!!!") print(eeee) def setBackgroundColor(self, color): """ add background color """ brush = QBrush(color) self.scene.setBackgroundBrush(brush) self.scene.backgroundBrush() def cardSvgFile(self, name): """ get card svg file from card name name = 'c_4','d_Q',... for jokers name = 'j_r' or 'j_b' for back name = 'back_1', 'back_2', ... """ fn = os.path.join(self.svgCardsPath, name + ".svg") # TODO change to SVG return fn def addCard(self, my_card, player=0, faceDown=False): """ adds CardGraphicsItem graphics to board. also updates the total cards list """ # svg file of the card graphics if faceDown: svgFile = self.cardSvgFile(self.deckBackSVG) else: svgFile = self.cardSvgFile(str(my_card.color) + str(my_card.value)) # create CardGraphicsItem instance ind = len(self.getCardsList()) + 1 tmp = CardGraphicsItem(my_card, ind, svgFile, player, faceDown) tmp.setScale(self.defScale) tmp.setZValue(ind) # set ZValue as index (last in is up) # self.cardsGraphItems.append(tmp) self.scene.addItem(tmp) # sanity check #print("num of cards=" + str(len(self.cardsList))) def removeAll(self): try: for i in (self.getCardsList()): self.scene.removeItem(i) except Exception as e: print("Exception:", e) def removeCard(self, card): """ removes CardGraphicsItem graphics from board """ self.scene.removeItem(card) # TODO - UPDATE THIS FUNCTION def changeCard(self, graphicsCardElement, faceDown=False): """ replace CardGraphicsItem keeps same index and ZValue ! """ nameToAdd = str(graphicsCardElement.card.color) + str( graphicsCardElement.card.value) zValueTmp = graphicsCardElement.zValue() position = graphicsCardElement.pos() angle = graphicsCardElement.rotation() scale = graphicsCardElement.scale() player = graphicsCardElement.player self.scene.removeItem(graphicsCardElement) # svg file of the card graphics if faceDown: svgFile = self.cardSvgFile(self.deckBackSVG) else: svgFile = self.cardSvgFile(nameToAdd) ind = int(zValueTmp) tmp = CardGraphicsItem( card(graphicsCardElement.card.color, graphicsCardElement.card.value), ind, svgFile, player, faceDown) tmp.setScale(self.defScale) tmp.setZValue(ind) # set ZValue as index (last in is up) self.scene.addItem(tmp) return tmp def getCardsList(self): """ returns and prints all CardGraphicsItem in scene (disregard other graphics items) """ itemsOut = [] #print("Cards List:") for item in self.scene.items(): if isinstance(item, CardGraphicsItem): itemsOut.append(item) #print("Ind=%3d | Name=%4s | Player=%d | faceDown=%r " % \ # (item.ind, item.name, item.player, item.faceDown) ) #print("Total cards num = " + str(len(itemsOut))) return itemsOut def deal_cards(self, cards, playerNum, fdown=False): n = 1 c2 = 0 dx = [0, self.defHandSpacing, 0, self.defHandSpacing] dy = [self.defHandSpacing, 0, self.defHandSpacing, 0] x, y, ang = self.playersHandsPos[playerNum - 1] for card in cards: self.addCard(card, player=playerNum, faceDown=fdown) #add the item to the scene self.getCardsList()[0].setPos( x + dx[playerNum - 1] * c2, y + dy[playerNum - 1] * c2) #change the position n += 1 c2 += 1
class MainWindow(QMainWindow): """ 主窗口类 """ def __init__(self): super().__init__() self.item_cnt = 0 # 使用QListWidget来记录已有的图元,并用于选择图元。注:这是图元选择的简单实现方法,更好的实现是在画布中直接用鼠标选择图元 self.list_widget = QListWidget(self) self.list_widget.setMinimumWidth(200) # 使用QGraphicsView作为画布 self.scene = QGraphicsScene(self) self.scene.setSceneRect(0, 0, 600, 600) self.canvas_widget = MyCanvas(self.scene, self) self.canvas_widget.setFixedSize(600, 600) self.canvas_widget.main_window = self self.canvas_widget.list_widget = self.list_widget # 设置菜单栏 menubar = self.menuBar() file_menu = menubar.addMenu('文件') set_pen_act = file_menu.addAction('设置画笔') reset_canvas_act = file_menu.addAction('重置画布') exit_act = file_menu.addAction('退出') draw_menu = menubar.addMenu('绘制') line_menu = draw_menu.addMenu('线段') line_naive_act = line_menu.addAction('Naive') line_dda_act = line_menu.addAction('DDA') line_bresenham_act = line_menu.addAction('Bresenham') polygon_menu = draw_menu.addMenu('多边形') polygon_dda_act = polygon_menu.addAction('DDA') polygon_bresenham_act = polygon_menu.addAction('Bresenham') ellipse_act = draw_menu.addAction('椭圆') curve_menu = draw_menu.addMenu('曲线') curve_bezier_act = curve_menu.addAction('Bezier') curve_b_spline_act = curve_menu.addAction('B-spline') edit_menu = menubar.addMenu('编辑') translate_act = edit_menu.addAction('平移') rotate_act = edit_menu.addAction('旋转') scale_act = edit_menu.addAction('缩放') clip_menu = edit_menu.addMenu('裁剪') clip_cohen_sutherland_act = clip_menu.addAction('Cohen-Sutherland') clip_liang_barsky_act = clip_menu.addAction('Liang-Barsky') # 连接信号和槽函数 exit_act.triggered.connect(qApp.quit) line_naive_act.triggered.connect(self.line_naive_action) self.list_widget.currentTextChanged.connect( self.canvas_widget.selection_changed) # 设置主窗口的布局 self.hbox_layout = QHBoxLayout() self.hbox_layout.addWidget(self.canvas_widget) self.hbox_layout.addWidget(self.list_widget, stretch=1) self.central_widget = QWidget() self.central_widget.setLayout(self.hbox_layout) self.setCentralWidget(self.central_widget) self.statusBar().showMessage('空闲') self.resize(600, 600) self.setWindowTitle('CG Demo') def get_id(self): _id = str(self.item_cnt) self.item_cnt += 1 return _id def line_naive_action(self): self.canvas_widget.start_draw_line('Naive', self.get_id()) self.statusBar().showMessage('Naive算法绘制线段') self.list_widget.clearSelection() self.canvas_widget.clear_selection()
def _finishViewMatrixChange(self): self.scene2data, isInvertible = self.data2scene.inverted() self._setSceneRect() self._tiling.data2scene = self.data2scene self._tileProvider._onSizeChanged() QGraphicsScene.invalidate(self, self.sceneRect())
def __init__(self, posModel, along, preemptive_fetch_number=5, parent=None, name="Unnamed Scene", swapped_default=False): """ * preemptive_fetch_number -- number of prefetched slices; 0 turns the feature off * swapped_default -- whether axes should be swapped by default. """ QGraphicsScene.__init__(self, parent=parent) self._along = along self._posModel = posModel # QGraphicsItems can change this if they are in a state that should temporarily forbid brushing # (For example, when the slice intersection marker is in 'draggable' state.) self.allow_brushing = True self._dataShape = (0, 0) self._dataRectItem = None # A QGraphicsRectItem (or None) self._offsetX = 0 self._offsetY = 0 self.name = name self._tileWidth = 256 self._stackedImageSources = StackedImageSources(LayerStackModel()) self._showTileOutlines = False # FIXME: We don't show the red 'progress pies' because they look terrible. # If we could fix their timing, maybe it would be worth it. self._showTileProgress = False self._tileProvider = None self._dirtyIndicator = None self._prefetching_enabled = False self._swappedDefault = swapped_default self.reset() # BowWave preemptive caching self.setPreemptiveFetchNumber(preemptive_fetch_number) self._course = (1, 1) # (along, pos or neg direction) self._time = self._posModel.time self._channel = self._posModel.channel self._posModel.timeChanged.connect(self._onTimeChanged) self._posModel.channelChanged.connect(self._onChannelChanged) self._posModel.slicingPositionChanged.connect( self._onSlicingPositionChanged) self._allTilesCompleteEvent = threading.Event() self.dirty = False # We manually keep track of the tile-wise QGraphicsItems that # we've added to the scene in this dict, otherwise we would need # to use O(N) lookups for every tile by calling QGraphicsScene.items() self.tile_graphicsitems = defaultdict( set) # [Tile.id] -> set(QGraphicsItems) self.last_drag_pos = None # See mouseMoveEvent()
class QtImageViewer(QGraphicsView): """ PyQt image viewer widget w QGraphicsView handles a scene composed by an image plus shapes (rectangles, polygons, blobs). The input image (it must be a QImage) is internally converted into a QPixmap. """ viewUpdated = pyqtSignal(QRectF) #region visible in percentage viewHasChanged = pyqtSignal(float, float, float) #posx, posy, posz def __init__(self): QGraphicsView.__init__(self) self.setStyleSheet("background-color: rgb(40,40,40)") self.scene = QGraphicsScene() self.setScene(self.scene) # Store a local handle to the scene's current image pixmap. self.pixmapitem = QGraphicsPixmapItem() self.pixmapitem.setZValue(0) self.scene.addItem(self.pixmapitem) self.img_map = None # current image size self.imgwidth = 0 self.imgheight = 0 # Image aspect ratio mode. self.aspectRatioMode = Qt.KeepAspectRatio # Set scrollbar self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.verticalScrollBar().valueChanged.connect(self.viewChanged) self.horizontalScrollBar().valueChanged.connect(self.viewChanged) # Panning is enabled if and only if the image is greater than the viewport. self.panEnabled = True self.zoomEnabled = True # zoom is always active self.zoom_factor = 1.0 self.ZOOM_FACTOR_MIN = 0.5 self.ZOOM_FACTOR_MAX = 16.0 self.px_to_mm = 1.0 # transparency self.opacity = 1.0 MIN_SIZE = 250 self.pixmap = QPixmap(MIN_SIZE, MIN_SIZE) self.overlay_image = QImage(1, 1, QImage.Format_ARGB32) self.viewport().setMinimumWidth(MIN_SIZE) self.viewport().setMinimumHeight(MIN_SIZE) self.resetTransform() self.setMouseTracking(True) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) #self.setContextMenuPolicy(Qt.CustomContextMenu) def setImg(self, img, zoomf=0.0): """ Set the scene's current image (input image must be a QImage) For calculating the zoom factor automatically set it to 0.0. """ self.img_map = img if type(img) is QImage: imageARGB32 = img.convertToFormat(QImage.Format_ARGB32) self.pixmap = QPixmap.fromImage(imageARGB32) self.imgwidth = img.width() self.imgheight = img.height() if self.imgheight: self.ZOOM_FACTOR_MIN = min( 1.0 * self.width() / self.imgwidth, 1.0 * self.height() / self.imgheight) else: raise RuntimeError("Argument must be a QImage.") self.pixmapitem.setPixmap(self.pixmap) if zoomf < 0.0000001: # calculate zoom factor # Set scene size to image size (!) self.setSceneRect(QRectF(self.pixmap.rect())) # calculate zoom factor pixels_of_border = 10 zf1 = (self.viewport().width() - pixels_of_border) / self.imgwidth zf2 = (self.viewport().height() - pixels_of_border) / self.imgheight zf = min(zf1, zf2) self.zoom_factor = zf self.updateViewer() @pyqtSlot() def viewChanged(self): if not self.imgwidth: return rect = self.viewportToScenePercent() self.viewUpdated.emit(rect) posx = self.horizontalScrollBar().value() posy = self.verticalScrollBar().value() zoom = self.zoom_factor / self.px_to_mm self.viewHasChanged.emit(posx, posy, zoom) def setViewParameters(self, posx, posy, zoomfactor): if not self.isVisible(): return self.blockSignals(True) self.horizontalScrollBar().setValue(posx) self.verticalScrollBar().setValue(posy) self.zoom_factor = zoomfactor * self.px_to_mm self.updateViewer() self.blockSignals(False) def updateViewer(self): """ Show current zoom (if showing entire image, apply current aspect ratio mode). """ self.resetTransform() self.scale(self.zoom_factor, self.zoom_factor) self.invalidateScene() def clear(self): self.pixmapitem.setPixmap(QPixmap()) self.img_map = None def disableScrollBars(self): self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) def enablePan(self): self.panEnabled = True def disablePan(self): self.panEnabled = False def enableZoom(self): self.zoomEnabled = True def disableZoom(self): self.zoomEnabled = False def viewportToScene(self): #check topleft = self.mapToScene(self.viewport().rect().topLeft()) bottomright = self.mapToScene(self.viewport().rect().bottomRight()) return QRectF(topleft, bottomright) def viewportToScenePercent(self): view = self.viewportToScene() view.setCoords(view.left() / self.imgwidth, view.top() / self.imgheight, view.right() / self.imgwidth, view.bottom() / self.imgheight) return view def clampCoords(self, x, y): if self.img_map is not None: xc = max(0, min(int(x), self.img_map.width())) yc = max(0, min(int(y), self.img_map.height())) else: xc = 0 yc = 0 return (xc, yc) # UNUSED def setOpacity(self, opacity): self.opacity = opacity def setOverlayImage(self, image): self.overlay_image = image.convertToFormat(QImage.Format_ARGB32) self.drawOverlayImage() def drawOverlayImage(self): if self.overlay_image.width() <= 1: return pxmap = self.pixmap.copy() p = QPainter() p.begin(pxmap) p.setOpacity(self.opacity) p.drawImage(0, 0, self.overlay_image) p.end() self.pixmapitem.setPixmap(pxmap) def clipScenePos(self, scenePosition): posx = scenePosition.x() posy = scenePosition.y() if posx < 0: posx = 0 if posy < 0: posy = 0 if posx > self.imgwidth: posx = self.imgwidth if posy > self.imgheight: posy = self.imgheight return [round(posx), round(posy)] def resizeEvent(self, event): """ Maintain current zoom on resize. """ if self.imgheight: self.ZOOM_FACTOR_MIN = min(1.0 * self.width() / self.imgwidth, 1.0 * self.height() / self.imgheight) self.updateViewer() @pyqtSlot(float, float) def center(self, x, y): zf = self.zoom_factor xmap = float(self.img_map.width()) * x ymap = float(self.img_map.height()) * y view = self.viewportToScene() (w, h) = (view.width(), view.height()) posx = max(0, xmap - w / 2) posy = max(0, ymap - h / 2) posx = min(posx, self.img_map.width() - w / 2) posy = min(posy, self.img_map.height() - h / 2) self.horizontalScrollBar().setValue(posx * zf) self.verticalScrollBar().setValue(posy * zf)
class RenderWindow(QWidget): def __init__(self): windowSettings = self.loadSettings() self.width = windowSettings["ImageWidth"] self.height = windowSettings["ImageHeight"] super().__init__() self.setFixedSize(self.width, self.height) self.move(200, 200) self.setWindowTitle('RayTracing') self.showBuckets = True # show bucket switch self.bgImage = QImage(self.width, self.height, 4) # QImage.Format_RGB32 self.bgImage.fill(QColor(0, 0, 0)) # important, give canvas a default color self.bucketLocator = QImage( "bucketLocator.png") # Bucket Locator Image self.graphic = QGraphicsScene(0, 0, self.width, self.height, self) self.canvasPixmap = QPixmap().fromImage(self.bgImage) self.canvasPainter = QPainter(self.canvasPixmap) # Render image pixmap and painter self.renderImagePixmap = QPixmap().fromImage(self.bgImage) self.renderImagePainter = QPainter(self.renderImagePixmap) # BuckerLocators pixmap and painter self.locatorPixmap = QPixmap().fromImage(self.bgImage) self.locatorPainter = QPainter(self.locatorPixmap) self.graphicItem = self.graphic.addPixmap(self.canvasPixmap) self.graphicView = QGraphicsView(self.graphic, self) self.show() def loadSettings(self): with open("RenderSettings.json") as settingsData: renderSettings = json.load(settingsData) return renderSettings["RenderWindow"] def keyPressEvent(self, event): if event.key() == Qt.Key_S: self.saveImage() elif event.key() == Qt.Key_H: if self.showBuckets: self.showBuckets = False print("Hide Buckets") else: self.showBuckets = True print("Show Buckets") self.refreshCanvas() def startRender(self, scene, cam): # start render in a new thread self.renderTask = RenderThread(self.width, self.height, scene, cam) self.renderTask.updateImgSignal.connect(self.updateRenderImage) self.renderTask.bucketProgressSignal.connect(self.showBucketProgess) self.renderTask.finished.connect(self.cleanBucketLocators) self.renderTask.finished.connect(self.saveImage) self.renderTask.start() def cleanBucketLocators(self): self.locatorPainter.drawImage(0, 0, self.bgImage) self.refreshCanvas() def showBucketProgess(self, bucketProgressPos): bucketSize = bucketProgressPos[2] if len(bucketProgressPos) > 3: blackPatch = QImage(bucketSize, bucketSize, 4) blackPatch.fill(0) self.locatorPainter.drawImage(bucketProgressPos[3], bucketProgressPos[4], blackPatch) bucketLocImg = self.bucketLocator.scaled(bucketSize, bucketSize) self.locatorPainter.drawImage(bucketProgressPos[0], bucketProgressPos[1], bucketLocImg) self.refreshCanvas() def updateRenderImage(self, bucketDataList): # update the render view, note the render is in another thread] # use QPainter to stamp the image to canvas self.renderImagePainter.drawImage(bucketDataList[0], bucketDataList[1], bucketDataList[2]) self.refreshCanvas() def refreshCanvas(self): self.canvasPainter.drawPixmap(0, 0, self.renderImagePixmap) if self.showBuckets: self.canvasPainter.setCompositionMode( 12) # plus locator layer on top self.canvasPainter.drawPixmap(0, 0, self.locatorPixmap) self.canvasPainter.setCompositionMode( 0) # set comp mode back to over self.graphicItem.setPixmap(self.canvasPixmap) def saveImage(self): self.canvasPixmap.save("Render10.png") print("Image Saved")
def play_video(self): try: # read image from queue ret, frame, current_frame_no = self.q.get() if ret is True: # update progress bar location at each frame progress = self.frame_to_timestamp(current_frame_no, self.fps_metadata) + ' / ' \ + self.frame_to_timestamp(self.totalFrames, self.fps_metadata) self.progresslabel.setText(progress) # to sync with audio progress self.current_second = current_frame_no / self.fps_metadata # stop updating slider in UI while clicked while continuing playback if self.slider_pressed is False: self.progressBar.setValue(current_frame_no) # encode frame and send to clients try: _, buffer = cv2.imencode('.jpeg', frame, [cv2.IMWRITE_JPEG_QUALITY, 80]) encoded_frame = base64.b64encode(buffer) # print(buffer) # print(encoded_frame) # luk # print(sys.getsizeof(encoded_frame)) # TODO: maybe send total_frames and fps only once in the TCP connection msg_pair = {"frame_nb": current_frame_no, "total_frames": self.totalFrames, "frame": encoded_frame, "fps": self.fps_metadata} packed_message = pickle.dumps(msg_pair) msg_size = sys.getsizeof(packed_message) if msg_size > 63000: print(msg_size) # print(self.clients) for client in self.clients: self.video_socket.sendto(packed_message, (client, self.client_port)) # print(client) except Exception as e: logging.error('video: {}'.format(e)) # luk # import numpy as np # dec = base64.b64decode(encoded_frame, ' /') # dec = np.fromstring(dec, dtype=np.uint8) # frame = cv2.imdecode(dec, 1) # # display frame in player # convert image to RGB format frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # get image infos height, width, channel = frame.shape # print(height, width, channel) step = channel * width # create QImage from image qImg = QImage(frame.data, width, height, step, QImage.Format_RGB888) # show image in UI frame label # self.frame.setPixmap(QPixmap.fromImage(qImg)) pixmap = QPixmap.fromImage(qImg) pixmap = pixmap.scaled(self.frame.width(), self.frame.height()) scene = QGraphicsScene() scene.addPixmap(pixmap) self.frame.setSceneRect(0, 0, self.frame.width() - 10, self.frame.height() - 10) self.frame.setScene(scene) # because frame processing time if fluctuating # we need to sync it to the FPS fetched from the metadata # sync with audio timestamp if self.current_second < self.threadAudio.current_second and self.frame_freq > 0: self.frame_freq -= 0.001 elif self.current_second > self.threadAudio.current_second: self.frame_freq += 0.001 # source for sync with fps: # https://pyshine.com/Send-video-over-UDP-socket-in-Python # sync with metadata fps if self.cnt == self.frames_to_count: try: self.fps_actual = (self.frames_to_count / (time.time() - self.time_prev_frame)) self.time_prev_frame = time.time() self.cnt = 0 if self.fps_actual > self.fps_metadata: self.frame_freq += 0.001 elif self.fps_actual < self.fps_metadata and self.frame_freq > 0: self.frame_freq -= 0.001 else: pass except Exception as e: logging.error(e) self.cnt += 1 # print(self.fps_metadata, self.fps_actual) self.fpsLabel.setText(str(round(self.fps_actual, 1))) # restart and update timer with new frame frequency self.timer.start(self.frame_freq * SECONDS_TO_MS) # restart playback at end of video and pause if current_frame_no >= self.totalFrames - 5: try: self.stop_timer() self.threadAudio.stopSignal.emit() self.move_progress_bar_client(0) self.threadAudio.move_slider_client(0) logging.info('Server finished playback') except Exception as e: logging.error('reset playback err: ', e) except Exception as e: logging.error(e)
class ChessView(QGraphicsView): boardWidht = 8 boardHeight = 8 boardOffset = 20 fieldWidht = 60 fieldHeight = 60 def __init__(self): QGraphicsView.__init__(self) # SIZES OF THE BOARD VIEW self.viewHeight = self.boardHeight * self.fieldHeight + 3 * self.boardOffset self.viewWidht = self.boardWidht * self.fieldWidht + 3 * self.boardOffset self.setFixedHeight(self.viewHeight) self.setFixedWidth(self.viewWidht) # SCENE AND ALL VISUAL THINGS self.scene = QGraphicsScene(0, 0, self.viewWidht - self.boardOffset, self.viewHeight - self.boardOffset) # self.view = QGraphicsView(self.scene) self.setScene(self.scene) self.generateBoard() self.addingGameBoardToScene() self.printBoard() # MOVE MANAGE self.moveFigure = [(-1, -1), (-1, -1)] self.playerRound = "white" self.figureChosen = False self.possibleMoves = [] def highlightPossibleFieldMoves(self): for position in self.possibleMoves: arrayPosition = self.translateCordinatesIntoPositionInBoardArray( position) self.gameBoard[arrayPosition].setHighlightPossibleMoveFields() self.gameBoard[arrayPosition].updateSelf() def notHighlightAllFields(self): for i in range(self.boardWidht): for j in range(self.boardHeight): if self.gameBoard[i * self.boardWidht + j].getHighlightField(): self.gameBoard[i * self.boardWidht + j].highlightField = False self.gameBoard[i * self.boardWidht + j].updateSelf() def translateCordinatesIntoPositionInBoardArray(self, cordinates): xPos = cordinates[0] yPos = cordinates[1] return (7 - yPos) * self.boardWidht + xPos def getClickedFigurePosition(self): return (self.moveFigure) def addingGameBoardToScene(self): for i in range(self.boardWidht): for j in range(self.boardHeight): self.scene.addItem(self.gameBoard[i * self.boardWidht + j]) def generateBoard(self): self.gameBoard = [] for i in range(self.boardWidht): for j in range(self.boardHeight): color = self.generateColorOfField(i, j) self.gameBoard.append( BoardField(j * self.fieldWidht + self.boardOffset, i * self.fieldHeight + self.boardOffset, color, self.fieldWidht, self.boardOffset, None, self)) def generateColorOfField(self, xindex, yindex): if (xindex + yindex) % 2 == 0: color = QColor(255, 255, 255) else: color = QColor(150, 150, 150) return color def printBoard(self): for i in range(self.boardWidht): print("") for j in range(self.boardHeight): print(self.gameBoard[i * self.boardWidht + j].getBoardPosition(), end=" ") print(self.gameBoard[i * self.boardWidht + j].getFieldPosition(), end=" ")
def renderSolution(self, solution): __pickImageList = [] __pixPickImageList = [] __itemPickImageList = [] __scenePickImageList = [ QGraphicsScene(), QGraphicsScene(), QGraphicsScene(), QGraphicsScene(), QGraphicsScene() ] __scenePickStarList = [ QGraphicsScene(), QGraphicsScene(), QGraphicsScene(), QGraphicsScene(), QGraphicsScene() ] for i in range(5): if solution["atk"][i]['star'] == 1: __scenePickStarList[i].addText("一星") if solution["atk"][i]['star'] == 2: __scenePickStarList[i].addText("二星") if solution["atk"][i]['star'] == 3: __scenePickStarList[i].addText("三星") if solution["atk"][i]['star'] == 4: __scenePickStarList[i].addText("四星") if solution["atk"][i]['star'] == 5: __scenePickStarList[i].addText("五星") if solution["atk"][i]['star'] == 6: __scenePickStarList[i].addText("六星") for pick in solution["atk"]: __pickImageList.append(util.query_getPickAvatar(pick['id'])) __pixPickImageList = [ QtGui.QPixmap.fromImage(pickImage) for pickImage in __pickImageList ] __itemPickImageList = [ QGraphicsPixmapItem(pix) for pix in __pixPickImageList ] for i in range(len(__scenePickImageList)): __scenePickImageList[i].addItem(__itemPickImageList[i]) try: self.findChild(QGraphicsView, 'pick1Avatar_%s' % solution['id']).setScene(__scenePickImageList[0]) self.findChild(QGraphicsView, 'pick2Avatar_%s' % solution['id']).setScene(__scenePickImageList[1]) self.findChild(QGraphicsView, 'pick3Avatar_%s' % solution['id']).setScene(__scenePickImageList[2]) self.findChild(QGraphicsView, 'pick4Avatar_%s' % solution['id']).setScene(__scenePickImageList[3]) self.findChild(QGraphicsView, 'pick5Avatar_%s' % solution['id']).setScene(__scenePickImageList[4]) self.findChild(QGraphicsView, 'pick1Star_%s' % solution['id']).setScene(__scenePickStarList[0]) self.findChild(QGraphicsView, 'pick2Star_%s' % solution['id']).setScene(__scenePickStarList[1]) self.findChild(QGraphicsView, 'pick3Star_%s' % solution['id']).setScene(__scenePickStarList[2]) self.findChild(QGraphicsView, 'pick4Star_%s' % solution['id']).setScene(__scenePickStarList[3]) self.findChild(QGraphicsView, 'pick5Star_%s' % solution['id']).setScene(__scenePickStarList[4]) self.findChild(QLabel, 'upCount_%s' % solution['id']).setText( str(solution['up'])) self.findChild(QLabel, 'upCount_%s' % solution['id']).setStyleSheet("color:green") self.findChild(QLabel, 'downCount_%s' % solution['id']).setText( str(solution['down'])) self.findChild(QLabel, 'downCount_%s' % solution['id']).setStyleSheet("color:red") for comment in list(reversed(solution['comment'])): self.findChild( QTextBrowser, 'commentBrowser_%s' % solution['id']).append( "(%s) %s" % (comment['date'][:10], comment['msg'])) except Exception as e: print(e, solution)
def recognizeAndSolve(self, teamNum: [0, 1, 2, 3, 4]): if self.handle == 0: QMessageBox.information(self, "No Handle", "No Handle") self.queryStatusTag.setText("请选择句柄") self.queryStatusTag.setStyleSheet("color:red") return self.sceneCharImageList = [ QGraphicsScene(), QGraphicsScene(), QGraphicsScene(), QGraphicsScene(), QGraphicsScene() ] for scene in self.sceneCharImageList: scene.clear() for i in range(self.solutionListLayout.count()): self.solutionListLayout.itemAt(i).widget().deleteLater() screenshot = screen.grabWindow(self.handle).toImage() copyX = config.simulator['marginOffset'][0] copyY = config.simulator['marginOffset'][1] copyWidth = screenshot.width() - config.simulator['marginOffset'][ 0] - config.simulator['marginOffset'][2] copyHeight = screenshot.height() - config.simulator['marginOffset'][ 1] - config.simulator['marginOffset'][3] gameImage = screenshot.copy(copyX, copyY, copyWidth, copyHeight) # 根据边框裁剪出游戏图像 if teamNum == 0: # 当前目标队,右上 translatedCharY = gameImage.height( ) * config.charLocationRatioConfig_CurrentEnemyTeam[ 'y'] # 根据比例计算出对方阵容图标的y值、h值、w值 translatedCharH = gameImage.height( ) * config.charLocationRatioConfig_CurrentEnemyTeam['h'] translatedCharW = gameImage.width( ) * config.charLocationRatioConfig_CurrentEnemyTeam['w'] self.charImageList = [ gameImage.copy(gameImage.width() * x, translatedCharY, translatedCharW, translatedCharH).scaledToWidth(60) for x in config.charLocationRatioConfig_CurrentEnemyTeam['x'] ] # 裁剪出对方每个角色头像 if teamNum == 1: # 履历一队 translatedCharY = gameImage.height( ) * config.charLocationRatioConfig_HistoryTeamOne[ 'y'] # 根据比例计算出对方阵容图标的y值、h值、w值 translatedCharH = gameImage.height( ) * config.charLocationRatioConfig_HistoryTeamOne['h'] translatedCharW = gameImage.width( ) * config.charLocationRatioConfig_HistoryTeamOne['w'] self.charImageList = [ gameImage.copy(gameImage.width() * x, translatedCharY, translatedCharW, translatedCharH).scaledToWidth(60) for x in config.charLocationRatioConfig_HistoryTeamOne['x'] ] # 裁剪出对方每个角色头像 if teamNum == 2: # 履历二队 translatedCharY = gameImage.height( ) * config.charLocationRatioConfig_HistoryTeamTwo[ 'y'] # 根据比例计算出对方阵容图标的y值、h值、w值 translatedCharH = gameImage.height( ) * config.charLocationRatioConfig_HistoryTeamTwo['h'] translatedCharW = gameImage.width( ) * config.charLocationRatioConfig_HistoryTeamTwo['w'] self.charImageList = [ gameImage.copy(gameImage.width() * x, translatedCharY, translatedCharW, translatedCharH).scaledToWidth(60) for x in config.charLocationRatioConfig_HistoryTeamTwo['x'] ] # 裁剪出对方每个角色头像 if teamNum == 3: # 履历三队 translatedCharY = gameImage.height( ) * config.charLocationRatioConfig_HistoryTeamThree[ 'y'] # 根据比例计算出对方阵容图标的y值、h值、w值 translatedCharH = gameImage.height( ) * config.charLocationRatioConfig_HistoryTeamThree['h'] translatedCharW = gameImage.width( ) * config.charLocationRatioConfig_HistoryTeamThree['w'] self.charImageList = [ gameImage.copy(gameImage.width() * x, translatedCharY, translatedCharW, translatedCharH).scaledToWidth(60) for x in config.charLocationRatioConfig_HistoryTeamThree['x'] ] # 裁剪出对方每个角色头像 if teamNum == -1: # 当前防守队 translatedCharY = gameImage.height( ) * config.charLocationRatioConfig_OwnTeam[ 'y'] # 根据比例计算出对方阵容图标的y值、h值、w值 translatedCharH = gameImage.height( ) * config.charLocationRatioConfig_OwnTeam['h'] translatedCharW = gameImage.width( ) * config.charLocationRatioConfig_OwnTeam['w'] self.charImageList = [ gameImage.copy(gameImage.width() * x, translatedCharY, translatedCharW, translatedCharH).scaledToWidth(60) for x in config.charLocationRatioConfig_OwnTeam['x'] ] # 裁剪出对方每个角色头像 self.charDataList = [ { 'name': '未知角色', 'id': 1000 }, { 'name': '未知角色', 'id': 1000 }, { 'name': '未知角色', 'id': 1000 }, { 'name': '未知角色', 'id': 1000 }, { 'name': '未知角色', 'id': 1000 }, ] self.pixCharImageList = [ QtGui.QPixmap.fromImage(charImage) for charImage in self.charImageList ] # for i in range(len(self.pixCharImageList)): # self.pixCharImageList[i].save('%s.png' % i) self.itemCharImageList = [ QGraphicsPixmapItem(pix) for pix in self.pixCharImageList ] # self.sceneCharImageList = [QGraphicsScene().addItem(item) for item in self.itemCharImageList] self.showChars() self.parseChars() raw_id_list = [charData['id'] for charData in self.charDataList] id_list = [x * 100 + 1 for x in raw_id_list] payload = { "_sign": "a", "def": id_list, "nonce": "a", "page": 1, "sort": 1, "ts": int(time.time()), "region": self.region } runnable = RequestRunnable("https://api.pcrdfans.com/x/v1/search", payload, self, self.apiKey) QThreadPool.globalInstance().start(runnable)
class WindowDesign(Ui_DesignWindow): def setupUi(self, DesignWindow, OldWindow, funcReload): super().setupUiWin(DesignWindow) # cac bien noi bo self.numOfRect = 0 self.numOfImg = 0 self.numOfText = 0 self.rect = [] self.img = [] self.text = [] self.scene = QGraphicsScene() self.scene.setSceneRect(0, 0, 10, 10) q = QPixmap("watermark/pdfModel.png").scaledToWidth(650) self.width = q.width() self.height = q.height() self.scene.setSceneRect(0, 0, self.width, self.height) self.mau = self.scene.addPixmap(q) self.graphicsView.setScene(self.scene) # Gan cac su kien self.btnSelectImg.clicked.connect(self.addImage) self.widthRec.textChanged.connect(self.changeWidth) self.heightRec.textChanged.connect(self.changeHeight) self.btnAddRec.clicked.connect(self.addRect) self.btnUndoRec.clicked.connect(self.undoRec) self.btnSelectColor.clicked.connect(self.selectColor) self.btnAddText.clicked.connect(self.addText) self.textInput.textChanged.connect(self.changeText) self.sizeText.textChanged.connect(self.changeSize) self.btnUndoText.clicked.connect(self.undoText) self.btnSave.clicked.connect( lambda: self.makeImg(DesignWindow, OldWindow, funcReload)) self.btnSelectPdf.clicked.connect(lambda: self.loadPdf(DesignWindow)) self.btnUndoImg.clicked.connect(self.undoImg) def loadPdf(self, ThisWindow): fname = QFileDialog.getOpenFileName(ThisWindow, 'Chọn PDF mẫu', 'c:\\', "Pdf files (*.pdf)") if fname[0]: pdf2png(fname[0], "watermark/") q = QPixmap("watermark/pdfModel.png").scaledToWidth(650) self.width = q.width() self.height = q.height() self.scene.setSceneRect(0, 0, self.width, self.height) self.mau.hide() self.mau = self.scene.addPixmap(q) def makeImg(self, ThisWindow, OldWindow, funcReload): name = self.textName.text() if self.textName.text() != "" else "NoName" self.mau.hide() img = QImage(self.width, self.height, QImage.Format_ARGB32) painter = QPainter(img) self.scene.render(painter) painter.end() img.save("watermark/template.png") png2pdf("watermark/template.png", "watermark/" + name + ".pdf") ThisWindow.close() OldWindow.show() funcReload() def addImage(self): fname = QFileDialog.getOpenFileName(None, 'Open file', 'c:\\', "Image files (*.png)") if fname[0]: temImg = QPixmap(fname[0]) temImg = temImg.scaledToWidth(int(temImg.width() * 70 / 123)) self.img.append({ "main": self.scene.addPixmap(temImg), "url": fname[0] }) self.img[self.numOfImg]["main"].setFlag( QGraphicsItem.ItemIsMovable) self.numOfImg += 1 def undoImg(self): if self.numOfImg > 0: self.img[-1]["main"].hide() self.img.pop() self.numOfImg -= 1 def undoText(self): if self.numOfText > 0: self.text[-1]["main"].hide() self.text.pop() self.numOfText -= 1 def changeSize(self): try: size = int(self.sizeText.text()) if self.numOfText > 0: self.text[-1]["size"] = size html = self.toHtml(self.text[-1]["content"], self.text[-1]["color"], size) self.text[-1]["main"].setHtml(html) except: pass def changeText(self): content = self.textInput.text() if content != "" and self.numOfText > 0: self.text[-1]["content"] = content html = self.toHtml(content, self.text[-1]["color"], self.text[-1]["size"]) self.text[-1]["main"].setHtml(html) def addText(self): content = "Không có nội dung" if self.textInput.text( ) == "" else self.textInput.text() try: size = int(self.sizeText.text()) except: size = 15 self.text.append({ "main": self.scene.addText(""), "content": content, "color": [0, 0, 255], "size": size }) self.text[self.numOfText]["main"].setHtml( self.toHtml(content, [0, 0, 255], size)) self.text[self.numOfText]["main"].setFlag(QGraphicsItem.ItemIsMovable) self.numOfText += 1 def selectColor(self): color = QColorDialog.getColor() if self.numOfText > 0: self.text[-1]["color"] = [color.red(), color.green(), color.blue()] html = self.toHtml(self.text[-1]["content"], self.text[-1]["color"], self.text[-1]["size"]) self.text[self.numOfText - 1]["main"].setHtml(html) def undoRec(self): if self.numOfRect > 0: self.rect[-1].hide() self.rect.pop() self.numOfRect -= 1 def changeWidth(self): try: r = self.rect[-1].rect() r.setWidth(float(self.widthRec.text())) self.rect[-1].setRect(r) except: pass def changeHeight(self): try: r = self.rect[-1].rect() r.setHeight(float(self.heightRec.text())) self.rect[-1].setRect(r) except: pass def addRect(self): self.rect.append( self.scene.addRect(0, 0, 100, 100, QPen(Qt.red, -1), QBrush(Qt.white))) self.rect[self.numOfRect].setFlag(QGraphicsItem.ItemIsMovable) self.numOfRect += 1 self.widthRec.setText("100") self.heightRec.setText("100") @staticmethod def toHtml(content, color, size): str = '<span style="color: rgb({},{},{});font-size: {}px">{}</span>' return str.format(color[0], color[1], color[2], size, content)
class fDuration (QGraphicsView): viewUpdate = pyqtSignal() def __init__(self,winParent): QGraphicsView.__init__(self) self.winParent=winParent self.viewUpdate.connect(self.update) self.m_hour = 0 self.m_min = 0 self.m_sec = 0 self.m_scaleX = 0 self.m_scaleY = 0 self.m_originalHeight = 245 self.m_originalWidth = 245 self.m_originalFdCtr = QPointF(120,120) self.m_originalMarkCtr = QPointF(120, 120) self.m_faceZ = -20 self.m_handZ = -10 self.m_caseZ = 10 self.m_mark1Z = 20 self.m_mark2Z = 30 self.m_mark3Z = 40 self.m_itemHand = None self.m_itemFace = None self.m_itemCase = None self.m_itemMark1 = None self.m_itemMark2 = None self.m_itemMark3 = None self.setStyleSheet("background: transparent; border: none"); self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setInteractive(False) self.setEnabled(False) self.m_scene = QGraphicsScene(self) self.setScene(self.m_scene) self.init() def init (self): #os.chdir('/Users/zeyneptuna/Desktop/during_flight/widget/flight_duration') self.m_scaleX = self.width() / self.m_originalWidth self.m_scaleY = self.height() / self.m_originalHeight self.m_itemFace = QGraphicsSvgItem("widget/flight_duration/fd_face.svg") self.m_itemFace.setCacheMode(QGraphicsItem.NoCache) self.m_itemFace.setZValue(self.m_faceZ) self.m_itemFace.setTransform(QTransform.fromScale(self.m_scaleX, self.m_scaleY), True) self.m_itemFace.setTransformOriginPoint(self.m_originalFdCtr) self.m_scene.addItem(self.m_itemFace) self.m_itemCase = QGraphicsSvgItem("widget/flight_duration/fd_case.svg") self.m_itemCase.setCacheMode(QGraphicsItem.NoCache) self.m_itemCase.setZValue(self.m_caseZ) self.m_itemCase.setTransform(QTransform.fromScale(self.m_scaleX, self.m_scaleY), True) self.m_itemCase.setTransformOriginPoint(self.m_originalFdCtr) self.m_scene.addItem(self.m_itemCase) #self.m_itemMark1 = QGraphicsSvgItem("fd_mark_1.svg") #self.m_itemMark1.setCacheMode(QGraphicsItem.NoCache) #self.m_itemMark1.setZValue(self.m_mark1Z) #self.m_itemMark1.setTransformOriginPoint(self.m_originalMarkCtr) #self.m_itemMark1.setTransform(QTransform.fromScale(self.m_scaleX, self.m_scaleY), True) #self.m_scene.addItem(self.m_itemMark1) #self.m_itemMark2 = QGraphicsSvgItem("fd_mark_2.svg") #self.m_itemMark2.setCacheMode(QGraphicsItem.NoCache) #self.m_itemMark2.setZValue(self.m_mark2Z) #self.m_itemMark2.setTransformOriginPoint(self.m_originalMarkCtr) #self.m_itemMark2.setTransform(QTransform.fromScale(self.m_scaleX, self.m_scaleY), True) #self.m_scene.addItem(self.m_itemMark2) #self.m_itemMark3 = QGraphicsSvgItem("fd_mark_3.svg") #self.m_itemMark3.setCacheMode(QGraphicsItem.NoCache) #self.m_itemMark3.setZValue(self.m_mark3Z) #self.m_itemMark3.setTransformOriginPoint(self.m_originalMarkCtr) #self.m_itemMark3.setTransform(QTransform.fromScale(self.m_scaleX, self.m_scaleY), True) #self.m_scene.addItem(self.m_itemMark3) self.centerOn (self.width()/2, self.height()/2) self.updateView() def reinit(self): if (self.m_scene): self.m_scene.clear() self.init() def update(self): self.updateView() def setHour (self, hour): self.m_hour = hour def setMin (self, mins): self.m_min = mins def setSec (self, sec): self.m_sec = sec def resizeEvent (self, event): QGraphicsView.resizeEvent (self,event) self.reinit() def reset (self): self.m_itemFace = None self.m_itemCase = None self.m_itemMark1 = None self.m_itemMark2 = None self.m_itemMark3 = None self.m_hour = 0 self.m_min = 0 self.m_sec = 0 def updateView(self): #angle1 = 90*((self.m_hour - 9)/3) #angle2 = 90*((self.m_min)/15) #angle3 = 90*((self.m_sec - 54)/15) #self.m_itemMark1.setRotation( angle1 ) #self.m_itemMark2.setRotation( angle2 ) #self.m_itemMark3.setRotation( angle3 ) self.m_scene.update()
class TRelFormatDlg(QDialog, Ui_TRelFormatDlg): """ Class documentation goes here. """ def __init__(self, parent=None, modelData=None, relFormat=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(TRelFormatDlg, self).__init__(parent) self.modelData = modelData self.relFormat = relFormat if self.relFormat is None: self.relFormat = TRelFormat() self.testItem = None self.setupUi(self) # complete ui setups self.graphicsView = QGraphicsView(parent=self.frmView) self.scene = QGraphicsScene(self) self.scene.setSceneRect(0, 0, 300, 600) self.graphicsView.setScene(self.scene) self.populateUIfromObject() self.drawLine() def populateUIfromObject(self, ): self.spinLineWidth.setValue(self.relFormat.formatDict["lineWidth"]) #line style if self.relFormat.formatDict["lineStyle"] == "Solid": self.rbSolidLine.setChecked(True) if self.relFormat.formatDict["lineStyle"] == "Dash": self.rbDashLine.setChecked(True) if self.relFormat.formatDict["lineStyle"] == "Dot": self.rbDotLine.setChecked(True) if self.relFormat.formatDict["lineStyle"] == "DashDot": self.rbDashDotLine.setChecked(True) if self.relFormat.formatDict["lineStyle"] == "DashDotDot": self.rbDashDotDotLine.setChecked(True) def drawLine(self, ): if not (self.testItem is None): self.scene.removeItem(self.testItem) pen = self.relFormat.pen() #brush = self.relFormat.brush() self.testItem = QGraphicsLineItem(5, 50, 100, 50, parent=None) self.testItem.setPen(pen) self.scene.addItem(self.testItem) @pyqtSlot() def on_okButton_clicked(self): """ Slot documentation goes here. """ return @pyqtSlot() def on_cancelButton_clicked(self): """ Slot documentation goes here. """ QDialog.reject(self) @pyqtSlot() def on_rbNone_clicked(self): """ Slot documentation goes here. """ if self.rbNone.isChecked() == True: self.relFormat.formatDict["fillStyle"] = "None" self.drawLine() @pyqtSlot() def on_rbPattern_clicked(self): """ Slot documentation goes here. """ if self.rbPattern.isChecked() == True: self.relFormat.formatDict["fillStyle"] = "Pattern" self.drawLine() @pyqtSlot(int) def on_spinPattern_valueChanged(self, p0): """ Slot documentation goes here. @param p0 DESCRIPTION @type int """ self.relFormat.formatDict["patternNumber"] = self.spinPattern.value() self.drawLine() @pyqtSlot() def on_btnFillColor_clicked(self): """ fill color push button """ aColor = QColor() QColor.setNamedColor(aColor, self.relFormat.formatDict["fillColor"]) newColor = QColorDialog.getColor(initial=aColor, parent=None) if newColor.isValid(): self.relFormat.formatDict["fillColor"] = newColor.name() self.drawLine() @pyqtSlot() def on_btnLineColor_clicked(self): """ Slot documentation goes here. """ aColor = QColor() QColor.setNamedColor(aColor, self.relFormat.formatDict["lineColor"]) newColor = QColorDialog.getColor(initial=aColor, parent=None) if newColor.isValid(): self.relFormat.formatDict["lineColor"] = newColor.name() self.drawLine() @pyqtSlot() def on_rbNoLine_clicked(self): """ Slot documentation goes here. """ if self.rbNoLine.isChecked() == True: self.relFormat.formatDict["lineStyle"] = "No Line" self.drawLine() @pyqtSlot() def on_rbSolidLine_clicked(self): """ Slot documentation goes here. """ if self.rbSolidLine.isChecked() == True: self.relFormat.formatDict["lineStyle"] = "Solid" self.drawLine() @pyqtSlot() def on_rbDashLine_clicked(self): """ Slot documentation goes here. """ if self.rbDashLine.isChecked() == True: self.relFormat.formatDict["lineStyle"] = "Dash" self.drawLine() @pyqtSlot() def on_rbDotLine_clicked(self): """ Slot documentation goes here. """ if self.rbDotLine.isChecked() == True: self.relFormat.formatDict["lineStyle"] = "Dot" self.drawLine() @pyqtSlot() def on_rbDashDotLine_clicked(self): """ Slot documentation goes here. """ if self.rbDashDotLine.isChecked() == True: self.relFormat.formatDict["lineStyle"] = "DashDot" self.drawLine() @pyqtSlot() def on_rbDashDotDotLine_clicked(self): """ Slot documentation goes here. """ if self.rbDashDotDotLine.isChecked() == True: self.relFormat.formatDict["lineStyle"] = "DashDotDot" self.drawLine() @pyqtSlot(int) def on_spinLineWidth_valueChanged(self, p0): """ Slot documentation goes here. @param p0 DESCRIPTION @type int """ self.relFormat.formatDict["lineWidth"] = self.spinLineWidth.value() self.drawLine()
class Lighting(QGraphicsView): def __init__(self, parent=None): super(Lighting, self).__init__(parent) self.angle = 0.0 self.m_scene = QGraphicsScene() self.m_lightSource = None self.m_items = [] self.setScene(self.m_scene) self.setupScene() timer = QTimer(self) timer.timeout.connect(self.animate) timer.setInterval(30) timer.start() self.setRenderHint(QPainter.Antialiasing) self.setFrameStyle(QFrame.NoFrame) def setupScene(self): self.m_scene.setSceneRect(-300, -200, 600, 460) linearGrad = QLinearGradient(QPointF(-100, -100), QPointF(100, 100)) linearGrad.setColorAt(0, QColor(255, 255, 255)) linearGrad.setColorAt(1, QColor(192, 192, 255)) self.setBackgroundBrush(linearGrad) radialGrad = QRadialGradient(30, 30, 30) radialGrad.setColorAt(0, Qt.yellow) radialGrad.setColorAt(0.2, Qt.yellow) radialGrad.setColorAt(1, Qt.transparent) pixmap = QPixmap(60, 60) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setPen(Qt.NoPen) painter.setBrush(radialGrad) painter.drawEllipse(0, 0, 60, 60) painter.end() self.m_lightSource = self.m_scene.addPixmap(pixmap) self.m_lightSource.setZValue(2) for i in range(-2, 3): for j in range(-2, 3): if (i + j) & 1: item = QGraphicsEllipseItem(0, 0, 50, 50) else: item = QGraphicsRectItem(0, 0, 50, 50) item.setPen(QPen(Qt.black, 1)) item.setBrush(QBrush(Qt.white)) effect = QGraphicsDropShadowEffect(self) effect.setBlurRadius(8) item.setGraphicsEffect(effect) item.setZValue(1) item.setPos(i * 80, j * 80) self.m_scene.addItem(item) self.m_items.append(item) def animate(self): self.angle += (math.pi / 30) xs = 200 * math.sin(self.angle) - 40 + 25 ys = 200 * math.cos(self.angle) - 40 + 25 self.m_lightSource.setPos(xs, ys) for item in self.m_items: effect = item.graphicsEffect() delta = QPointF(item.x() - xs, item.y() - ys) effect.setOffset(QPointF(delta.toPoint() / 30)) dd = math.hypot(delta.x(), delta.y()) color = effect.color() color.setAlphaF(max(0.4, min(1 - dd / 200.0, 0.7))) effect.setColor(color) self.m_scene.update()
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 ImageView(QGraphicsView): """图片查看控件""" def __init__(self, *args, **kwargs): image = kwargs.pop('image', None) background = kwargs.pop('background', None) super(ImageView, self).__init__(*args, **kwargs) self.setCursor(Qt.OpenHandCursor) self.setBackground(background) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setRenderHints(QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform) self.setCacheMode(self.CacheBackground) self.setViewportUpdateMode(self.SmartViewportUpdate) self._item = QGraphicsPixmapItem() # 放置图像 self._item.setFlags(QGraphicsPixmapItem.ItemIsFocusable | QGraphicsPixmapItem.ItemIsMovable) self._scene = QGraphicsScene(self) # 场景 self.setScene(self._scene) self._scene.addItem(self._item) rect = QApplication.instance().desktop().availableGeometry(self) self.resize(int(rect.width() * 2 / 3), int(rect.height() * 2 / 3)) self.pixmap = None self._delta = 0.1 # 缩放 self.setPixmap(image) def setBackground(self, color): """设置背景颜色 :param color: 背景颜色 :type color: QColor or str or GlobalColor """ if isinstance(color, QColor): self.setBackgroundBrush(color) elif isinstance(color, (str, Qt.GlobalColor)): color = QColor(color) if color.isValid(): self.setBackgroundBrush(color) def setPixmap(self, pixmap, fitIn=True): """加载图片 :param pixmap: 图片或者图片路径 :param fitIn: 是否适应 :type pixmap: QPixmap or QImage or str :type fitIn: bool """ if isinstance(pixmap, QPixmap): self.pixmap = pixmap elif isinstance(pixmap, QImage): self.pixmap = QPixmap.fromImage(pixmap) elif isinstance(pixmap, str) and os.path.isfile(pixmap): self.pixmap = QPixmap(pixmap) else: return self._item.setPixmap(self.pixmap) self._item.update() self.setSceneDims() if fitIn: self.fitInView( QRectF(self._item.pos(), QSizeF(self.pixmap.size())), Qt.KeepAspectRatio) self.update() def setSceneDims(self): if not self.pixmap: return self.setSceneRect( QRectF(QPointF(0, 0), QPointF(self.pixmap.width(), self.pixmap.height()))) def fitInView(self, rect, flags=Qt.IgnoreAspectRatio): """剧中适应 :param rect: 矩形范围 :param flags: :return: """ if not self.scene() or rect.isNull(): return unity = self.transform().mapRect(QRectF(0, 0, 1, 1)) self.scale(1 / unity.width(), 1 / unity.height()) viewRect = self.viewport().rect() sceneRect = self.transform().mapRect(rect) x_ratio = viewRect.width() / sceneRect.width() y_ratio = viewRect.height() / sceneRect.height() if flags == Qt.KeepAspectRatio: x_ratio = y_ratio = min(x_ratio, y_ratio) elif flags == Qt.KeepAspectRatioByExpanding: x_ratio = y_ratio = max(x_ratio, y_ratio) self.scale(x_ratio, y_ratio) self.centerOn(rect.center()) def wheelEvent(self, event): if event.angleDelta().y() > 0: self.zoomIn() else: self.zoomOut() def zoomIn(self): """放大""" self.zoom(1 + self._delta) def zoomOut(self): """缩小""" self.zoom(1 - self._delta) def zoom(self, factor): """缩放 :param factor: 缩放的比例因子 """ _factor = self.transform().scale(factor, factor).mapRect(QRectF(0, 0, 1, 1)).width() if _factor < 0.07 or _factor > 100: # 防止过大过小 return self.scale(factor, factor)
def picShow(self,number): self.pic = QGraphicsScene() self.pic.addPixmap(QPixmap('food_pic/'+str(number)+'.jpg')) return self.pic
def invalidateViewports(self, sceneRectF): """Call invalidate on the intersection of all observing viewport-rects and rectF.""" sceneRectF = sceneRectF if sceneRectF.isValid() else self.sceneRect() for view in self.views(): QGraphicsScene.invalidate( self, sceneRectF.intersected(view.viewportRect()))
def __init__(self, parent=None): QGraphicsView.__init__(self, parent) self.setScene(QGraphicsScene())
class QtImageViewer(QGraphicsView): """ PyQt image viewer widget for a QPixmap in a QGraphicsView scene with mouse zooming and panning. Displays a QImage or QPixmap (QImage is internally converted to a QPixmap). To display any other image format, you must first convert it to a QImage or QPixmap. Some useful image format conversion utilities: qimage2ndarray: NumPy ndarray <==> QImage (https://github.com/hmeine/qimage2ndarray) ImageQt: PIL Image <==> QImage (https://github.com/python-pillow/Pillow/blob/master/PIL/ImageQt.py) Mouse interaction: Left mouse button drag: Pan image. Right mouse button drag: Zoom box. Right mouse button doubleclick: Zoom to show entire image. """ # Mouse button signals emit image scene (x, y) coordinates. # !!! For image (row, column) matrix indexing, row = y and column = x. leftMouseButtonPressed = pyqtSignal(float, float) rightMouseButtonPressed = pyqtSignal(float, float) leftMouseButtonReleased = pyqtSignal(float, float) rightMouseButtonReleased = pyqtSignal(float, float) leftMouseButtonDoubleClicked = pyqtSignal(float, float) rightMouseButtonDoubleClicked = pyqtSignal(float, float) def __init__(self): QGraphicsView.__init__(self) # Image is displayed as a QPixmap in a QGraphicsScene attached to this QGraphicsView. self.scene = QGraphicsScene() self.setScene(self.scene) # Store a local handle to the scene's current image pixmap. self._pixmapHandle = None # Image aspect ratio mode. # !!! ONLY applies to full image. Aspect ratio is always ignored when zooming. # Qt.IgnoreAspectRatio: Scale image to fit viewport. # Qt.KeepAspectRatio: Scale image to fit inside viewport, preserving aspect ratio. # Qt.KeepAspectRatioByExpanding: Scale image to fill the viewport, preserving aspect ratio. self.aspectRatioMode = Qt.KeepAspectRatio # Scroll bar behaviour. # Qt.ScrollBarAlwaysOff: Never shows a scroll bar. # Qt.ScrollBarAlwaysOn: Always shows a scroll bar. # Qt.ScrollBarAsNeeded: Shows a scroll bar only when zoomed. self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) # Stack of QRectF zoom boxes in scene coordinates. self.zoomStack = [] # Flags for enabling/disabling mouse interaction. self.canZoom = True self.canPan = True def hasImage(self): """ Returns whether or not the scene contains an image pixmap. """ return self._pixmapHandle is not None def clearImage(self): """ Removes the current image pixmap from the scene if it exists. """ if self.hasImage(): self.scene.removeItem(self._pixmapHandle) self._pixmapHandle = None def pixmap(self): """ Returns the scene's current image pixmap as a QPixmap, or else None if no image exists. :rtype: QPixmap | None """ if self.hasImage(): return self._pixmapHandle.pixmap() return None def image(self): """ Returns the scene's current image pixmap as a QImage, or else None if no image exists. :rtype: QImage | None """ if self.hasImage(): return self._pixmapHandle.pixmap().toImage() return None def setImage(self, image): """ Set the scene's current image pixmap to the input QImage or QPixmap. Raises a RuntimeError if the input image has type other than QImage or QPixmap. :type image: QImage | QPixmap """ if type(image) is QPixmap: pixmap = image elif type(image) is QImage: pixmap = QPixmap.fromImage(image) else: raise RuntimeError( "ImageViewer.setImage: Argument must be a QImage or QPixmap.") if self.hasImage(): self._pixmapHandle.setPixmap(pixmap) else: self._pixmapHandle = self.scene.addPixmap(pixmap) self.setSceneRect(QRectF( pixmap.rect())) # Set scene size to image size. self.updateViewer() def loadImageFromFile(self, fileName=""): """ Load an image from file. Without any arguments, loadImageFromFile() will popup a file dialog to choose the image file. With a fileName argument, loadImageFromFile(fileName) will attempt to load the specified image file directly. """ if len(fileName) == 0: if QT_VERSION_STR[0] == '4': fileName = QFileDialog.getOpenFileName(self, "Open image file.") elif QT_VERSION_STR[0] == '5': fileName, dummy = QFileDialog.getOpenFileName( self, "Open image file.") if len(fileName) and os.path.isfile(fileName): image = QImage(fileName) self.setImage(image) def updateViewer(self): """ Show current zoom (if showing entire image, apply current aspect ratio mode). """ if not self.hasImage(): return if len(self.zoomStack) and self.sceneRect().contains( self.zoomStack[-1]): self.fitInView(self.zoomStack[-1], Qt.IgnoreAspectRatio ) # Show zoomed rect (ignore aspect ratio). else: self.zoomStack = [ ] # Clear the zoom stack (in case we got here because of an invalid zoom). self.fitInView( self.sceneRect(), self.aspectRatioMode ) # Show entire image (use current aspect ratio mode). def resizeEvent(self, event): """ Maintain current zoom on resize. """ self.updateViewer() def mousePressEvent(self, event): """ Start mouse pan or zoom mode. """ scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: if self.canPan: self.setDragMode(QGraphicsView.ScrollHandDrag) self.leftMouseButtonPressed.emit(scenePos.x(), scenePos.y()) elif event.button() == Qt.RightButton: if self.canZoom: self.setDragMode(QGraphicsView.RubberBandDrag) self.rightMouseButtonPressed.emit(scenePos.x(), scenePos.y()) QGraphicsView.mousePressEvent(self, event) def mouseReleaseEvent(self, event): """ Stop mouse pan or zoom mode (apply zoom if valid). """ QGraphicsView.mouseReleaseEvent(self, event) scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: self.setDragMode(QGraphicsView.NoDrag) self.leftMouseButtonReleased.emit(scenePos.x(), scenePos.y()) elif event.button() == Qt.RightButton: if self.canZoom: viewBBox = self.zoomStack[-1] if len( self.zoomStack) else self.sceneRect() selectionBBox = self.scene.selectionArea().boundingRect( ).intersected(viewBBox) self.scene.setSelectionArea( QPainterPath()) # Clear current selection area. if selectionBBox.isValid() and (selectionBBox != viewBBox): self.zoomStack.append(selectionBBox) self.updateViewer() self.setDragMode(QGraphicsView.NoDrag) self.rightMouseButtonReleased.emit(scenePos.x(), scenePos.y()) def mouseDoubleClickEvent(self, event): """ Show entire image. """ scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: self.leftMouseButtonDoubleClicked.emit(scenePos.x(), scenePos.y()) elif event.button() == Qt.RightButton: if self.canZoom: self.zoomStack = [] # Clear zoom stack. self.updateViewer() self.rightMouseButtonDoubleClicked.emit(scenePos.x(), scenePos.y()) QGraphicsView.mouseDoubleClickEvent(self, event)
@perf_timer("MyWidget2.paintEvent()") def paintEvent(self, ev: QtGui.QPaintEvent): painter = QPainter(self) rects = [] for i in range(data_range): rects.append( QRectF(self.df['x'][i], self.df['y'][i], self.df['width'][i], self.df['height'][i])) painter.drawRects(rects) class MyPathItem(QGraphicsPathItem): def __init__(self, parent=None): QGraphicsPathItem.__init__(self, parent) if __name__ == '__main__': app = QApplication([]) view = QGraphicsView() view.resize(640, 480) scene = QGraphicsScene() view.setScene(scene) view.show() app.exec()
class Ui_Dialog(QMessageBox): def picShow(self,number): self.pic = QGraphicsScene() self.pic.addPixmap(QPixmap('food_pic/'+str(number)+'.jpg')) return self.pic def messengerSelect1(self): _translate = QtCore.QCoreApplication.translate global a,table_count,cal_sum selectBut = QtWidgets.QMessageBox.question(self ,"Select Food","Do you choose this food?",QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No) if selectBut == QtWidgets.QMessageBox.Yes: if ((cal_sum + cal_total[0+((bar_buttom-1)*4)])>cal_limit): QtWidgets.QMessageBox.warning(self,"Calories Alert","Overweight calories",QtWidgets.QMessageBox.Cancel) elif (table_count == 10): QtWidgets.QMessageBox.warning(self,"Food list Alert","Overflow Food",QtWidgets.QMessageBox.Cancel) else: self.tableWidget.setItem(table_count,0,QtWidgets.QTableWidgetItem(a[0+((bar_buttom-1)*4)])) self.tableWidget.setItem(table_count,1,QtWidgets.QTableWidgetItem(str(cal_total[0+((bar_buttom-1)*4)]))) cal_sum = cal_sum + cal_total[0+((bar_buttom-1)*4)] self.CalTotal.setText(_translate("Dialog", str(cal_sum))) table_count += 1 else: pass def messengerSelect2(self): _translate = QtCore.QCoreApplication.translate global a,table_count,cal_sum selectBut = QtWidgets.QMessageBox.question(self ,"Select Food","Do you choose this food?",QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No) if selectBut == QtWidgets.QMessageBox.Yes: if ((cal_sum + cal_total[1+((bar_buttom-1)*4)])>cal_limit): QtWidgets.QMessageBox.warning(self,"Calories Alert","Over-nutrition",QtWidgets.QMessageBox.Cancel) elif (table_count == 10): QtWidgets.QMessageBox.warning(self,"Food list Alert","Shouldn't choose this food",QtWidgets.QMessageBox.Cancel) else: self.tableWidget.setItem(table_count,0,QtWidgets.QTableWidgetItem(a[1+((bar_buttom-1)*4)])) self.tableWidget.setItem(table_count,1,QtWidgets.QTableWidgetItem(str(cal_total[1+((bar_buttom-1)*4)]))) cal_sum = cal_sum + cal_total[1+((bar_buttom-1)*4)] self.CalTotal.setText(_translate("Dialog", str(cal_sum))) table_count += 1 else: pass def messengerSelect3(self): _translate = QtCore.QCoreApplication.translate global a,table_count,cal_sum selectBut = QtWidgets.QMessageBox.question(self ,"Select Food","Do you choose this food?",QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No) if selectBut == QtWidgets.QMessageBox.Yes: if ((cal_sum + cal_total[2+((bar_buttom-1)*4)])>cal_limit): QtWidgets.QMessageBox.warning(self,"Calories Alert","Overweight calories",QtWidgets.QMessageBox.Cancel) elif (table_count == 10): QtWidgets.QMessageBox.warning(self,"Food list Alert","Overflow Food",QtWidgets.QMessageBox.Cancel) else: self.tableWidget.setItem(table_count,0,QtWidgets.QTableWidgetItem(a[2+((bar_buttom-1)*4)])) self.tableWidget.setItem(table_count,1,QtWidgets.QTableWidgetItem(str(cal_total[2+((bar_buttom-1)*4)]))) cal_sum = cal_sum + cal_total[2+((bar_buttom-1)*4)] self.CalTotal.setText(_translate("Dialog", str(cal_sum))) table_count += 1 else: pass def messengerSelect4(self): _translate = QtCore.QCoreApplication.translate global a,table_count,cal_sum selectBut = QtWidgets.QMessageBox.question(self ,"Select Food","Do you choose this food?",QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No) if selectBut == QtWidgets.QMessageBox.Yes: if ((cal_sum + cal_total[3+((bar_buttom-1)*4)])>cal_limit): QtWidgets.QMessageBox.warning(self,"Calories Alert","Overweight calories",QtWidgets.QMessageBox.Cancel) elif (table_count == 10): QtWidgets.QMessageBox.warning(self,"Food list Alert","Overflow Food",QtWidgets.QMessageBox.Cancel) else: self.tableWidget.setItem(table_count,0,QtWidgets.QTableWidgetItem(a[3+((bar_buttom-1)*4)])) self.tableWidget.setItem(table_count,1,QtWidgets.QTableWidgetItem(str(cal_total[3+((bar_buttom-1)*4)]))) cal_sum = cal_sum + cal_total[3+((bar_buttom-1)*4)] self.CalTotal.setText(_translate("Dialog", str(cal_sum))) table_count += 1 else: pass def checkLen(self): global len_food mydb = mysql.connector.connect( converter_class=MyConverter, host="localhost", user="******", passwd="1234", database="project4c", port = 3306 ) mycursor = mydb.cursor() mycursor.execute("SELECT food_name FROM food") myresult = mycursor.fetchall() a = [] for food in myresult: for fooddetail in food: a.append(fooddetail) mydb.close() len_food = int((len(a)) / 4) if ((int(len(a)) % 4) != 0): len_food += 1 def calTolist(self): global cal_total mydb = mysql.connector.connect( converter_class=MyConverter, host="34.80.120.194", user="******", passwd="@Stang1996", database="project4c", port = 3306 ) mycursor = mydb.cursor() mycursor.execute("SELECT cal FROM food ORDER BY food_id ASC") myresult = mycursor.fetchall() for cal in myresult: for caldetail in cal: cal_total.append(caldetail) def BackBut(self): _translate = QtCore.QCoreApplication.translate global bar_buttom,a if (bar_buttom > 1): bar_buttom -= 1 self.food_1.setText(_translate("Dialog", a[0+((bar_buttom-1)*4)])) self.food_2.setText(_translate("Dialog", a[1+((bar_buttom-1)*4)])) self.food_3.setText(_translate("Dialog", a[2+((bar_buttom-1)*4)])) self.food_4.setText(_translate("Dialog", a[3+((bar_buttom-1)*4)])) self.graphicsView.setScene(self.picShow(1+(bar_buttom-1)*4)) self.graphicsView_2.setScene(self.picShow(2+(bar_buttom-1)*4)) self.graphicsView_3.setScene(self.picShow(3+(bar_buttom-1)*4)) self.graphicsView_4.setScene(self.picShow(4+(bar_buttom-1)*4)) def NextBut(self): _translate = QtCore.QCoreApplication.translate global bar_buttom,len_food,a self.checkLen() if (bar_buttom < len_food): bar_buttom += 1 self.food_1.setText(_translate("Dialog", a[0+((bar_buttom-1)*4)])) self.food_2.setText(_translate("Dialog", "x "+a[1+((bar_buttom-1)*4)])) self.food_3.setText(_translate("Dialog", a[2+((bar_buttom-1)*4)])) self.food_4.setText(_translate("Dialog", a[3+((bar_buttom-1)*4)])) self.graphicsView.setScene(self.picShow(1+(bar_buttom-1)*4)) self.graphicsView_2.setScene(self.picShow(2+(bar_buttom-1)*4)) self.graphicsView_3.setScene(self.picShow(3+(bar_buttom-1)*4)) self.graphicsView_4.setScene(self.picShow(4+(bar_buttom-1)*4)) def databaseText(self): _translate = QtCore.QCoreApplication.translate global bar_buttom,cal_sum mydb = mysql.connector.connect( converter_class=MyConverter, host="34.80.120.194", user="******", passwd="@Stang1996", database="project4c", port = 3306 ) mycursor = mydb.cursor() mycursor.execute("SELECT food_name FROM food") myresult = mycursor.fetchall() global a for food in myresult: for fooddetail in food: a.append(fooddetail) mydb.close() self.calTolist() self.food_1.setText(_translate("Dialog", a[0])) self.food_2.setText(_translate("Dialog", a[1])) self.food_3.setText(_translate("Dialog", a[2])) self.food_4.setText(_translate("Dialog", a[3])) self.CalTotal.setText(_translate("Dialog", str(cal_sum))) self.graphicsView.setScene(self.picShow(1)) self.graphicsView_2.setScene(self.picShow(2)) self.graphicsView_3.setScene(self.picShow(3)) self.graphicsView_4.setScene(self.picShow(4)) def clearBut(self): _translate = QtCore.QCoreApplication.translate global cal_sum,table_count yonBut = QtWidgets.QMessageBox.warning(self ,"Select Food","Do you choose this food?",QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No) if yonBut == QtWidgets.QMessageBox.Yes : cal_sum = 0.0 i = 0 for i in range(int(table_count)): self.tableWidget.setItem(i,0,QtWidgets.QTableWidgetItem()) self.tableWidget.setItem(i,1,QtWidgets.QTableWidgetItem()) table_count = 0 self.CalTotal.setText(_translate("Dialog", str(cal_sum))) def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(806, 675) self.label_welcome = QtWidgets.QLabel(Dialog) self.label_welcome.setGeometry(QtCore.QRect(56, 20, 161, 51)) font = QtGui.QFont() font.setPointSize(24) self.label_welcome.setFont(font) self.label_welcome.setObjectName("label_welcome") self.user_name = QtWidgets.QLabel(Dialog) self.user_name.setGeometry(QtCore.QRect(220, 20, 301, 51)) font = QtGui.QFont() font.setPointSize(24) self.user_name.setFont(font) self.user_name.setObjectName("user_name") self.label_select = QtWidgets.QLabel(Dialog) self.label_select.setGeometry(QtCore.QRect(60, 80, 371, 31)) font = QtGui.QFont() font.setPointSize(14) self.label_select.setFont(font) self.label_select.setObjectName("label_select") self.backButton = QtWidgets.QPushButton(Dialog) self.backButton.setGeometry(QtCore.QRect(30, 630, 89, 25)) self.backButton.setObjectName("backButton") self.backButton.clicked.connect(self.BackBut) self.nextButton = QtWidgets.QPushButton(Dialog) self.nextButton.setGeometry(QtCore.QRect(430, 630, 89, 25)) self.nextButton.setObjectName("nextButton") self.nextButton.clicked.connect(self.NextBut) self.graphicsView = QtWidgets.QGraphicsView(Dialog) self.graphicsView.setGeometry(QtCore.QRect(20, 130, 241, 171)) self.graphicsView.setObjectName("graphicsView") self.graphicsView_2 = QtWidgets.QGraphicsView(Dialog) self.graphicsView_2.setGeometry(QtCore.QRect(280, 130, 241, 171)) self.graphicsView_2.setObjectName("graphicsView_2") self.select_1 = QtWidgets.QPushButton(Dialog) self.select_1.setGeometry(QtCore.QRect(100, 340, 89, 25)) self.select_1.setObjectName("select_1") self.graphicsView_3 = QtWidgets.QGraphicsView(Dialog) self.graphicsView_3.setGeometry(QtCore.QRect(20, 380, 241, 171)) self.graphicsView_3.setObjectName("graphicsView_3") self.graphicsView_4 = QtWidgets.QGraphicsView(Dialog) self.graphicsView_4.setGeometry(QtCore.QRect(280, 380, 241, 171)) self.graphicsView_4.setObjectName("graphicsView_4") self.select_2 = QtWidgets.QPushButton(Dialog) self.select_2.setGeometry(QtCore.QRect(360, 340, 89, 25)) self.select_2.setObjectName("select_2") self.select_3 = QtWidgets.QPushButton(Dialog) self.select_3.setGeometry(QtCore.QRect(100, 590, 89, 25)) self.select_3.setObjectName("select_3") self.select_4 = QtWidgets.QPushButton(Dialog) self.select_4.setGeometry(QtCore.QRect(360, 590, 89, 25)) self.select_4.setObjectName("select_4") self.select_1.clicked.connect(self.messengerSelect1) self.select_2.clicked.connect(self.messengerSelect2) self.select_3.clicked.connect(self.messengerSelect3) self.select_4.clicked.connect(self.messengerSelect4) self.food_1 = QtWidgets.QLabel(Dialog) self.food_1.setGeometry(QtCore.QRect(30, 310, 221, 20)) self.food_1.setObjectName("food_1") self.food_3 = QtWidgets.QLabel(Dialog) self.food_3.setGeometry(QtCore.QRect(40, 560, 221, 20)) self.food_3.setObjectName("food_3") self.food_2 = QtWidgets.QLabel(Dialog) self.food_2.setGeometry(QtCore.QRect(300, 310, 221, 20)) self.food_2.setObjectName("food_2") self.food_4 = QtWidgets.QLabel(Dialog) self.food_4.setGeometry(QtCore.QRect(300, 560, 221, 20)) self.food_4.setObjectName("food_4") self.confirmButton = QtWidgets.QPushButton(Dialog) self.confirmButton.setGeometry(QtCore.QRect(540, 570, 89, 61)) self.confirmButton.setObjectName("confirmButton") self.clearButtom = QtWidgets.QPushButton(Dialog) self.clearButtom.setGeometry(QtCore.QRect(700, 570, 89, 61)) self.clearButtom.setObjectName("clearButtom") self.clearButtom.clicked.connect(self.clearBut) self.label_welcome_2 = QtWidgets.QLabel(Dialog) self.label_welcome_2.setGeometry(QtCore.QRect(540, 490, 91, 51)) font = QtGui.QFont() font.setPointSize(18) self.label_welcome_2.setFont(font) self.label_welcome_2.setObjectName("label_welcome_2") self.label_welcome_3 = QtWidgets.QLabel(Dialog) self.label_welcome_3.setGeometry(QtCore.QRect(710, 490, 61, 51)) font = QtGui.QFont() font.setPointSize(18) self.label_welcome_3.setFont(font) self.label_welcome_3.setObjectName("label_welcome_3") self.CalTotal = QtWidgets.QLabel(Dialog) self.CalTotal.setGeometry(QtCore.QRect(620, 490, 81, 51)) font = QtGui.QFont() font.setPointSize(18) self.CalTotal.setFont(font) self.CalTotal.setObjectName("CalTotal") self.label_welcome_5 = QtWidgets.QLabel(Dialog) self.label_welcome_5.setGeometry(QtCore.QRect(530, 40, 111, 51)) font = QtGui.QFont() font.setPointSize(18) self.label_welcome_5.setFont(font) self.label_welcome_5.setObjectName("label_welcome_5") self.Cal_Limit = QtWidgets.QLabel(Dialog) self.Cal_Limit.setGeometry(QtCore.QRect(640, 40, 81, 51)) font = QtGui.QFont() font.setPointSize(18) self.Cal_Limit.setFont(font) self.Cal_Limit.setObjectName("Cal_Limit") self.label_welcome_7 = QtWidgets.QLabel(Dialog) self.label_welcome_7.setGeometry(QtCore.QRect(730, 40, 61, 51)) font = QtGui.QFont() font.setPointSize(18) self.label_welcome_7.setFont(font) self.label_welcome_7.setObjectName("label_welcome_7") self.tableWidget = QtWidgets.QTableWidget(Dialog) self.tableWidget.setGeometry(QtCore.QRect(540, 140, 241, 351)) self.tableWidget.setMaximumSize(QtCore.QSize(241, 351)) self.tableWidget.setRowCount(10) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(2) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item) self.databaseText() self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): global cal_limit _translate = QtCore.QCoreApplication.translate self.nextButton.setText(_translate("Dialog", "Next >")) self.label_welcome.setText(_translate("Dialog", "Welcome! ")) self.label_select.setText(_translate("Dialog", "What would you like to order please? ")) self.backButton.setText(_translate("Dialog", "< Back")) self.select_1.setText(_translate("Dialog", "Select")) self.select_2.setText(_translate("Dialog", "Select")) self.select_3.setText(_translate("Dialog", "Select")) self.select_4.setText(_translate("Dialog", "Select")) self.confirmButton.setText(_translate("Dialog", "Confirm(s)")) self.clearButtom.setText(_translate("Dialog", "Clear")) self.label_welcome_2.setText(_translate("Dialog", "Total :")) self.label_welcome_3.setText(_translate("Dialog", "kCal")) self.label_welcome_5.setText(_translate("Dialog", "Cal Limit :")) self.Cal_Limit.setText(_translate("Dialog", str(cal_limit))) self.label_welcome_7.setText(_translate("Dialog", "kCal")) item = self.tableWidget.horizontalHeaderItem(0) item.setText(_translate("Dialog", "Food")) item = self.tableWidget.horizontalHeaderItem(1) item.setText(_translate("Dialog", "Calorie(s)"))
def __init__(self, x, y, w, h): QGraphicsScene.__init__(self, x, y, w, h)
def initUI(self, path_to_options): """ initialize the view-scene graphic environment """ self.scene = QGraphicsScene() #self.scene.setSceneRect(0, 0, 640, 480) self.view = QGraphicsViewExtend(self.scene) self.view.setSceneRect(QRectF(self.view.viewport().rect())) self.view.setSceneRect(QRectF(0, 0, 850, 900)) self.view.setRenderHint(QPainter.Antialiasing) layout = QGridLayout() layout.addWidget(self.view) self.setLayout(layout) self.setBackgroundColor(QColor('green')) # special properties self.svgCardsPath = "../cards" self.cardsGraphItems = [] #holds all the cards items self.defInsertionPos = QPointF(0, 0) self.defAngle = 0 self.defScale = 0.5 self.deckBackSVG = 'back_1' self.numOfPlayers = 4 self.playersHandsPos = [(75, 50, 0), (210, 50, 180), (680, 50, 0), (210, 385, 0)] #(x,y,angle) self.defHandSpacing = 24 self.midCards = [] self.options_file_path = path_to_options # Card fields pen = QPen() brush = QBrush() self.scene.addRect(QRectF(200, 230, 100, 80), pen, brush) self.scene.addRect(QRectF(200 + 120, 230, 100, 80), pen, brush) self.scene.addRect(QRectF(200 + 120 * 2, 230, 100, 80), pen, brush) self.scene.addRect(QRectF(200 + 120 * 3, 230, 100, 80), pen, brush) # Player Names self.player1_label = self.addPlayerLabel(425, 350, "Player 1") self.player2_label = self.addPlayerLabel(0, 240, "Player 2") self.player3_label = self.addPlayerLabel(425, 20, "Player 3") self.player4_label = self.addPlayerLabel(782, 240, "Player 4") self.card1_label = self.addPlayerLabel(200, 210, "") self.card2_label = self.addPlayerLabel(200 + 120, 210, "") self.card3_label = self.addPlayerLabel(200 + 120 * 2, 210, "") self.card4_label = self.addPlayerLabel(200 + 120 * 3, 210, "") self.card_label_l = [ self.card1_label, self.card2_label, self.card3_label, self.card4_label ] self.card_label_pla = [ self.player1_label, self.player2_label, self.player3_label, self.player4_label ] self.play_1_state = self.addPlayerLabel(200, 250, "") self.play_2_state = self.addPlayerLabel(200 + 120, 250, "") self.play_3_state = self.addPlayerLabel(200 + 120 * 2, 250, "") self.play_4_state = self.addPlayerLabel(200 + 120 * 3, 250, "") self.game_indicator = self.addPlayerLabel(650, 5, "Game: ") self.mode_label = self.addPlayerLabel(150, 5, "Mode: ") playbtn = QPushButton('Start', self) playbtn.resize(50, 32) playbtn.move(10, 10) playbtn.clicked.connect(self.start_clicked) options = QPushButton('Options', self) options.resize(80, 32) options.move(65, 10) options.clicked.connect(self.options_clicked) nextRound = QPushButton('nextRound', self) nextRound.resize(80, 32) nextRound.move(150, 10) nextRound.setVisible(False) nextRound.clicked.connect(self.nextRound_clicked) self.scene.addWidget(playbtn) self.scene.addWidget(nextRound) self.scene.addWidget(options) self.my_game = None # Testing tree: self.my_tree = None # Storing game_play self.game_play = {} self.corrString = "" # emit signal: self.server_receivedSig.connect(self.parseClient) ### Client stuff: self.clientTimer = QTimer(self) self.tcpSocket = None self.games_played = 0 self.reset_client() self.server_thread = None
# Parent widget. widget = QGraphicsWidget() layout = QGraphicsLinearLayout(Qt.Vertical, widget) layout.addItem(editProxy) layout.addItem(buttonProxy) widget.setLayout(layout) p1 = Pixmap(QPixmap(':/digikam.png')) p2 = Pixmap(QPixmap(':/akregator.png')) p3 = Pixmap(QPixmap(':/accessories-dictionary.png')) p4 = Pixmap(QPixmap(':/k3b.png')) p5 = Pixmap(QPixmap(':/help-browser.png')) p6 = Pixmap(QPixmap(':/kchart.png')) scene = QGraphicsScene(0, 0, 400, 300) scene.setBackgroundBrush(scene.palette().window()) scene.addItem(widget) scene.addItem(boxProxy) scene.addItem(p1) scene.addItem(p2) scene.addItem(p3) scene.addItem(p4) scene.addItem(p5) scene.addItem(p6) machine = QStateMachine() state1 = QState(machine) state2 = QState(machine) state3 = QState(machine) machine.setInitialState(state1)
class MainController(QObject): appStart = pyqtSignal() newCommand = pyqtSignal(tuple) def __init__(self): super(MainController, self).__init__() self.ser = Serial(WIFLY_SERIAL_PORT, WIFLY_BAUD_RATE) self.wiflyReceiver = WiflyReceiver(self.ser) self.wiflySender = WiflySender(self.ser) self.rover = Rover() self.mainWidget = MainWidget() self.wiflyReceiverThread = QThread() self.wiflyReceiver.moveToThread(self.wiflyReceiverThread) self.wiflySenderThread = QThread() self.wiflySender.moveToThread(self.wiflySenderThread) self.simState = SIMULATION_STATE_PHASE_1 self.simTimer = QTimer() self.simTimer.setSingleShot(True) self.wiflyReceiver.msgReceived.connect(self.mainWidget.appendMsg) self.wiflyReceiver.msgReceived.connect(self.rover.processData) self.newCommand.connect(self.wiflySender.sendMsg) self.appStart.connect(self.wiflyReceiver.processMsg) self.mainWidget.ui.gearSlider.valueChanged.connect( self.manualGearChange) self.mainWidget.ui.upButton.clicked.connect(self.manualMoveForward) self.mainWidget.ui.downButton.clicked.connect(self.manualMoveBackward) self.mainWidget.ui.leftButton.clicked.connect(self.manualMoveLeft) self.mainWidget.ui.rightButton.clicked.connect(self.manualMoveRight) self.mainWidget.ui.brakeButton.clicked.connect(self.manualStop) self.mainWidget.ui.simulationButton.clicked.connect( self.simulationStart) self.rover.newRoverPosition.connect(self.drawRover) self.rover.newWallDetected.connect(self.drawNewWall) self.simTimer.timeout.connect(self.simulationUpdate) self.mapScene = QGraphicsScene(0, 0, WORLD_X / CANVAS_RATIO, WORLD_Y / CANVAS_RATIO) self.mainWidget.ui.mappingGraphicsView.setScene(self.mapScene) self.roverRect = QGraphicsRectItem() self.mapScene.addItem(self.roverRect) """ rect1 = QGraphicsRectItem() rect2 = QGraphicsRectItem() self.mapScene.addItem(rect1) self.mapScene.addItem(rect2) rect1.setRect(100, 100, 20, 40) rect2.setRect(100, 100, 20, 40) #rect.moveBy(10, 50) rect2.setTransformOriginPoint(100, 100) rect2.setRotation(-10) print rect1.rect().center() #print rect2.transformOriginPoint().x(), rect2.transformOriginPoint().y() """ @pyqtSlot(tuple, tuple) def drawNewWall(self, wallFront, wallRear): pFront = QGraphicsRectItem(wallFront[0] / CANVAS_RATIO, wallFront[1] / CANVAS_RATIO, DOT_SIZE, DOT_SIZE) pRear = QGraphicsRectItem(wallRear[0] / CANVAS_RATIO, wallRear[1] / CANVAS_RATIO, DOT_SIZE, DOT_SIZE) self.mapScene.addItem(pFront) self.mapScene.addItem(pRear) @pyqtSlot(tuple, float) def drawRover(self, center, orientation): self.roverRect.setRect((center[0] - ROVER_WIDTH / 2) / CANVAS_RATIO, (center[1] - ROVER_LENGTH / 2) / CANVAS_RATIO, ROVER_WIDTH / CANVAS_RATIO, ROVER_LENGTH / CANVAS_RATIO) self.roverRect.setTransformOriginPoint(center[0] / CANVAS_RATIO, center[1] / CANVAS_RATIO) self.roverRect.setRotation(math.degrees(-orientation)) @pyqtSlot() def manualGearChange(self): gear = self.mainWidget.ui.gearSlider.value() self.mainWidget.ui.gearLcdNumber.display(gear) self.rover.roverGear = gear self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) @pyqtSlot() def manualMoveForward(self): self.rover.roverDirection = ROVER_DIRECTION_FORWARD self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) @pyqtSlot() def manualMoveBackward(self): self.rover.roverDirection = ROVER_DIRECTION_BACKWARD self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) @pyqtSlot() def manualMoveLeft(self): self.rover.roverDirection = ROVER_DIRECTION_LEFT self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) @pyqtSlot() def manualMoveRight(self): self.rover.roverDirection = ROVER_DIRECTION_RIGHT self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) @pyqtSlot() def manualStop(self): self.mainWidget.ui.gearSlider.setValue(0) @pyqtSlot() def simulationStart(self): self.simState == SIMULATION_STATE_PHASE_1 self.simTimer.start(5000) @pyqtSlot() def simulationUpdate(self): if self.simState == SIMULATION_STATE_PHASE_1: self.simState = SIMULATION_STATE_PHASE_2 self.rover.roverGear = 2 self.rover.roverDirection = ROVER_DIRECTION_FORWARD self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) self.simTimer.start(16000) elif self.simState == SIMULATION_STATE_PHASE_2: self.simState = SIMULATION_STATE_PHASE_3 self.rover.roverDirection = ROVER_DIRECTION_BACKWARD self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) self.simTimer.start(6100) elif self.simState == SIMULATION_STATE_PHASE_3: self.simState = SIMULATION_STATE_PHASE_4 self.rover.roverDirection = ROVER_DIRECTION_LEFT self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) self.simTimer.start(3500) elif self.simState == SIMULATION_STATE_PHASE_4: self.simState = SIMULATION_STATE_PHASE_5 self.rover.roverDirection = ROVER_DIRECTION_BACKWARD self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) self.simTimer.start(8300) elif self.simState == SIMULATION_STATE_PHASE_5: self.rover.roverGear = 0 self.rover.roverDirection = ROVER_DIRECTION_STOP self.rover.updateMotorCommand() self.newCommand.emit(tuple(self.rover.commandMsg)) def start(self): self.mainWidget.show() self.wiflyReceiverThread.start() self.wiflySenderThread.start() self.appStart.emit()
if __name__ == '__main__': import sys app = QApplication(sys.argv) button1 = QGraphicsRectWidget() button2 = QGraphicsRectWidget() button3 = QGraphicsRectWidget() button4 = QGraphicsRectWidget() button2.setZValue(1) button3.setZValue(2) button4.setZValue(3) scene = QGraphicsScene(0, 0, 300, 300) scene.setBackgroundBrush(Qt.black) scene.addItem(button1) scene.addItem(button2) scene.addItem(button3) scene.addItem(button4) window = QGraphicsView(scene) window.setFrameStyle(0) window.setAlignment(Qt.AlignLeft | Qt.AlignTop) window.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) window.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) machine = QStateMachine() group = QState()
class UiMain(QMainWindow): def __init__(self): super().__init__() ui = Ui_MainWindow() ui.setupUi(self) self.ui = ui self.media_path = "" # Default Show Realtime Video self.showVideo_flag = True self.ui.realtimemode.setChecked(True) self.writeVideo_flag = True self.return_elements = [ "input/input_data:0", "pred_sbbox/concat_2:0", "pred_mbbox/concat_2:0", "pred_lbbox/concat_2:0" ] self.pb_file = "./models/yolov3_visdrone.pb" self.output_path = './output/output.avi' self.counting_path = './output/counting.avi' self.annotation_path = './output/tracker.txt' self.pickle_file_path = './output/tmp.pk' self.num_classes = 12 self.input_size = 416 self.is_on = False ui.browse.clicked.connect(self.browse_file) ui.generate.clicked.connect(self.generate_baseline) ui.start.clicked.connect(self.start_process) ui.pause.setEnabled(False) ui.pause.clicked.connect(self.pause_process) ui.realtimemode.clicked.connect(self.update_realtimemode) def browse_file(self): media_path, media_type = QFileDialog.getOpenFileName( self, "Open Media") if media_path == "": return self.media_path = media_path # Valiate media vid = cv2.VideoCapture(media_path) self.vid = vid if not vid.isOpened(): self.ui.textBrowser.setPlainText("Couldn't open media!") else: self.ui.textBrowser.setPlainText(media_path) self.ui.textBrowser.moveCursor( self.ui.textBrowser.textCursor().End) # Save media info self.total_frame_counter = int(vid.get(cv2.CAP_PROP_FRAME_COUNT)) self.media_fps = vid.get(cv2.CAP_PROP_FPS) self.media_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))) # Sample frame for baseline while True: return_value, frame = vid.read() if return_value == True: frame = cv2.cvtColor( frame, cv2.COLOR_BGR2RGB, ) self.frame = frame break self.update_graphic_viewer(frame) self.generate_baseline() def generate_baseline(self): # Validate if self.media_path == "": self.ui.baseline_message.setText("Please open media first!") return try: self.left_position = int(self.ui.left_position.toPlainText()) self.left_start = int(self.ui.left_start.toPlainText()) self.left_end = int(self.ui.left_end.toPlainText()) self.right_position = int(self.ui.right_position.toPlainText()) self.right_start = int(self.ui.right_start.toPlainText()) self.right_end = int(self.ui.right_end.toPlainText()) self.bottom_position = int(self.ui.bottom_position.toPlainText()) self.bottom_start = int(self.ui.bottom_start.toPlainText()) self.bottom_end = int(self.ui.bottom_end.toPlainText()) except ValueError: self.ui.baseline_message.setText( "Argument Fault! Please input number!") image = self.frame.copy() cv2.line(image, (self.left_position, self.left_start), (self.left_position, self.left_end), (0xFF, 0, 0), 5) cv2.line(image, (self.right_position, self.right_start), (self.right_position, self.right_end), (0, 0xFF, 0), 5) cv2.line(image, (self.bottom_start, self.bottom_position), (self.bottom_end, self.bottom_position), (0, 0, 0xFF), 5) self.update_graphic_viewer(image) def update_graphic_viewer(self, image): showImage = QtGui.QImage(image, image.shape[1], image.shape[0], QtGui.QImage.Format_RGB888) pix = QtGui.QPixmap.fromImage(showImage) item = QGraphicsPixmapItem(pix) # 创建像素图元 self.scene = QGraphicsScene() # 创建场景 self.scene.addItem(item) self.ui.graphicsView.setScene(self.scene) # 将场景添加至视图 ''' Control mutual Status ''' def mutual_control(self, status: bool): self.ui.browse.setEnabled(status) self.ui.generate.setEnabled(status) self.ui.start.setEnabled(status) self.ui.pause.setEnabled(status) self.ui.realtimemode.setEnabled(status) ''' 开始进行图像处理操作 ''' def start_process(self): self.mutual_control(False) self.ui.pause.setEnabled(True) self.compute_thread = WorkThread(window=self) self.compute_thread.update_graphic_viewer.connect( self.update_graphic_viewer) self.compute_thread.update_process_message.connect( self.update_process_message) self.compute_thread.start() def pause_process(self): self.is_on = not self.is_on if self.is_on == True: self.ui.pause.setText('pause') else: self.ui.pause.setText('continue') def update_realtimemode(self): self.showVideo_flag = self.ui.realtimemode.isChecked() def update_process_message(self, message): self.ui.process_message.setText(message)
def upd_image(self): scene = QGraphicsScene() self.graphics_view.setScene(scene) pixmap = QPixmap() pixmap.loadFromData(QByteArray(self.image)) scene.addItem(QGraphicsPixmapItem(pixmap))
class View(QGraphicsView): projections = OrderedDict([ ('Spherical', Proj('+proj=ortho +lat_0=48 +lon_0=17')), ('Mercator', Proj(init='epsg:3395')), ('WGS84', Proj(init='epsg:3857')), ('ETRS89 - LAEA Europe', Proj("+init=EPSG:3035")) ]) def __init__(self, controller): super().__init__() self.controller = controller self.scene = QGraphicsScene(self) self.setScene(self.scene) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setRenderHint(QPainter.Antialiasing) self.proj = 'Spherical' self.ratio, self.offset = 1 / 400, (0, 0) self.display = True self.shapefile = join(controller.path_shapefiles, 'World countries_1.shp') # brush for water and lands self.water_brush = QBrush(QColor(64, 164, 223)) self.land_brush = QBrush(QColor(52, 165, 111)) self.land_pen = QPen(QColor(0, 0, 0)) # draw the map self.polygons = self.scene.createItemGroup(self.draw_polygons()) self.draw_water() # set of graphical nodes self.nodes = set() ## Zoom system def zoom_in(self): self.scale(1.25, 1.25) def zoom_out(self): self.scale(1 / 1.25, 1 / 1.25) def wheelEvent(self, event): self.zoom_in() if event.angleDelta().y() > 0 else self.zoom_out() ## Mouse bindings def mouseMoveEvent(self, event): # sliding the scrollbar with the right-click button if event.buttons() == Qt.RightButton: self.trigger_menu = False offset = self.cursor_pos - event.pos() self.cursor_pos = event.pos() x_value = self.horizontalScrollBar().value() + offset.x() y_value = self.verticalScrollBar().value() + offset.y() self.horizontalScrollBar().setValue(x_value) self.verticalScrollBar().setValue(y_value) super().mouseMoveEvent(event) def mousePressEvent(self, event): # activate rubberband for selection # by default, the rubberband is active for both clicks, we have to # deactivate it explicitly for the right-click if event.buttons() == Qt.LeftButton: self.setDragMode(QGraphicsView.RubberBandDrag) if event.button() == Qt.RightButton: self.cursor_pos = event.pos() super().mousePressEvent(event) ## Drag & Drop system def dragEnterEvent(self, event): if event.mimeData().hasFormat('application/x-dnditemdata'): event.acceptProposedAction() dragMoveEvent = dragEnterEvent def dropEvent(self, event): pos = self.mapToScene(event.pos()) geo_pos = self.to_geographical_coordinates(pos.x(), pos.y()) if event.mimeData().hasFormat('application/x-dnditemdata'): new_node = Node(self.controller, pos) ## Map functions def to_geographical_coordinates(self, x, y): px, py = (x - self.offset[0]) / self.ratio, (self.offset[1] - y) / self.ratio return self.projections[self.proj](px, py, inverse=True) def to_canvas_coordinates(self, longitude, latitude): px, py = self.projections[self.proj](longitude, latitude) return px * self.ratio + self.offset[ 0], -py * self.ratio + self.offset[1] def move_to_geographical_coordinates(self): for node in self.nodes: node.setPos( QPointF(*self.to_canvas_coordinates(node.longitude, node.latitude))) def draw_polygons(self): sf = shapefile.Reader(self.shapefile) polygons = sf.shapes() for polygon in polygons: # convert shapefile geometries into shapely geometries # to extract the polygons of a multipolygon polygon = shapely.geometry.shape(polygon) # if it is a polygon, we use a list to make it iterable if polygon.geom_type == 'Polygon': polygon = [polygon] for land in polygon: qt_polygon = QPolygonF() for lon, lat in land.exterior.coords: px, py = self.to_canvas_coordinates(lon, lat) if px > 1e+10: continue qt_polygon.append(QPointF(px, py)) polygon_item = QGraphicsPolygonItem(qt_polygon) polygon_item.setBrush(self.land_brush) polygon_item.setPen(self.land_pen) polygon_item.setZValue(1) yield polygon_item def draw_water(self): if self.proj in ('Spherical', 'ETRS89 - LAEA Europe'): cx, cy = self.to_canvas_coordinates(17, 48) # if the projection is ETRS89, we need the diameter and not the radius R = 6371000 * self.ratio * (1 if self.proj == 'Spherical' else 2) earth_water = QGraphicsEllipseItem(cx - R, cy - R, 2 * R, 2 * R) earth_water.setZValue(0) earth_water.setBrush(self.water_brush) self.polygons.addToGroup(earth_water) else: # we compute the projected bounds of the Mercator (3395) projection # upper-left corner x and y coordinates: ulc_x, ulc_y = self.to_canvas_coordinates(-180, 84) # lower-right corner x and y coordinates lrc_x, lrc_y = self.to_canvas_coordinates(180, -84.72) # width and height of the map (required for the QRectItem) width, height = lrc_x - ulc_x, lrc_y - ulc_y earth_water = QGraphicsRectItem(ulc_x, ulc_y, width, height) earth_water.setZValue(0) earth_water.setBrush(self.water_brush) self.polygons.addToGroup(earth_water) def show_hide_map(self): self.display = not self.display self.polygons.show() if self.display else self.polygons.hide() def delete_map(self): self.scene.removeItem(self.polygons) def redraw_map(self): self.delete_map() self.polygons = self.scene.createItemGroup(self.draw_polygons()) self.draw_water() # replace the nodes at their geographical location self.move_to_geographical_coordinates()
def __init__(self, conf, defeat): self.config = conf super().__init__() self.setWindowTitle(conf.get_text('victory')) self.setFixedSize(QSize(640, 480)) self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.WindowTitleHint | Qt.FramelessWindowHint) button = QPushButton(conf.get_text('close'), self) button.setCheckable(True) button.setFixedSize(QSize(640, 30)) button.move(0, 450) # noinspection PyUnresolvedReferences button.clicked.connect(self.close) result_output = QTextEdit(self) result_output.setReadOnly(True) result_output.setFixedSize(QSize(640, 200)) result_output.move(0, 250) result_output.setLineWrapMode(QTextEdit.NoWrap) result_output.insertHtml(self.generate_result_text()) gview = QGraphicsView(self) scene = QGraphicsScene() if defeat: img = conf.theme_selected.get_defeat_pixmap() text = conf.get_text('defeat') else: img = conf.theme_selected.get_victory_pixmap() text = conf.get_text('victory') scene.addPixmap(img.scaled(QSize(640, 220))) gview.move(0, 30) gview.setScene(scene) label_title = QLabel(self) label_title.setText(text) label_title.setFixedSize(QSize(640, 30)) label_title.setAlignment(Qt.AlignCenter) label_title.setFont(self.get_font_title())