Tuesday, September 10, 2024

Creating Forms and Print Preview with Jinja2 Templates in PyQt6

 In this blog post, we will walk through creating a PyQt6 application that uses Jinja2 templates for rendering printable content. Our example application is a manufacturing order entry system with forms for data entry and functionality for print preview and printing.

We expect to create the following screen:


And here is its print preview:


Step-by-Step Breakdown

  1. Setup PyQt6 and Jinja2

    Ensure you have PyQt6 and Jinja2 installed. You can install these via pip if you haven’t already:

pip install PyQt6 jinja2

2. Create the Main Application Class

We'll start by creating a class ManufacturingOrderEntry that inherits from QMainWindow. This class will contain all the UI elements and functionality for our form.

1
2
3
4
5
6
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QFormLayout, QLineEdit, QDateEdit, QLabel, QHBoxLayout, QTableWidget, QTableWidgetItem, QGridLayout, QPushButton, QTextEdit
from PyQt6.QtGui import QFont, QColor, QPalette
from PyQt6.QtCore import Qt
from PyQt6 import QtPrintSupport
from jinja2 import Template

3. Define the Constructor and Layouts

In the __init__ method, set up the main window layout and UI components 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class ManufacturingOrderEntry(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Manufacturing Order Entry")
        self.setGeometry(100, 100, 800, 600)

        # Main Layout
        main_widget = QWidget(self)
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)

        # Header Sections
        header_layout = self.create_header_layout()
        main_layout.addLayout(header_layout)

        # Process and Inspection Sections
        process_layout = self.create_process_layout()
        main_layout.addLayout(process_layout)

        # Prepared and Approved By Section
        prepared_approved_layout = self.create_prepared_approved_layout()
        main_layout.addLayout(prepared_approved_layout)

        # Adding TextEdit for rendering printable content
        self.etext = QTextEdit(self)
        self.etext.setReadOnly(True)
        main_layout.addWidget(self.etext)

        # Buttons for Print and Preview
        button_layout = QHBoxLayout()
        self.print_button = QPushButton('Print', self)
        self.preview_button = QPushButton('Preview', self)
        button_layout.addWidget(self.preview_button)
        button_layout.addWidget(self.print_button)
        main_layout.addLayout(button_layout)

        # Connecting buttons to handlers
        self.preview_button.clicked.connect(self.handle_print_preview)
        self.print_button.clicked.connect(self.handle_print)

        # Generate the content for the QTextEdit
        self.generate_content()

4. Define Layout Creation Methods

Methods like create_header_layout, create_process_layout, and create_prepared_approved_layout are responsible for setting up different sections of the form.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def create_header_layout(self):
    layout = QGridLayout()
    layout.setContentsMargins(5, 5, 5, 5)
    # Add widgets and layout configurations here
    return layout

def create_process_layout(self):
    layout = QVBoxLayout()
    # Add widgets and layout configurations here
    return layout

def create_prepared_approved_layout(self):
    layout = QHBoxLayout()
    # Add widgets and layout configurations here
    return layout

5. Generate Content with Jinja2

Use Jinja2 templates to render HTML content for printing. This content is set in a QTextEdit widget, which will be used for both print preview and printing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def generate_content(self):
    # Collecting data
    # Define the data to be used in the template
    template = """
    <style>
        /* Define your CSS styles here */
    </style>
    <h1>Production Order</h1>
    <!-- Manufacturing Order Details -->
    <table>
        <!-- Table content here -->
    </table>
    <!-- Process I, II, Inspection, Packing tables -->
    <!-- Signature section -->
    """
    # Render the template with data
    rendered_html = Template(template).render(
        # Pass variables here
    )
    self.etext.setHtml(rendered_html)

 6. Implement Print Preview and Printing

Implement methods to handle print preview and printing using QPrintPreviewDialog and QPrinter.

1
2
3
4
5
6
7
8
9
def handle_print_preview(self):
    dialog = QtPrintSupport.QPrintPreviewDialog()
    dialog.paintRequested.connect(self.etext.print)
    dialog.exec()

def handle_print(self):
    printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.PrinterMode.HighResolution)
    printer.setPageSize(QtPrintSupport.QPageSize(QtPrintSupport.QPageSize.PageSizeId.A4))
    self.etext.print(printer)

 7. Run the Application

Finally, set up the main function to run the application

1
2
3
4
5
6
7
8
def main():
    app = QApplication(sys.argv)
    window = ManufacturingOrderEntry()
    window.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()

Conclusion

