Source: QPSQL driver not loaded: Using Postgres with Qt & Python on Windows
Setting PATH to use the Postgres library
If you’re trying to use Postgres with PyQt5/6 or PySide2/PySide6 you may have come across an issue with loading the driver. Qt (correctly) lists the driver as available in Qt, but when trying to load it the load will fail. This is because the Qt library depends on Postgres’ own library, which must be available in the path to load.
Executing the above script in a new command prompt will give the following output (if Postgres is not accessible).
>python test.py
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QODBC QODBC3 QPSQL QPSQL7
Available drivers ['QSQLITE', 'QODBC', 'QODBC3', 'QPSQL', 'QPSQL7']
Unable to connect.
Last error Driver not loaded Driver not loaded
The list of “available drivers” shows the Qt drivers which are available in your PyQt5 (or PyQt6, or PySide2, or PySide6) installation. For example, in my installation the driver files are under site-packages\PyQt5\Qt5\plugins\sqldrivers
C:\Users\Martin\AppData\Local\Programs\Python\Python37\Lib\site-packages\PyQt5\Qt5\plugins\sqldrivers> dir
Volume in drive C has no label.
Volume Serial Number is 0A6A-65ED
Directory of C:\Users\Martin\AppData\Local\Programs\Python\Python37\Lib\site-packages\PyQt5\Qt5\plugins\sqldrivers
02/12/2021 14:35 <DIR> .
02/12/2021 14:35 <DIR> ..
02/12/2021 14:35 1,412,080 qsqlite.dll
02/12/2021 14:35 98,288 qsqlodbc.dll
02/12/2021 14:35 79,856 qsqlpsql.dll
3 File(s) 1,590,224 bytes
2 Dir(s) 174,429,970,432 bytes free
The Driver not loaded error is occurring because the Qt Postgres driver cannot find the Postgres libraries. The Qt Postgres driver is a wrapper around these libraries, rather than a complete implementation of Postgres itself.
To get this working you need to ensure the required Postgres library files are available in your path. You can do this by adding your Postgres installation bin
folder to your path. For example, on my computer Postgres is installed under C:\Program Files\PostgreSQL\14\
(I’m using version 14). We need to add to the Postgres bin
folder to the PATH
as this contains libpq.dll
(Postgres Access Library) which Qt needs.
SET PATH=%PATH%;C:\Program Files\PostgreSQL\14\bin
With that in place, running the script again will show that that driver has loaded successfully. The connection still isn’t working, since it needs the username and password set. But if you get this far you know the driver is working properly.