Friday, April 2, 2021

Setting up PyQt5 in PyCharm 2020.3.5 on Fedora 33 Server

*************************************************************

Update as of 04/11/2021. See also Setting up PyQt5 in PyCharm 2021.1 on AlmaLinux 8.3

*************************************************************

Following below is a brief description to enable PyCharm 2020.3.5 to execute python scripts been written with PyQT5 bindings involved.

PyQt5 is a comprehensive set of Python bindings for Qt v5. It is implemented as more than 35 extension modules and enables Python to be used as an alternative application development language to C++ on all supported platforms including iOS and Android.

First install packages :-

$ sudo dnf install qt5-qtbase-devel

$ sudo dnf install PyQt5 

$ sudo dnf install qt5-designer

Afterward install the most recent version of PyCharm on Linux.

Start PyCharm via desktop link to shell executable

(KDE Desktop environment)

Per https://pythonpyqt.com/how-to-install-pyqt5-in-pycharm/

Step 1 Create a new project

Step 2 Set the default PyCharm parser.

Select File | Settings | Project: first | Project Interpreter, set Project Interpreter to The version of python you are using

Step 3 Adding third-party libraries. Stay in the Project Interpreter interface, click on the +, find and install pyqt5pyqt5-sippyqt5-tools. After successful installation, the interface should look like this.















Step 4 Configuring QtDesigner

Due to qt5-designer has been installed, configure it in PyCharm 

Then configure PyUIC tools

Arguments: -m PyQt5.uic.pyuic $FileName$ -o $FileNameWithoutExtension$.py

PyCharm select File | Settings | Tools | PyCharm. External Tools, click + New Tools



















SQLITE3 Database administration via PyQT5 Framework in PyCharm 3.5 Environment Database administration via PyQT5 Framework in PyCharm 3.5 EnvironmentNow test at run time  code from link mentioned above  https://realpython.com/python-pyqt-layout/

import sys
 2
 3from PyQt5.QtWidgets import (
 4    QApplication,
 5    QComboBox,
 6    QFormLayout,
 7    QLineEdit,
 8    QStackedLayout,
 9    QVBoxLayout,
10    QWidget,
11)
12
13class Window(QWidget):
14    def __init__(self):
15        super().__init__()
16        self.setWindowTitle("QStackedLayout Example")
17        # Create a top-level layout
18        layout = QVBoxLayout()
19        self.setLayout(layout)
20        # Create and connect the combo box to switch between pages
21        self.pageCombo = QComboBox()
22        self.pageCombo.addItems(["Page 1", "Page 2"])
23        self.pageCombo.activated.connect(self.switchPage)
24        # Create the stacked layout
25        self.stackedLayout = QStackedLayout()
26        # Create the first page
27        self.page1 = QWidget()
28        self.page1Layout = QFormLayout()
29        self.page1Layout.addRow("Name:", QLineEdit())
30        self.page1Layout.addRow("Address:", QLineEdit())
31        self.page1.setLayout(self.page1Layout)
32        self.stackedLayout.addWidget(self.page1)
33        # Create the second page
34        self.page2 = QWidget()
35        self.page2Layout = QFormLayout()
36        self.page2Layout.addRow("Job:", QLineEdit())
37        self.page2Layout.addRow("Department:", QLineEdit())
38        self.page2.setLayout(self.page2Layout)
39        self.stackedLayout.addWidget(self.page2)
40        # Add the combo box and the stacked layout to the top-level layout
41        layout.addWidget(self.pageCombo)
42        layout.addLayout(self.stackedLayout)
43
44    def switchPage(self):
45        self.stackedLayout.setCurrentIndex(self.pageCombo.currentIndex())
46
47if __name__ == "__main__":
48    app = QApplication(sys.argv)
49    window = Window()
50    window.show()
51    sys.exit(app.exec_())





























Another sample


















OLD PROGRAMMER'S CODE @ YANDEX.ZEN