This example demonstrates how to integrate Jinja2 templating with PyQt6 to create dynamic, printable forms. The approach allows for the separation of form data and presentation logic, making it easier to manage and update form layouts and styles. You can further customize the template and styles as needed for your specific use case.


Here is the rest complete program listing:


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import sys
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QFormLayout, QLineEdit, 
    QDateEdit, QLabel, QHBoxLayout, QTableWidget, QTableWidgetItem, QGridLayout, QPushButton, QTextEdit
)
from PyQt6.QtGui import QFont, QColor, QPalette
from PyQt6.QtCore import Qt
from PyQt6 import QtPrintSupport
from jinja2 import Template

class ManufacturingOrderEntry(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Manufacturing Order Entry")
        self.setGeometry(100, 100, 800, 600)

        # Main Layout
        main_widget = QWidget(self)
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)

        # Header Sections
        header_layout = self.create_header_layout()
        main_layout.addLayout(header_layout)

        # Process and Inspection Sections
        process_layout = self.create_process_layout()
        main_layout.addLayout(process_layout)

        # Prepared and Approved By Section
        prepared_approved_layout = self.create_prepared_approved_layout()
        main_layout.addLayout(prepared_approved_layout)

        # Adding TextEdit for rendering printable content
        self.etext = QTextEdit(self)
        self.etext.setReadOnly(True)
        main_layout.addWidget(self.etext)

        # Buttons for Print and Preview
        button_layout = QHBoxLayout()
        self.print_button = QPushButton('Print', self)
        self.preview_button = QPushButton('Preview', self)
        button_layout.addWidget(self.preview_button)
        button_layout.addWidget(self.print_button)
        main_layout.addLayout(button_layout)

        # Connecting buttons to handlers
        self.preview_button.clicked.connect(self.handle_print_preview)
        self.print_button.clicked.connect(self.handle_print)

        # Generate the content for the QTextEdit
        self.generate_content()

    def generate_content(self):
        # Collecting data from the form fields
        order_no = "12345"
        product = "Widget A"
        job_quantity = "500"
        customer_delivery_date = "2024-09-25"
        job_started_date = "2024-09-20"
        rm_transfer_date = "2024-09-21"
        packing_target_date = "2024-09-22"
        dispatch_target_date = "2024-09-23"
        finish_product_transfer_date = "2024-09-24"
        job_end_date = "2024-09-25"

        process_i = [
            ["1", "100", "pcs", "Stage 1", "0", "$100", "100"],
            ["2", "200", "pcs", "Stage 2", "0", "$200", "200"],
            ["3", "300", "pcs", "Stage 3", "0", "$300", "300"],
        ]
        process_ii = [
            ["1", "100", "pcs", "Stage 1", "0", "$100", "100"],
            ["2", "200", "pcs", "Stage 2", "0", "$200", "200"],
        ]
        inspection = [
            ["1", "100", "pcs", "Inspection 1", "0", "$50", "100"],
        ]
        packing = [
            ["1", "100", "pcs", "Packing 1", "0", "$70", "100"],
        ]
        prepared_by = "John Doe"
        approved_by = "Jane Smith"

        template = """
<style>
    body {
        font-family: Arial, sans-serif;
    }
    table {
        width: 100%;
        border-collapse: collapse;
    }
    th, td {
        border: 1px solid #000;
        padding: 5px;
        text-align: center;
    }
    th {
        background-color: #000;
        color: #fff;
    }
    .section-header {
        background-color: #000;
        color: #fff;
        text-align: center;
        font-weight: bold;
        padding: 5px;
        border: 1px solid #000;
        margin-top: 10px;
    }
    .process-table {
        margin-top: 10px;
    }
    .process-header {
        background-color: #FFD700;
        text-align: center;
        font-weight: bold;
    }
    .signature-section {
        width: 50%;
        margin: 30px auto;
        text-align: center;
    }
    .signature-line {
        border-top: 1px solid #000;
        width: 60%;
        margin: 0 auto;
    }
    .signature-label {
        margin-top: 5px;
        font-weight: bold;
    }
    .signature-container {
        display: flex;
        justify-content: space-between;
    }
    .signature-item {
        flex: 1;
        text-align: center;
    }
</style>

<h1>Production Order</h1>

<!-- Manufacturing Order Details -->
<table>
    <tr>
        <td>Manufacturing Order No. & Date:</td>
        <td>{{ order_no }}</td>
        <td>Job Started Date:</td>
        <td>{{ job_started_date }}</td>
    </tr>
    <tr>
        <td>Product:</td>
        <td>{{ product }}</td>
        <td>R.M. Location - Mat. Transfer Date:</td>
        <td>{{ rm_transfer_date }}</td>
    </tr>
    <tr>
        <td>Job Quantity:</td>
        <td>{{ job_quantity }}</td>
        <td>Target of Packing:</td>
        <td>{{ packing_target_date }}</td>
    </tr>
    <tr>
        <td>Customer Delivery Date:</td>
        <td>{{ customer_delivery_date }}</td>
        <td>Target of Dispatch:</td>
        <td>{{ dispatch_target_date }}</td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td>Finish Product Location - Mat. Transfer Date:</td>
        <td>{{ finish_product_transfer_date }}</td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td>Job End Date:</td>
        <td>{{ job_end_date }}</td>
    </tr>
</table>

<!-- Process I -->
<div class="section-header">Process I</div>
<table class="process-table">
    <thead class="process-header">
        <tr>
            <th>Serial No.</th>
            <th>QTY</th>
            <th>U.M.O</th>
            <th>Internal Process Stage</th>
            <th>Rej. Qty</th>
            <th>Cost</th>
            <th>Passed Quantity</th>
        </tr>
    </thead>
    <tbody>
        {% for row in process_i %}
        <tr>
            {% for element in row %}
            <td>{{ element }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

<!-- Process II -->
<div class="section-header">Process II</div>
<table class="process-table">
    <thead class="process-header">
        <tr>
            <th>Serial No.</th>
            <th>QTY</th>
            <th>U.M.O</th>
            <th>Internal Process Stage</th>
            <th>Rej. Qty</th>
            <th>Cost</th>
            <th>Passed Quantity</th>
        </tr>
    </thead>
    <tbody>
        {% for row in process_ii %}
        <tr>
            {% for element in row %}
            <td>{{ element }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

<!-- Inspection -->
<div class="section-header">Inspection</div>
<table class="process-table">
    <thead class="process-header">
        <tr>
            <th>Serial No.</th>
            <th>QTY</th>
            <th>U.M.O</th>
            <th>Internal Process Stage</th>
            <th>Rej. Qty</th>
            <th>Cost</th>
            <th>Passed Quantity</th>
        </tr>
    </thead>
    <tbody>
        {% for row in inspection %}
        <tr>
            {% for element in row %}
            <td>{{ element }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

<!-- Packing -->
<div class="section-header">Packing</div>
<table class="process-table">
    <thead class="process-header">
        <tr>
            <th>Serial No.</th>
            <th>QTY</th>
            <th>U.M.O</th>
            <th>Internal Process Stage</th>
            <th>Rej. Qty</th>
            <th>Cost</th>
            <th>Passed Quantity</th>
        </tr>
    </thead>
    <tbody>
        {% for row in packing %}
        <tr>
            {% for element in row %}
            <td>{{ element }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

<!-- Prepared and Approved By -->
<div class="signature-section" style="margin-top: 50px;">
    <div class="signature-container">
        <div class="signature-item">
            <div class="signature-label">Prepared By</div>
            <div class="signature-line"></div>
            <div style="height: 50px;"></div> <!-- Space for signature -->
            <div>{{ prepared_by }}</div>
        </div>
        <p /> <br />
        <div class="signature-item">
            <div class="signature-label">Approved By</div>
            <div class="signature-line"></div>
            <div style="height: 50px;"></div> <!-- Space for signature -->
            <div>{{ approved_by }}</div>
        </div>
    </div>
</div>
"""

        # Render the table with Jinja2 template
        rendered_html = Template(template).render(
            order_no=order_no,
            product=product,
            job_quantity=job_quantity,
            customer_delivery_date=customer_delivery_date,
            job_started_date=job_started_date,
            rm_transfer_date=rm_transfer_date,
            packing_target_date=packing_target_date,
            dispatch_target_date=dispatch_target_date,
            finish_product_transfer_date=finish_product_transfer_date,
            job_end_date=job_end_date,
            process_i=process_i,
            process_ii=process_ii,
            inspection=inspection,
            packing=packing,
            prepared_by=prepared_by,
            approved_by=approved_by
        )
        self.etext.setHtml(rendered_html)


    def handle_print_preview(self):
        dialog = QtPrintSupport.QPrintPreviewDialog()
        dialog.paintRequested.connect(self.etext.print)
        dialog.exec()

    def handle_print(self):
        printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.PrinterMode.HighResolution)
        printer.setPageSize(QtPrintSupport.QPageSize(QtPrintSupport.QPageSize.PageSizeId.A4))
        self.etext.print(printer)

    def create_header_layout(self):
        layout = QGridLayout()
        layout.setContentsMargins(5, 5, 5, 5)

        # Manufacturing Order Details
        layout.addWidget(self.create_colored_label("MANUFACTURING ORDER NO. & DATE:", "lightblue"), 0, 0)
        layout.addWidget(QLineEdit(), 0, 1)
        layout.addWidget(self.create_colored_label("PRODUCT:", "lightblue"), 1, 0)
        layout.addWidget(QLineEdit(), 1, 1)
        layout.addWidget(self.create_colored_label("JOB QUANTITY:", "lightblue"), 2, 0)
        layout.addWidget(QLineEdit(), 2, 1)
        layout.addWidget(self.create_colored_label("CUSTOMER DELIVERY DATE:", "lightblue"), 3, 0)
        layout.addWidget(QDateEdit(calendarPopup=True), 3, 1)

        # Job Details
        layout.addWidget(self.create_colored_label("JOB STARTED DATE:", "lightgreen"), 0, 2)
        layout.addWidget(QDateEdit(calendarPopup=True), 0, 3)
        layout.addWidget(self.create_colored_label("R.M. LOCATION - MAT. TRANSFER DATE:", "lightgreen"), 1, 2)
        layout.addWidget(QDateEdit(calendarPopup=True), 1, 3)
        layout.addWidget(self.create_colored_label("TARGET OF PACKING:", "lightgreen"), 2, 2)
        layout.addWidget(QDateEdit(calendarPopup=True), 2, 3)
        layout.addWidget(self.create_colored_label("TARGET OF DISPATCH:", "lightgreen"), 3, 2)
        layout.addWidget(QDateEdit(calendarPopup=True), 3, 3)
        layout.addWidget(self.create_colored_label("FINISH PRODUCT LOC. - MAT. TRANSFER DATE:", "lightgreen"), 4, 2)
        layout.addWidget(QDateEdit(calendarPopup=True), 4, 3)
        layout.addWidget(self.create_colored_label("JOB END DATE:", "lightgreen"), 5, 2)
        layout.addWidget(QDateEdit(calendarPopup=True), 5, 3)

        return layout

    def create_process_layout(self):
        layout = QVBoxLayout()
        
        # Process I Section
        layout.addWidget(self.create_colored_label("Process I", "lightpurple", True, font_color="white"))
        layout.addWidget(self.create_process_table("Process I", QColor(245, 222, 255)))  # Light purple

        # Process II Section
        layout.addWidget(self.create_colored_label("Process II", "lightpurple", True, font_color="white"))
        layout.addWidget(self.create_process_table("Process II", QColor(245, 222, 255)))  # Light purple

        # Inspection Section
        layout.addWidget(self.create_colored_label("Inspection", "yellow", True))
        layout.addWidget(self.create_process_table("Inspection", QColor(255, 255, 204)))  # Light yellow

        # Packing Section
        layout.addWidget(self.create_colored_label("Packing", "lightgreen", True))
        layout.addWidget(self.create_process_table("Packing", QColor(204, 255, 204)))  # Light green

        return layout

    def create_process_table(self, title, color):
        table = QTableWidget(5, 7)
        table.setHorizontalHeaderLabels([
            "Serial No.", "QTY", "U.M.O", "Internal Process Stage", 
            "Rej. Qty", "Cost", "Passed Quantity"
        ])
        for i in range(5):
            for j in range(7):
                table.setItem(i, j, QTableWidgetItem(""))

        # Set background color for each cell
        palette = table.palette()
        palette.setColor(QPalette.ColorRole.Base, color)
        table.setPalette(palette)
        table.setAlternatingRowColors(True)
        return table

    def create_colored_label(self, text, color, is_section=False, font_color="black"):
        label = QLabel(text)
        if is_section:
            label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            label.setFont(QFont('Arial', 10, QFont.Weight.Bold))
            label.setStyleSheet(f"background-color: {color}; color: {font_color}; padding: 5px; border: 1px solid black;")
        else:
            label.setStyleSheet(f"background-color: {color}; padding: 5px;")
        return label

    def create_prepared_approved_layout(self):
        layout = QHBoxLayout()
        layout.addWidget(self.create_colored_label("PREPARED BY", "white"))
        layout.addWidget(QLineEdit())
        layout.addWidget(self.create_colored_label("APPROVED BY", "white"))
        layout.addWidget(QLineEdit())
        return layout

def main():
    app = QApplication(sys.argv)
    window = ManufacturingOrderEntry()
    window.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()


No comments:

Post a Comment