Attachment 'painttext.py'
Download 1 #!/usr/bin/env python
2
3 import sys
4 from PyQt4.QtCore import Qt
5 from PyQt4.QtGui import *
6
7 class Window(QWidget):
8
9 def __init__(self, parent = None):
10
11 QWidget.__init__(self, parent)
12
13 self.label = QLabel()
14
15 self.lineEdit = QLineEdit("ABCDE")
16 self.fontComboBox = QFontComboBox()
17 self.sizeSpinBox = QDoubleSpinBox()
18 self.sizeSpinBox.setMinimum(1.0)
19 self.sizeSpinBox.setValue(12.0)
20 saveButton = QPushButton(self.tr("Save"))
21
22 self.lineEdit.textChanged.connect(self.updateImage)
23 self.fontComboBox.currentFontChanged.connect(self.updateImage)
24 self.sizeSpinBox.valueChanged.connect(self.updateImage)
25 saveButton.clicked.connect(self.saveImage)
26
27 formLayout = QFormLayout()
28 formLayout.addRow(self.tr("&Text:"), self.lineEdit)
29 formLayout.addRow(self.tr("&Font:"), self.fontComboBox)
30 formLayout.addRow(self.tr("Font &Size:"), self.sizeSpinBox)
31
32 layout = QGridLayout()
33 layout.addWidget(self.label, 0, 0, 1, 3, Qt.AlignCenter)
34 layout.addLayout(formLayout, 1, 0, 1, 3)
35 layout.addWidget(saveButton, 2, 1)
36 self.setLayout(layout)
37
38 self.updateImage()
39 self.setWindowTitle(self.tr("Paint Text"))
40
41 def updateImage(self):
42
43 font = QFont(self.fontComboBox.currentFont())
44 font.setPointSizeF(self.sizeSpinBox.value())
45 metrics = QFontMetricsF(font)
46
47 text = unicode(self.lineEdit.text())
48 if not text:
49 return
50
51 rect = metrics.boundingRect(text)
52 position = -rect.topLeft()
53
54 pixmap = QPixmap(rect.width(), rect.height())
55 pixmap.fill(Qt.white)
56
57 painter = QPainter()
58 painter.begin(pixmap)
59 painter.setFont(font)
60 painter.drawText(position, text)
61 painter.end()
62
63 self.label.setPixmap(pixmap)
64
65 def saveImage(self):
66
67 formats = QImageWriter.supportedImageFormats()
68 formats = map(lambda suffix: u"*."+unicode(suffix), formats)
69 path = unicode(QFileDialog.getSaveFileName(self, self.tr("Save Image"),
70 "", self.tr("Image files (%1)").arg(u" ".join(formats))))
71
72 if path:
73 if not self.label.pixmap().save(path):
74 QMessageBox.warning(self, self.tr("Save Image"),
75 self.tr("Failed to save file at the specified location."))
76
77
78 if __name__ == "__main__":
79
80 app = QApplication(sys.argv)
81 window = Window()
82 window.show()
83 sys.exit(app.exec_())
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.