def _changeForm(self, current, previous): prev_page = self.page_container.currentWidget() next_page = self.page_container.widget(self.list_option.currentRow()) curr_page = str(next_page.objectName()) objs = {'alias_page': self.alias, 'macro_page': self.macro, 'keypad_page': self.keypad, 'account_page': self.accounts, 'trigger_page': self.trigger} form = objs.get(curr_page) if form: form.disableSignal(True) form.loadForm() form.disableSignal(False) # The transition effect works with the image of the previous page and # the image of the next page. To do the image of the next_page correct # we have to force the application of the layout before taking the image. next_page.resize(prev_page.size()) next_page.layout().activate() self._startTransition(QPixmap.grabWidget(prev_page), QPixmap.grabWidget(next_page))
def setCurrentIndex(self, index): """ Set the current shown widget index. """ index = max(min(index, self.count() - 1), 0) if self.__currentIndex == -1: self.layout().setCurrentIndex(index) self.__currentIndex = index return # if not self.animationEnabled(): # self.layout().setCurrentIndex(index) # self.__currentIndex = index # return # else start the animation current = self.__widgets[self.__currentIndex] next_widget = self.__widgets[index] current_pix = QPixmap.grabWidget(current) next_pix = QPixmap.grabWidget(next_widget) with updates_disabled(self): self.__fadeWidget.setPixmap(current_pix) self.__fadeWidget.setPixmap2(next_pix) self.__nextCurrentIndex = index self.__transitionStart()
def main(): app = QApplication(sys.argv) widget = QWidget() QPixmap.grabWidget(widget, 100, 100, 200, 200) widget.show() app.exec_() e = Event() e.capture = False e.daemon = False e.start() while True: if e.is_press and e.is_release: if e.press_cnt == 1: if e.start_x > e.end_x: e.start_x, e.end_x = e.end_x, e.start_x if e.start_y > e.end_y: e.start_y, e.end_y = e.end_y, e.start_y width = e.end_x - e.start_x height = e.end_y - e.start_y f = tempfile.NamedTemporaryFile( prefix='screentshot_', suffix='.png') command = "import -window root -crop '%sx%s+%s+%s' " %( width, height, e.start_x, e.start_y) command += f.name EasyProcess(command).call() im = Image.open(f.name) im.show() break e.stop()
def __outPNG(self): """ To save the profile as png file """ fileName = QFileDialog.getSaveFileName( self.__iface.mainWindow(), QCoreApplication.translate("VDLTools", "Save As"), QCoreApplication.translate("VDLTools", "Profile.png"),"Portable Network Graphics (*.png)") if fileName is not None: QPixmap.grabWidget(self.__printWdg).save(fileName, "PNG")
def grab_widget(self, widget, suffix=None, subdir=None): """Save a widget as a png file : :param widget: the widget to take a screenshot of :param suffix: string to add to the default filename of the image :param subdir: subdirectory of images_path in which to put the image file, defaults to the name of the test class - the name of the png file is the name of the test case, without 'test_' - it is stored in the directory with the same name as the class, without 'test' """ import sys import os from PyQt4 import QtGui from PyQt4.QtGui import QPixmap if not subdir: images_path = os.path.join( self.images_path, self.__class__.__name__.lower()[:-len('Test')]) else: images_path = os.path.join(self.images_path, subdir) if not os.path.exists(images_path): os.makedirs(images_path) # try to move up in the stack until we find a test method for i in range(1, 10): if sys._getframe(i).f_code.co_name.startswith('test'): break test_case_name = sys._getframe(i).f_code.co_name[5:] image_name = '%s.png' % test_case_name if suffix: image_name = '%s_%s.png' % (test_case_name, suffix) widget.adjustSize() widget.repaint() self.process() QtGui.QApplication.flush() inner_pixmap = QPixmap.grabWidget(widget) # # we'll create a label that contains a screenshot of our widget and # take a screenshot of that label, for the sole purpose of adding a border # parent_widget = QtGui.QLabel() parent_widget.setPixmap(inner_pixmap) parent_widget.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Plain) parent_widget.setObjectName('grab_widget_parent') parent_widget.setLineWidth(2) parent_widget.setStyleSheet(""" #grab_widget_parent { border: 2px solid gray; }""") parent_widget.adjustSize() outer_pixmap = QPixmap.grabWidget(parent_widget) outer_pixmap.save(os.path.join(images_path, image_name), 'PNG')
def outPNG(self, iface, wdg, mdl, library): for i in range(0, mdl.rowCount()): if mdl.item(i, 0).data(Qt.CheckStateRole): name = str(mdl.item(i, 2).data(Qt.EditRole)) #return fileName = QFileDialog.getSaveFileName( iface.mainWindow(), "Save As", "Profile of " + name + ".png", "Portable Network Graphics (*.png)") if fileName: if library == "Qwt5" and has_qwt: QPixmap.grabWidget(wdg.plotWdg).save(fileName, "PNG") elif library == "Matplotlib" and has_mpl: wdg.plotWdg.figure.savefig(str(fileName))
def grab_widget(self, widget, suffix=None, subdir=None): """Save a widget as a png file : :param widget: the widget to take a screenshot of :param suffix: string to add to the default filename of the image :param subdir: subdirectory of images_path in which to put the image file, defaults to the name of the test class - the name of the png file is the name of the test case, without 'test_' - it is stored in the directory with the same name as the class, without 'test' """ import sys import os from PyQt4 import QtGui from PyQt4.QtGui import QPixmap if not subdir: images_path = os.path.join(self.images_path, self.__class__.__name__.lower()[:-len('Test')]) else: images_path = os.path.join(self.images_path, subdir) if not os.path.exists(images_path): os.makedirs(images_path) # try to move up in the stack until we find a test method for i in range(1, 10): if sys._getframe(i).f_code.co_name.startswith('test'): break test_case_name = sys._getframe(i).f_code.co_name[5:] image_name = '%s.png'%test_case_name if suffix: image_name = '%s_%s.png'%(test_case_name, suffix) widget.adjustSize() widget.repaint() self.process() QtGui.QApplication.flush() inner_pixmap = QPixmap.grabWidget(widget) # # we'll create a label that contains a screenshot of our widget and # take a screenshot of that label, for the sole purpose of adding a border # parent_widget = QtGui.QLabel() parent_widget.setPixmap(inner_pixmap) parent_widget.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Plain) parent_widget.setObjectName('grab_widget_parent') parent_widget.setLineWidth(2) parent_widget.setStyleSheet(""" #grab_widget_parent { border: 2px solid gray; }""") parent_widget.adjustSize() outer_pixmap = QPixmap.grabWidget(parent_widget) outer_pixmap.save(os.path.join(images_path, image_name), 'PNG')
def eventFilter( self, object, event ): if event.type() == event.MouseButtonPress: if self.isLocked(): return False if event.button() == Qt.MidButton or \ (event.button() == Qt.LeftButton and \ event.modifiers() == Qt.ShiftModifier): index = self.tabBar().tabAt(event.pos()) view = self.widget(index) pixmap = QPixmap.grabWidget(view) drag = QDrag(self) data = QMimeData() data.setText('move view:{}'.format(index)) drag.setMimeData(data) drag.setPixmap(pixmap) drag.exec_() return True return False elif event.type() == event.DragEnter: if ( str(event.mimeData().text()).startswith('move view:') and event.source() != self ): event.acceptProposedAction() return True elif event.type() == event.Drop: text = str(event.mimeData().text()) splt = text.split(':') self.snagViewFromPanel(event.source(), int(splt[1])) return True return False
def show_selector(self): if self.selector != self.stack.currentWidget(): temp_dir = os.path.join(QDir.tempPath(), "ninja-ide") if not os.path.exists(temp_dir): os.mkdir(temp_dir) collected_data = [] current = self.stack.currentIndex() for index in range(self.stack.count()): widget = self.stack.widget(index) if widget == self.selector: continue closable = True if widget == self.splitter: closable = False pixmap = QPixmap.grabWidget(widget, widget.rect()) path = os.path.join(temp_dir, "screen%s.png" % index) pixmap.save(path) if index == current: self.selector.set_preview(index, path) collected_data.insert(0, (index, path, closable)) else: collected_data.append((index, path, closable)) self.selector.set_model(collected_data) else: self.selector.close_selector()
def mousePressEvent( self, event ): # handle an internal move from PyQt4.QtCore import Qt # start a drag event if ( event.button() == Qt.LeftButton and self.dragDropRect().contains( event.pos() ) ): from PyQt4.QtCore import QMimeData from PyQt4.QtGui import QDrag, QPixmap # create the pixmap pixmap = QPixmap.grabWidget( self, self.rect() ) # create the mimedata mimeData = QMimeData() mimeData.setText( 'ItemTitle::%s' % (self.title()) ) # create the drag drag = QDrag(self) drag.setMimeData( mimeData ) drag.setPixmap( pixmap ) drag.setHotSpot( event.pos() ) if ( not drag.exec_() ): self._accordianWidget.emitItemDragFailed(self) event.accept() # determine if the expand/collapse should occur elif ( event.button() == Qt.LeftButton and self.expandCollapseRect().contains( event.pos() ) ): self._clicked = True event.accept() else: event.ignore()
def mousePressEvent(self, event): # handle an internal move # start a drag event if event.button() == Qt.LeftButton and self.dragDropRect().contains( event.pos()): # create the pixmap pixmap = QPixmap.grabWidget(self, self.rect()) # create the mimedata mimeData = QMimeData() mimeData.setText('ItemTitle::%s' % (self.title())) # create the drag drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot(event.pos()) if not drag.exec_(): self._accordianWidget.emitItemDragFailed(self) event.accept() # determine if the expand/collapse should occur elif event.button() == Qt.LeftButton and self.expandCollapseRect( ).contains(event.pos()): self._clicked = True event.accept() else: event.ignore()
def saveWindow(self, fileName=None, fileType=None, window=False): self.repaint() # make sure we are uptodate if window: pixmap = QPixmap.grabWindow(self.winId()) else: pixmap = QPixmap.grabWidget(self) if not fileName: fileTypes = {unicode(QCoreApplication.translate('SubWindow', 'PNG - compressed image')):('png',), unicode(QCoreApplication.translate('SubWindow', 'JPEG - picture')):('jpg', 'jpeg'), unicode(QCoreApplication.translate('SubWindow', 'BMP - uncompressed bitmap')):('bmp',)} filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()]) dlg = QFileDialog(self, QCoreApplication.translate('SubWindow', 'Select name of file to save'), Globals.defaultFolder or '', filters) dlg.setFileMode(QFileDialog.AnyFile) dlg.setAcceptMode(QFileDialog.AcceptSave) if dlg.exec_() != QDialog.Accepted: return tmp = unicode(dlg.selectedFilter()) fileType = tmp[:tmp.find('(')-1] dlg.setDefaultSuffix(fileTypes[fileType][0]) files = dlg.selectedFiles() if not files: return fileName = unicode(files[0]) Globals.defaultFolder, tmp = os.path.split(fileName) try: pixmap.save(unicode(fileName)) except: QMessageBox.critical(self, QCoreApplication.translate('SubWindow', 'Could not save file!'), QCoreApplication.translate('SubWindow', 'Writing failed! Make sure you have write permissions!'))
def shoot(self): path = res.play2048s.__path__[0] filename = '/screenshot-' + str(self.screenshot_count).zfill(6) + '.jpg' window = QPixmap.grabWidget(self.window()) window.save(path + filename, 'jpg') self.screenshot_count += 1
def btnRunStep2(self): # filename = "file{:05d}.jpg" # filename = "file%05d.jpg" # filename = QtGui.QFileDialog.getSaveFileName( # self, # "Save file", # init_filename, # "" # ) # filename = str(filename) if self.teigen.need_run: self.step1() self._show_stats_after_step1() # filename = op.join(self.ui_output_dir_widget.get_dir(), filename) filename = self.config["filepattern"] # filename = iowidgetqt.str_format_old_to_new(filename) self.teigen.step2() fn_base, fn_ext = self.teigen.filepattern_split() self.figure.savefig(fn_base + "_" + "graph.pdf") self.figure.savefig(fn_base + "_" + "graph.png") self.figure.savefig(fn_base + "_" + "graph.svg") self.figure.savefig(fn_base + "_" + "graph.eps") from PyQt4.QtGui import QPixmap if self._wg_show_3d is not None: p = QPixmap.grabWidget(self._wg_show_3d.vtkWidget) p.save(fn_base + "_snapshot.png", 'png') # self.teigen.gen.saveVolumeToFile(filename) self.update_stats()
def _runTransition(self): """ A private method which runs the transition effect. The `_transition_index` attribute should be set before calling this method. If no transition object exists for this widget, then it is equivalent to calling `setCurrentIndex`. If the new index is not different from the current index the transition will not be performed. """ from_index = self.currentIndex() to_index = self._transition_index # If the index hasn't changed, there is nothing to update. if from_index == to_index: return # If there is no transition applied, just change the index. transition = self._transition if transition is None: self.setCurrentIndex(to_index) return # Otherwise, grab the pixmaps for the start and ending states # and set them on the transtion. The widgets are resized to the # current size so that the pixmaps are grabbed in a good state. src_widget = self.widget(from_index) dst_widget = self.widget(to_index) size = self.size() src_widget.resize(size) dst_widget.resize(size) src_pixmap = QPixmap.grabWidget(src_widget) dst_pixmap = QPixmap.grabWidget(dst_widget) out_pixmap = QPixmap(size) transition.setPixmaps(src_pixmap, dst_pixmap, out_pixmap) # Hide both of the constituent widgets so that the painter has # a clean widget on which to draw. src_widget.setVisible(False) dst_widget.setVisible(False) # Hookup the pixmap painter and start the transition. painter = self._painter = QPixmapPainter() painter.setTargetWidget(self) transition.pixmapUpdated.connect(painter.drawPixmap) transition.start()
def recordSceenshots(statesLoop): ''' A little utility i created to be able to generate GIFs from the simulation. Saves screenshots from the current view of every 10th simulation step. ''' i,j = 0,0 for x in statesLoop: if i < 2*943 and 0 == i % 10: img = QPixmap.grabWidget(self) img = img.scaled(640,500,transformMode = Qt.SmoothTransformation) img.save('data/img%(j)d.jpg' % locals(),'jpg') j+=1 i += 1 yield x
def printMe(self, painter, rect): # redirect table's painting on a pixmap view = self.viewport() if hasattr(self, "viewport") else self pixmap = QPixmap.grabWidget(view, view.rect()) QPainter.setRedirected(view, pixmap) event = QPaintEvent(QRect(0, 0, view.width(), view.height())) QApplication.sendEvent(view, event) QPainter.restoreRedirected(view) # print scaled pixmap pixmap = pixmap.scaled(rect.width(), rect.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation) painter.drawPixmap(rect, pixmap, pixmap.rect())
def mouseMoveEvent(self, event): if not (event.buttons() and Qt.LeftButton): return if ((event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance()): return drag = QDrag(self) pix = QPixmap.grabWidget(self) drag.setPixmap(pix) mime_data = QMimeData() mime_data.setText(self.map.text()) # mime_data.setImageData(self.currentmap) drag.setMimeData(mime_data) self.drop_action = drag.exec_(Qt.CopyAction | Qt.MoveAction)
def render(self, url): """The real worker. Loads the page (_load_page) and awaits the end of the given 'delay'. While it is waiting outstanding QApplication events are processed. After the given delay, the Window or Widget (depends on the value of 'grabWholeWindow' is drawn into a QPixmap and postprocessed (_post_process_image). """ self._load_page(url, self.width, self.height, self.timeout) # Wait for end of timer. In this time, process # other outstanding Qt events. if self.wait > 0: if self.logger: self.logger.debug("Waiting %d seconds " % self.wait) waitToTime = time.time() + self.wait while time.time() < waitToTime and QApplication.hasPendingEvents(): QApplication.processEvents() if self.renderTransparentBackground: # Another possible drawing solution image = QImage(self._page.viewportSize(), QImage.Format_ARGB32) image.fill(QColor(255, 0, 0, 0).rgba()) # http://ariya.blogspot.com/2009/04/transparent-qwebview-and-qwebpage.html palette = self._view.palette() palette.setBrush(QPalette.Base, Qt.transparent) self._page.setPalette(palette) self._view.setAttribute(Qt.WA_OpaquePaintEvent, False) painter = QPainter(image) painter.setBackgroundMode(Qt.TransparentMode) self._page.mainFrame().render(painter) painter.end() else: if self.grabWholeWindow: # Note that this does not fully ensure that the # window still has the focus when the screen is # grabbed. This might result in a race condition. self._view.activateWindow() image = QPixmap.grabWindow(self._window.winId()) else: image = QPixmap.grabWidget(self._window) return self._post_process_image(image)
def _get_image ( self ): # Note: The following code works in most cases, but fails when trying to # capture a VTK-based widget (the VTK-part of the widget is usually all # black), so we use the more involved technique of capturing the part of # the screen the widget covers: control = self.control if not control.isVisible(): return ImageResource( bitmap = QPixmap.grabWidget( control, 0, 0 ) ) point = control.mapToGlobal( QPoint() ) size = control.size() return ImageResource( bitmap = QPixmap.grabWindow( QApplication.desktop().winId(), point.x(), point.y(), size.width(), size.height() ) )
def getPixelColor(self, imgView, coordinates, debugFileName=None, relativeToCenter=True): """ Sample the color of the pixel at the given coordinates. If debugFileName is provided, export the view for debugging purposes. Example: self.getPixelColor(myview, (10,10), 'myview.png') """ img = QPixmap.grabWidget(imgView).toImage() if debugFileName is not None: img.save(debugFileName) point = QPoint(*coordinates) if relativeToCenter: centerPoint = imgView.rect().bottomRight() / 2 point += centerPoint return img.pixel(point)
def mouseMoveEvent(self, e): if self.drag_start is None: pass x = e.x() - self.drag_start.x() y = e.y() - self.drag_start.y() dist = QApplication.startDragDistance() if not self.draggable or x > dist or y > dist: return drag = QDrag(self) mime = QMimeData() mime.setText(self.__class__.__name__) mime.part = self drag.setMimeData(mime) pixmap = QPixmap.grabWidget(self) pixmap.setAlphaChannel(pixmap) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(drag.pixmap().width() / 2, drag.pixmap().height())) drag.start(Qt.CopyAction)
def mouseMoveEvent(self, e): if self.drag_start is None: pass x = e.x() - self.drag_start[0] y = e.y() - self.drag_start[1] dist = QApplication.startDragDistance() if (self.draggable is False) or (abs(x) < dist and abs(y) < dist): return drag = QDrag(self) mime = QMimeData() mime.setText(self.__class__.__name__) mime.part = self drag.setMimeData(mime) pixmap = QPixmap.grabWidget(self) pixmap.setAlphaChannel(pixmap) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(drag.pixmap().width() / 2, drag.pixmap().height())) self.dragging = True drag.start(Qt.CopyAction)
def render(self, url): """The real worker. Loads the page (_load_page) and awaits the end of the given 'delay'. While it is waiting outstanding QApplication events are processed. After the given delay, the Window or Widget (depends on the value of 'grabWholeWindow' is drawn into a QPixmap and postprocessed (_post_process_image). """ self._load_page(url, self.width, self.height, self.timeout) # Wait for end of timer. In this time, process # other outstanding Qt events. if self.wait > 0: LOG.debug("Waiting %d seconds " % self.wait) waitToTime = time.time() + self.wait while time.time() < waitToTime: while QApplication.hasPendingEvents(): QApplication.processEvents() # Paint this frame into an image #self._window.repaint() while QApplication.hasPendingEvents(): QApplication.processEvents() if self.grabWholeWindow: # Note that this does not fully ensure that the # window still has the focus when the screen is # grabbed. This might result in a race condition. self._view.activateWindow() image = QPixmap.grabWindow(self._window.winId()) else: image = QPixmap.grabWidget(self._window) ## Another possible drawing solution #image = QImage(self._page.viewportSize(), QImage.Format_ARGB32) #painter = QPainter(image) #self._page.mainFrame().render(painter) #painter.end() return self._post_process_image(image)
def doSnip(self): """ Do snip """ x = min(self.origin.x(), self.end.x()) y = min(self.origin.y(), self.end.y()) w = abs(self.origin.x() - self.end.x()) h = abs(self.origin.y() - self.end.y()) self.posX = x self.posY = y self.posW = w self.posH = h self.hide() if QtHelper.IS_QT5: pixmap = self.backgroundLabel.grab(QRect(x, y, w, h)) else: pixmap = QPixmap.grabWidget(self.backgroundLabel, x, y, w, h) self.snapshotResult = pixmap self.accept()
def mouseMoveEvent(self, e): # Chequear que se esté presionando el botón izquierdo if e.buttons() != Qt.LeftButton: return # posicion del click dentro del gmod mimeData = QMimeData() pixmap = QPixmap.grabWidget(self) painter = QPainter(pixmap) painter.setCompositionMode(painter.CompositionMode_DestinationIn) painter.fillRect(pixmap.rect(), QColor(0, 0, 0, 127)) painter.end() drag = QDrag(self) # escribir el MimeData drag.setMimeData(mimeData) # establecer el Pixmap drag.setPixmap(pixmap) # posicionar correctamente el pixmap drag.setHotSpot(e.pos()) drag.exec_(Qt.MoveAction)
def startDrag(self, event): child = self.childAt(event.pos()) if not child: return pos_in_child = event.pos() - child.pos() data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) stream << QVariant(child.value()) << QPoint(pos_in_child) mime = QMimeData() mime.setData("application/x-fridgemagnet", data) drag = QDrag(child) drag.setMimeData(mime) drag.setPixmap(QPixmap.grabWidget(child)) drag.setHotSpot(pos_in_child) child.hide() if (drag.start(Qt.MoveAction or Qt.CopyAction) == Qt.MoveAction): child.close() else: child.show()
def update_preview(self): if self.widget: snapshot = QPixmap.grabWidget(self.widget) self.snapshot = snapshot self.setPixmap(self.snapshot)
def take_screenshot(self, path): pixmap = QPixmap(QPixmap.grabWidget(self.display)) pixmap.save(path) self.logger.debug('Saving {}'.format(path))
plain = fromUnicodeString(codes[0]) shift = fromUnicodeString(codes[1]) ctrl = fromUnicodeString(codes[2]) alt = fromUnicodeString(codes[3]) if ctrl == plain: ctrl = "" if alt == plain: alt = "" self.codes.append((plain, shift, ctrl, alt)) ## testing if __name__ == "__main__": from PyQt4.QtGui import QApplication app = QApplication(sys.argv) layout = sys.argv[1] variant = sys.argv[2] filename = sys.argv[3] kb1 = Keyboard() kb1.setLayout(layout) kb1.setVariant(variant) snapshot = QPixmap.grabWidget(kb1) #snapshot = snapshot.scaled(600, 200, Qt.IgnoreAspectRatio, Qt.FastTransformation) snapshot.save(filename, "PNG")
shift = fromUnicodeString(codes[1]) ctrl = fromUnicodeString(codes[2]) alt = fromUnicodeString(codes[3]) if ctrl == plain: ctrl = "" if alt == plain: alt = "" self.codes.append((plain, shift, ctrl, alt)) ## testing if __name__ == "__main__": from PyQt4.QtGui import QApplication, QVBoxLayout app = QApplication(sys.argv) layout = sys.argv[1] variant = sys.argv[2] filename = sys.argv[3] kb1 = Keyboard() kb1.setLayout(layout) kb1.setVariant(variant) snapshot = QPixmap.grabWidget(kb1) #snapshot = snapshot.scaled(600, 200, Qt.IgnoreAspectRatio, Qt.FastTransformation) snapshot.save(filename, "PNG")