#!/usr/bin/python3
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog
from PyQt5.QtWidgets import QLabel
from PyQt5.QtCore import Qt, QSize
import sys
class win(QWidget):
   def __init__(self,x, y, dx, dy):
       super().__init__()
       self.setGeometry(x, y, dx, dy)
       self.setWindowTitle('Picture in window')
       fn = QFileDialog.getOpenFileName(self, \
         'Select a picture', '', '*.jpg *.png *.gif *.bmp')
       self.pix = QPixmap(fn[0])
       self.im = QLabel(self)
       self.im.move(0, 0)
       self.pix = self.pix.scaled(QSize(dx, dy), \
         Qt.KeepAspectRatio, Qt.SmoothTransformation);
       self.im.setPixmap(self.pix)
       self.setFixedSize(self.pix.width(), self.pix.height())
app = QApplication(sys.argv)
ex = win(50, 50, 800, 700)
ex.show()
sys.exit(app.exec())



































======================================================

SQLITE3 Database administration via PyQT5 Framework in PyCharm 3.5 Environment

======================================================

making minor changes to original code on Fedora 33 Server having previously enabled PyQT5 support by PyCharm

[boris@fedora33server PYQT]$ cat sqlcreate.py
import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
con = QSqlDatabase.addDatabase("QSQLITE")
con.setDatabaseName("contacts.sqlite")

if not con.open():
    print("Database Error: %s" % con.lastError().databaseText())
    sys.exit(1)

# Create a query and execute it right away using .exec()
createTableQuery = QSqlQuery()
createTableQuery.exec(
    """
    CREATE TABLE contacts (
        id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
        name VARCHAR(40) NOT NULL,
        job VARCHAR(50),
        email VARCHAR(40) NOT NULL
    )
    """
)
print(con.tables())

Loading data into created table

[boris@fedora33server PYQT]$ cat sql02.py
from PyQt5.QtSql import QSqlQuery, QSqlDatabase

con = QSqlDatabase.addDatabase("QSQLITE")
con.setDatabaseName("contacts.sqlite")
con.open()
insertDataQuery = QSqlQuery()
insertDataQuery.prepare(
    """
    INSERT INTO contacts (
        name,
        job,
        email
    )
    VALUES (?, ?, ?)
    """
)
data = [
    ("Joe", "Senior Web Developer", "joe@example.com"),
    ("Lara", "Project Manager", "lara@example.com"),
    ("David", "Data Analyst", "david@example.com"),
    ("Jane", "Senior Python Developer", "jane@example.com"),
]
# Use .addBindValue() to insert data
for name, job, email in data:
    insertDataQuery.addBindValue(name)
    insertDataQuery.addBindValue(job)
    insertDataQuery.addBindValue(email)
    insertDataQuery.exec()

[boris@fedora33server PYQT]$ cat sqliteditor.py
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import (
    QApplication,
    QMainWindow,
    QMessageBox,
    QTableView,
)
class Contacts(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("QTableView Example")
        self.resize(415, 200)
        # Set up the model
        self.model = QSqlTableModel(self)
        self.model.setTable("contacts")
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.setHeaderData(0, Qt.Horizontal, "ID")
        self.model.setHeaderData(1, Qt.Horizontal, "Name")
        self.model.setHeaderData(2, Qt.Horizontal, "Job")
        self.model.setHeaderData(3, Qt.Horizontal, "Email")
        self.model.select()
        # Set up the view
        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.resizeColumnsToContents()
        self.setCentralWidget(self.view)

def createConnection():
    con = QSqlDatabase.addDatabase("QSQLITE")
    con.setDatabaseName("contacts.sqlite")
    if not con.open():
        QMessageBox.critical(
            None,
            "QTableView Example - Error!",
            "Database Error: %s" % con.lastError().databaseText(),
        )
        return False
    return True

app = QApplication(sys.argv)
if not createConnection():
    sys.exit(1)
win = Contacts()
win.show()
sys.exit(app.exec_())
































No comments:

Post a Comment