Skip to content

Instantly share code, notes, and snippets.

@trigfa
Created November 18, 2013 20:42
Show Gist options
  • Save trigfa/7534956 to your computer and use it in GitHub Desktop.
Save trigfa/7534956 to your computer and use it in GitHub Desktop.
Trying to print from pyqt
import sys
import numpy as np
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#from xlwt import *
from pylab import plot, show
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar2
class ViewWidget(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# create a simple main widget to keep the figure
self.mainWidget = QWidget()
self.setCentralWidget(self.mainWidget)
layout = QVBoxLayout()
self.mainWidget.setLayout(layout)
# create a figure
self.figure_canvas = FigureCanvas(Figure())
layout.addWidget(self.figure_canvas, 10)
# and the axes for the figure
self.axes = self.figure_canvas.figure.add_subplot(111)
x = np.linspace(0.,2*np.pi,100)
self.axes.plot(x,np.sin(x),label='sin(x) ')
self.axes.plot(x,np.cos(x),label='cos(x) ')
self.axes.figure.set_facecolor('white')
self.axes.grid('on')
self.axes.legend()
# add a navigation toolbar
self.navigation_toolbar = NavigationToolbar2(self.figure_canvas, self)
layout.addWidget(self.navigation_toolbar, 0)
self.print_button = QPushButton()
self.print_button.setIcon(QIcon("Fileprint.png"))
self.print_button.setToolTip("Print the figure")
self.navigation_toolbar.addWidget(self.print_button)
self.connect(self.print_button, SIGNAL('clicked()'), self.goPrinter)
self.quit_button = QPushButton("&Quit")
self.navigation_toolbar.addWidget(self.quit_button)
self.connect(self.quit_button, SIGNAL('clicked()'), self.close)
def goPrinter(self):
printer = QPrinter()
printer.A4
printer.HighResolution
printer.Color
anotherWidget= QPrintDialog(printer,self)
if(anotherWidget.exec_() != QDialog.Accepted):
return
p = QPixmap.grabWidget(self.figure_canvas)
printLabel = QLabel()
printLabel.setPixmap(p)
painter = QPainter(printer)
printLabel.render(painter)
painter.end()
show()
if __name__=="__main__":
app=QApplication(sys.argv)
mw=ViewWidget()
mw.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment