i have a error in my coding please help me to resolve
-
raceback (most recent call last):
File "c:\Users\mohib\Desktop\PP\import sys.py", line 334, in custom_print
painter.begin(printer)
^^^^^^^^^^^^^
AttributeError: 'QPrinter' object has no attribute 'begin' -
Hi and welcome to devnet,
Which version of PySide / PyQt are you using ?
On which OS ?Is that file really name "import sys.py" ?
If so, the first thing to do is to rename it to something more meaningful and not using both a Python keyword and Python standard module in its name. -
@muhammad15
After you have addressed @SGaist's suggestion. What type is yourpainter
? If by any chance it is aQPrinter
you would (presumably) get that error message. -
@SGaist now I change it to rems_app.py.... but its again give error "File "c:\Users\mohib\Desktop\PP\rems_app.py", line 335, in custom_print
painter.begin(printer)
^^^^^^^^^^^^^
AttributeError: 'QPrinter' object has no attribute 'begin'
I using PyQt.... if i give you code here can you remover error from these codes ? now i am pasting my code here...
import sys
import sqlite3
import os
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QLabel, QPushButton, QLineEdit, QVBoxLayout,
QHBoxLayout, QWidget, QTableWidget, QTableWidgetItem, QMenu,
QAction, QFileDialog, QMessageBox, QDialog, QFormLayout, QSpinBox, QTabWidget
)
from PyQt5.QtGui import QFont, QColor, QPixmap
from PyQt5.QtCore import Qt, QDateTime
from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog
from PyQt5.QtGui import QPainterDatabase file paths
LOGIN_DB = "user_login.db"
SALES_DB = "sales_records.db"Ensure login database exists
def init_login_db():
with sqlite3.connect(LOGIN_DB) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT NOT NULL
)
""")
cursor.execute("SELECT COUNT(*) FROM users")
if cursor.fetchone()[0] == 0:
cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", ("admin", "admin"))Ensure sales database exists
def init_sales_db():
with sqlite3.connect(SALES_DB) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS sales (
serial INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT,
name TEXT,
plot_number TEXT,
plot_size TEXT,
total_amount REAL,
paid_amount REAL,
balance_amount REAL,
date_time TEXT
)
""")Initialize databases
init_login_db()
init_sales_db()class LoginPage(QWidget):
def init(self):
super().init()
self.setWindowTitle("Login")
self.setGeometry(100, 100, 400, 300)layout = QVBoxLayout() # Title self.title = QLabel("ISLAMABAD GARDEN VALLEY") self.title.setFont(QFont("Arial", 16, QFont.Bold)) self.title.setStyleSheet("color: blue;") self.title.setAlignment(Qt.AlignCenter) layout.addWidget(self.title) # Username and Password self.username_label = QLabel("Username:") self.username_input = QLineEdit() self.password_label = QLabel("Password:") self.password_input = QLineEdit() self.password_input.setEchoMode(QLineEdit.Password) layout.addWidget(self.username_label) layout.addWidget(self.username_input) layout.addWidget(self.password_label) layout.addWidget(self.password_input) # Login Button self.login_button = QPushButton("Login") self.login_button.setStyleSheet("background-color: #0078D7; color: white; padding: 8px; font-size: 14px;") self.login_button.clicked.connect(self.login) layout.addWidget(self.login_button) # Footer self.footer = QLabel("REAL ESTATE SOFTWARE developed by TRUTH") self.footer.setFont(QFont("Arial", 10, QFont.Bold)) self.footer.setStyleSheet("color: red;") self.footer.setAlignment(Qt.AlignCenter) layout.addWidget(self.footer) self.setLayout(layout) def login(self): username = self.username_input.text() password = self.password_input.text() with sqlite3.connect(LOGIN_DB) as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password)) user = cursor.fetchone() if user: main_window.show() self.close() else: QMessageBox.warning(self, "Login Failed", "Invalid username or password!")
class AddRecordDialog(QDialog):
def init(self):
super().init()
self.setWindowTitle("Add New Record")
self.setGeometry(100, 100, 400, 300)layout = QFormLayout() self.user_id_input = QLineEdit() self.name_input = QLineEdit() self.plot_number_input = QLineEdit() self.plot_size_input = QLineEdit() self.total_amount_input = QSpinBox() self.total_amount_input.setMaximum(1000000000) self.paid_amount_input = QSpinBox() self.paid_amount_input.setMaximum(1000000000) layout.addRow("User ID:", self.user_id_input) layout.addRow("Name:", self.name_input) layout.addRow("Plot Number:", self.plot_number_input) layout.addRow("Plot Size:", self.plot_size_input) layout.addRow("Total Amount:", self.total_amount_input) layout.addRow("Paid Amount:", self.paid_amount_input) self.submit_button = QPushButton("Add Record") self.submit_button.setStyleSheet("background-color: #28A745; color: white; padding: 8px; font-size: 14px;") self.submit_button.clicked.connect(self.add_record) layout.addWidget(self.submit_button) self.setLayout(layout) def add_record(self): user_id = self.user_id_input.text() name = self.name_input.text() plot_number = self.plot_number_input.text() plot_size = self.plot_size_input.text() total_amount = self.total_amount_input.value() paid_amount = self.paid_amount_input.value() if not user_id or not name or not plot_number or not plot_size: QMessageBox.warning(self, "Input Error", "All fields must be filled!") return balance_amount = total_amount - paid_amount date_time = QDateTime.currentDateTime().toString() with sqlite3.connect(SALES_DB) as conn: cursor = conn.cursor() cursor.execute(""" INSERT INTO sales (user_id, name, plot_number, plot_size, total_amount, paid_amount, balance_amount, date_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, (user_id, name, plot_number, plot_size, total_amount, paid_amount, balance_amount, date_time)) main_window.update_table() self.accept()
class UserSettingsDialog(QDialog):
def init(self):
super().init()
self.setWindowTitle("User Settings")
self.setGeometry(100, 100, 400, 200)layout = QFormLayout() self.new_user_label = QLabel("New Username:") self.new_user_input = QLineEdit() self.new_password_label = QLabel("New Password:") self.new_password_input = QLineEdit() self.new_password_input.setEchoMode(QLineEdit.Password) self.save_button = QPushButton("Save") self.save_button.clicked.connect(self.save_user) layout.addRow(self.new_user_label, self.new_user_input) layout.addRow(self.new_password_label, self.new_password_input) layout.addWidget(self.save_button) self.setLayout(layout) def save_user(self): username = self.new_user_input.text() password = self.new_password_input.text() if username and password: with sqlite3.connect(LOGIN_DB) as conn: cursor = conn.cursor() cursor.execute("INSERT OR REPLACE INTO users (username, password) VALUES (?, ?)", (username, password)) QMessageBox.information(self, "Success", "User saved successfully!") self.accept() else: QMessageBox.warning(self, "Error", "Both fields are required!")
class MainPage(QMainWindow):
def init(self):
super().init()
self.setWindowTitle("REMS (Real Estate Management System)")
self.setGeometry(100, 100, 1000, 600)# Set background image self.setStyleSheet("background-image: url('c:/users/mohib/desktop/PP/Garden.jpg');") # Menu Bar self.menu_bar = self.menuBar() # Sales Menu self.sales_menu = self.menu_bar.addMenu("Sales") self.add_action = QAction("Add New Record", self) self.add_action.triggered.connect(self.open_add_record_dialog) self.sales_menu.addAction(self.add_action) self.edit_action = QAction("Edit Record", self) self.sales_menu.addAction(self.edit_action) self.delete_action = QAction("Delete Record", self) self.delete_action.triggered.connect(self.delete_record) self.sales_menu.addAction(self.delete_action) self.search_action = QAction("Search Record", self) self.sales_menu.addAction(self.search_action) # Print Menu self.print_menu = self.menu_bar.addMenu("Print") self.print_action = QAction("Print Record", self) self.print_action.triggered.connect(self.print_record) self.print_menu.addAction(self.print_action) # User Settings Menu self.settings_menu = self.menu_bar.addMenu("User Settings") self.user_settings_action = QAction("User Settings", self) self.user_settings_action.triggered.connect(self.open_user_settings) self.settings_menu.addAction(self.user_settings_action) # Logout Menu self.logout_menu = self.menu_bar.addMenu("Logout") self.logout_action = QAction("Logout", self) self.logout_action.triggered.connect(self.logout) self.logout_menu.addAction(self.logout_action) # Main Widget self.main_widget = QWidget() self.setCentralWidget(self.main_widget) # Table self.table = QTableWidget() self.table.setColumnCount(8) self.table.setHorizontalHeaderLabels([ "Serial", "User ID", "Name", "Plot Number", "Plot Size", "Total Amount", "Paid Amount", "Balance Amount", "Date & Time" ]) # Layout layout = QVBoxLayout() layout.addWidget(self.table) self.main_widget.setLayout(layout) self.update_table() def open_add_record_dialog(self): dialog = AddRecordDialog() dialog.exec_() def open_user_settings(self): dialog = UserSettingsDialog() dialog.exec_() def update_table(self): with sqlite3.connect(SALES_DB) as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM sales") records = cursor.fetchall() self.table.setRowCount(len(records)) for row, record in enumerate(records): for col, value in enumerate(record): self.table.setItem(row, col, QTableWidgetItem(str(value))) def delete_record(self): selected_row = self.table.currentRow() if selected_row < 0: QMessageBox.warning(self, "Selection Error", "No record selected to delete.") return serial = self.table.item(selected_row, 0).text() with sqlite3.connect(SALES_DB) as conn: cursor = conn.cursor() cursor.execute("DELETE FROM sales WHERE serial = ?", (serial,)) self.update_table() def print_record(self): selected_row = self.table.currentRow() if selected_row < 0: QMessageBox.warning(self, "Selection Error", "No record selected to print.") return # Get the details of the selected record def get_item_text(row, col): item = self.table.item(row, col) return item.text() if item else "" serial = get_item_text(selected_row, 0) user_id = get_item_text(selected_row, 1) name = get_item_text(selected_row, 2) plot_number = get_item_text(selected_row, 3) plot_size = get_item_text(selected_row, 4) total_amount = get_item_text(selected_row, 5) paid_amount = get_item_text(selected_row, 6) balance_amount = get_item_text(selected_row, 7) date_time = get_item_text(selected_row, 8) # Set up the QPrinter for printing printer = QPrinter(QPrinter.HighResolution) printer.setPageSize(QPrinter.A4) # Create the QPrintPreviewDialog preview_dialog = QPrintPreviewDialog(printer, self) # Check if the background image exists background_image_path = "c:/users/mohib/desktop/pp/pp.jpg" if not os.path.exists(background_image_path): QMessageBox.warning(self, "Error", "Background image not found!") return # Set up the custom painter function to print the content def custom_print(painter): painter.begin(printer) painter.setPen(Qt.black) painter.setFont(QFont("Arial", 12)) background_image = QPixmap(background_image_path) painter.drawPixmap(0, 0, background_image) text = f""" Serial: {serial} User ID: {user_id} Name: {name} Plot Number: {plot_number} Plot Size: {plot_size} Total Amount: {total_amount} Paid Amount: {paid_amount} Balance Amount: {balance_amount} Date & Time: {date_time} """ painter.drawText(100, 100, text) painter.end() preview_dialog.paintRequested.connect(custom_print) preview_dialog.exec_() def logout(self): self.close() login_page.show()
Start the application
app = QApplication(sys.argv)
login_page = LoginPage()
main_window = MainPage()login_page.show()
sys.exit(app.exec_()) -
I also want to know more about it. Thank you so much!
-
@muhammad15 Please post your code properly!
You did not answer one of the questions from @SGaist
In Qt6 QPainter class has no method called begin(), so change the code if you want to use Qt6. -
@jsulm said in i have a error in my coding please help me to resolve:
.
i am just start learning coding , its my first project, help me to solve this issue.. make any changes you want to my codes to solve my issue , i am giving you full codes again here...
import sys
import sqlite3
import os
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QLabel, QPushButton, QLineEdit, QVBoxLayout,
QHBoxLayout, QWidget, QTableWidget, QTableWidgetItem, QMenu,
QAction, QFileDialog, QMessageBox, QDialog, QFormLayout, QSpinBox, QTabWidget
)
from PyQt5.QtGui import QFont, QColor, QPixmap
from PyQt5.QtCore import Qt, QDateTime
from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog
from PyQt5.QtGui import QPainterDatabase file paths
LOGIN_DB = "user_login.db"
SALES_DB = "sales_records.db"Ensure login database exists
def init_login_db():
with sqlite3.connect(LOGIN_DB) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT NOT NULL
)
""")
cursor.execute("SELECT COUNT(*) FROM users")
if cursor.fetchone()[0] == 0:
cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", ("admin", "admin"))Ensure sales database exists
def init_sales_db():
with sqlite3.connect(SALES_DB) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS sales (
serial INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT,
name TEXT,
plot_number TEXT,
plot_size TEXT,
total_amount REAL,
paid_amount REAL,
balance_amount REAL,
date_time TEXT
)
""")Initialize databases
init_login_db()
init_sales_db()class LoginPage(QWidget):
def init(self):
super().init()
self.setWindowTitle("Login")
self.setGeometry(100, 100, 400, 300)layout = QVBoxLayout() # Title self.title = QLabel("ISLAMABAD GARDEN VALLEY") self.title.setFont(QFont("Arial", 16, QFont.Bold)) self.title.setStyleSheet("color: blue;") self.title.setAlignment(Qt.AlignCenter) layout.addWidget(self.title) # Username and Password self.username_label = QLabel("Username:") self.username_input = QLineEdit() self.password_label = QLabel("Password:") self.password_input = QLineEdit() self.password_input.setEchoMode(QLineEdit.Password) layout.addWidget(self.username_label) layout.addWidget(self.username_input) layout.addWidget(self.password_label) layout.addWidget(self.password_input) # Login Button self.login_button = QPushButton("Login") self.login_button.setStyleSheet("background-color: #0078D7; color: white; padding: 8px; font-size: 14px;") self.login_button.clicked.connect(self.login) layout.addWidget(self.login_button) # Footer self.footer = QLabel("REAL ESTATE SOFTWARE developed by TRUTH") self.footer.setFont(QFont("Arial", 10, QFont.Bold)) self.footer.setStyleSheet("color: red;") self.footer.setAlignment(Qt.AlignCenter) layout.addWidget(self.footer) self.setLayout(layout) def login(self): username = self.username_input.text() password = self.password_input.text() with sqlite3.connect(LOGIN_DB) as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password)) user = cursor.fetchone() if user: main_window.show() self.close() else: QMessageBox.warning(self, "Login Failed", "Invalid username or password!")
class AddRecordDialog(QDialog):
def init(self):
super().init()
self.setWindowTitle("Add New Record")
self.setGeometry(100, 100, 400, 300)layout = QFormLayout() self.user_id_input = QLineEdit() self.name_input = QLineEdit() self.plot_number_input = QLineEdit() self.plot_size_input = QLineEdit() self.total_amount_input = QSpinBox() self.total_amount_input.setMaximum(1000000000) self.paid_amount_input = QSpinBox() self.paid_amount_input.setMaximum(1000000000) layout.addRow("User ID:", self.user_id_input) layout.addRow("Name:", self.name_input) layout.addRow("Plot Number:", self.plot_number_input) layout.addRow("Plot Size:", self.plot_size_input) layout.addRow("Total Amount:", self.total_amount_input) layout.addRow("Paid Amount:", self.paid_amount_input) self.submit_button = QPushButton("Add Record") self.submit_button.setStyleSheet("background-color: #28A745; color: white; padding: 8px; font-size: 14px;") self.submit_button.clicked.connect(self.add_record) layout.addWidget(self.submit_button) self.setLayout(layout) def add_record(self): user_id = self.user_id_input.text() name = self.name_input.text() plot_number = self.plot_number_input.text() plot_size = self.plot_size_input.text() total_amount = self.total_amount_input.value() paid_amount = self.paid_amount_input.value() if not user_id or not name or not plot_number or not plot_size: QMessageBox.warning(self, "Input Error", "All fields must be filled!") return balance_amount = total_amount - paid_amount date_time = QDateTime.currentDateTime().toString() with sqlite3.connect(SALES_DB) as conn: cursor = conn.cursor() cursor.execute(""" INSERT INTO sales (user_id, name, plot_number, plot_size, total_amount, paid_amount, balance_amount, date_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, (user_id, name, plot_number, plot_size, total_amount, paid_amount, balance_amount, date_time)) main_window.update_table() self.accept()
class UserSettingsDialog(QDialog):
def init(self):
super().init()
self.setWindowTitle("User Settings")
self.setGeometry(100, 100, 400, 200)layout = QFormLayout() self.new_user_label = QLabel("New Username:") self.new_user_input = QLineEdit() self.new_password_label = QLabel("New Password:") self.new_password_input = QLineEdit() self.new_password_input.setEchoMode(QLineEdit.Password) self.save_button = QPushButton("Save") self.save_button.clicked.connect(self.save_user) layout.addRow(self.new_user_label, self.new_user_input) layout.addRow(self.new_password_label, self.new_password_input) layout.addWidget(self.save_button) self.setLayout(layout) def save_user(self): username = self.new_user_input.text() password = self.new_password_input.text() if username and password: with sqlite3.connect(LOGIN_DB) as conn: cursor = conn.cursor() cursor.execute("INSERT OR REPLACE INTO users (username, password) VALUES (?, ?)", (username, password)) QMessageBox.information(self, "Success", "User saved successfully!") self.accept() else: QMessageBox.warning(self, "Error", "Both fields are required!")
class MainPage(QMainWindow):
def init(self):
super().init()
self.setWindowTitle("REMS (Real Estate Management System)")
self.setGeometry(100, 100, 1000, 600)# Set background image self.setStyleSheet("background-image: url('c:/users/mohib/desktop/PP/Garden.jpg');") # Menu Bar self.menu_bar = self.menuBar() # Sales Menu self.sales_menu = self.menu_bar.addMenu("Sales") self.add_action = QAction("Add New Record", self) self.add_action.triggered.connect(self.open_add_record_dialog) self.sales_menu.addAction(self.add_action) self.edit_action = QAction("Edit Record", self) self.sales_menu.addAction(self.edit_action) self.delete_action = QAction("Delete Record", self) self.delete_action.triggered.connect(self.delete_record) self.sales_menu.addAction(self.delete_action) self.search_action = QAction("Search Record", self) self.sales_menu.addAction(self.search_action) # Print Menu self.print_menu = self.menu_bar.addMenu("Print") self.print_action = QAction("Print Record", self) self.print_action.triggered.connect(self.print_record) self.print_menu.addAction(self.print_action) # User Settings Menu self.settings_menu = self.menu_bar.addMenu("User Settings") self.user_settings_action = QAction("User Settings", self) self.user_settings_action.triggered.connect(self.open_user_settings) self.settings_menu.addAction(self.user_settings_action) # Logout Menu self.logout_menu = self.menu_bar.addMenu("Logout") self.logout_action = QAction("Logout", self) self.logout_action.triggered.connect(self.logout) self.logout_menu.addAction(self.logout_action) # Main Widget self.main_widget = QWidget() self.setCentralWidget(self.main_widget) # Table self.table = QTableWidget() self.table.setColumnCount(8) self.table.setHorizontalHeaderLabels([ "Serial", "User ID", "Name", "Plot Number", "Plot Size", "Total Amount", "Paid Amount", "Balance Amount", "Date & Time" ]) # Layout layout = QVBoxLayout() layout.addWidget(self.table) self.main_widget.setLayout(layout) self.update_table() def open_add_record_dialog(self): dialog = AddRecordDialog() dialog.exec_() def open_user_settings(self): dialog = UserSettingsDialog() dialog.exec_() def update_table(self): with sqlite3.connect(SALES_DB) as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM sales") records = cursor.fetchall() self.table.setRowCount(len(records)) for row, record in enumerate(records): for col, value in enumerate(record): self.table.setItem(row, col, QTableWidgetItem(str(value))) def delete_record(self): selected_row = self.table.currentRow() if selected_row < 0: QMessageBox.warning(self, "Selection Error", "No record selected to delete.") return serial = self.table.item(selected_row, 0).text() with sqlite3.connect(SALES_DB) as conn: cursor = conn.cursor() cursor.execute("DELETE FROM sales WHERE serial = ?", (serial,)) self.update_table() def print_record(self): selected_row = self.table.currentRow() if selected_row < 0: QMessageBox.warning(self, "Selection Error", "No record selected to print.") return # Get the details of the selected record def get_item_text(row, col): item = self.table.item(row, col) return item.text() if item else "" serial = get_item_text(selected_row, 0) user_id = get_item_text(selected_row, 1) name = get_item_text(selected_row, 2) plot_number = get_item_text(selected_row, 3) plot_size = get_item_text(selected_row, 4) total_amount = get_item_text(selected_row, 5) paid_amount = get_item_text(selected_row, 6) balance_amount = get_item_text(selected_row, 7) date_time = get_item_text(selected_row, 8) # Set up the QPrinter for printing printer = QPrinter(QPrinter.HighResolution) printer.setPageSize(QPrinter.A4) # Create the QPrintPreviewDialog preview_dialog = QPrintPreviewDialog(printer, self) # Check if the background image exists background_image_path = "c:/users/mohib/desktop/pp/pp.jpg" if not os.path.exists(background_image_path): QMessageBox.warning(self, "Error", "Background image not found!") return # Set up the custom painter function to print the content def custom_print(painter): if painter.begin(printer): painter.setPen(Qt.black) painter.setFont(QFont("Arial", 12)) # Draw the background image background_image = QPixmap(background_image_path) painter.drawPixmap(0, 0, background_image) # Text content to print text = f""" Serial: {serial} User ID: {user_id} Name: {name} Plot Number: {plot_number} Plot Size: {plot_size} Total Amount: {total_amount} Paid Amount: {paid_amount} Balance Amount: {balance_amount} Date & Time: {date_time} """ # Draw the text on the page painter.drawText(100, 100, text) painter.end() # Show the print preview dialog preview_dialog.paintRequested.connect(custom_print) preview_dialog.exec_() def logout(self): self.close() login_page.show()
Start Application
app = QApplication(sys.argv)
login_page = LoginPage()
main_window = MainPage()
login_page.show()
sys.exit(app.exec_()) -
@muhammad15 I repeat myself: please format your code properly when posting it! You're asking others to fix your code for you, but you do not even bother to format it correctly.
I'm not going to fix it for you. I wrote already that there is no begin() method in QPrinter, it is really not so hard to remove that begin() call in your code... -
@muhammad15 On the importance of naming things correctly and using typing in Python:
preview_dialog.paintRequested.connect(custom_print)
The paintRequested signal has a QPrinter parameter not a QPainter.
So declaring
def custom_print(printer: QPrinter):
Would have already helped you understand where your issue came from.