How to create installable (.exe) file from PyQT5 [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have created a GUI in Designer and used 'loadui' to add functionality. So basically, I have a .ui file for design and a .py file which contains the functions. Code in brief is below:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QFileDialog,QMainWindow,QMessageBox
from PyQt5.uic import loadUi
import pymssql
from sqlalchemy import create_engine
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
loadUi("MCQ1.ui",self)
self.BrowDB.clicked.connect(self.load_dbase)
self.SelectDB.clicked.connect(self.select_dbase)
def load_dbase(self):
engine = create_engine('mssql+pymssql://(local)')
query = "select name FROM sys.databases;"
data = pd.read_sql(query,engine)
def select_dbase(self):
global db_value
db_value = self.select_db.currentText()
self.ChosenDB.setText("Chosen DB: "+db_value)
return db_value
app = QApplication(sys.argv)
MainWindow = MainWindow()
widget = QtWidgets.QStackedWidget()
widget.addWidget(MainWindow)
widget.setFixedSize(900, 800)
widget.show()
sys.exit(app.exec_())
How do I create an installable (.exe) file with this?

Have a look at fman build system.
With this system, it is possible to create an executable file.
A few additional steps are required:
install fbs
create new fbs project via command line:
fbs startproject
modify the freshly created src/main/python/main.py by implementing your code:
from fbs_runtime.application_context.PyQt5 import ApplicationContext
# start of your code
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QFileDialog,QMainWindow,QMessageBox
from PyQt5.uic import loadUi
import pymssql
from sqlalchemy import create_engine
class MainWindow(QMainWindow):
# [...]
# end of your code
if __name__ == '__main__':
appctxt = ApplicationContext()
# minor modification to the template to start your window
window = MainWindow()
exit_code = appctxt.app.exec()
sys.exit(exit_code)
test if everything is set up correctly via command line:
fbs run
create exectutable via command line:
fbs freeze
Now you should have a new folder "target", which contains an executable of your program.
If you run into any trouble, check out the tutorial and the manual of fbs, which should cover most issues. Additionally, it further illustrates how to create an installer package from the executable file.

Related

QtCreator's UI is not applied to the window, it's always empty (Qt for Python)

I have a fresh QtCreator installation, and I set it up to run using a fresh install of Python3.8 on which I pip-installed both pyside2 and pyside6.
When I create a new Qt for Python - Window (UI file) application, whatever I do to the UI file the window always shows up empty and with the default size when I run the app.
I've tried with a QDialog, QMainApplication, using Pyside2 or Pyside6, I've checked that it was correctly loading the UI (and the right one) - no dice. It just won't update, and appears not to have any reason not to.
Default code for completeness:
# This Python file uses the following encoding: utf-8
import os
from pathlib import Path
import sys
from PySide2.QtWidgets import QApplication, QDialog
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader
class Dialog(QDialog):
def __init__(self):
super(Dialog, self).__init__()
self.load_ui()
def load_ui(self):
loader = QUiLoader()
path = os.fspath(Path(__file__).resolve().parent / "form.ui")
ui_file = QFile(path)
ui_file.open(QFile.ReadOnly)
loader.load(ui_file, self)
ui_file.close()
if __name__ == "__main__":
app = QApplication([])
widget = Dialog()
widget.show()
sys.exit(app.exec_())
(In the UI I just drag-dropped a button right in the middle and saved the file)
Am I forgetting something fundamental? I'm only used to programming in C++ using QtCreator.
I was expecting this to work right out of the box, but it's not.
This only dynamically load the UI as a new widget, with this custom class as a parent.
If I want signals and slots to work, the only thing I've found was to add a custom build step:
Command: <path to pyside6 install, use pip show to know where>\uic.exe
Arguments: <filename of the .ui file> -o <the python translation .py
which will serve as baseclass> -g python
Working directory: [your project dir]
Then signals and slots need to be connected manually, so QtCreator really only enables you to draw the user interface but all the logic still needs to be done by hand. Component variables are normally named after their UI name, but you can see for yourself in the baseclass file. This is a big step back from how QtCreator is used in C++ ("go to slot" will not work).
Code to use:
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
from YourGenPyFileName import Ui_YourUIName
class MainWindow(QMainWindow, Ui_YourUIName):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
if __name__ == "__main__":
app = QApplication([])
widget = MainWindow()
widget.show()
sys.exit(app.exec_())

PySide6 + Qt Creator, pysideplugin error results in gray screen

Every time I create a Window UI - Dynamic load project in Qt Creator v8.0.2 and run the project I get the following error:
error: qt.pysideplugin: Environment variable PYSIDE_DESIGNER_PLUGINS
is not set, bailing out.
As a result, the window doesn't display any widgets, it is just a gray empty window
I have tried to configure os.environ['PYSIDE_DESIGNER_PLUGINS'] = '.' but then I get the following error:
error: qt.pysideplugin: No python files found in '.'.
Is there a way to load the pysideplugin to Qt Creator v8.0.2 or to remove the errors related to it and make the project run and show the widgets?
I am testing with a very simple UI
But when I run the project I can only see the following:
The complete code in the mainwindow.py file is:
# This Python file uses the following encoding: utf-8
import os
from pathlib import Path
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.load_ui()
def load_ui(self):
loader = QUiLoader()
path = Path(__file__).resolve().parent / "form.ui"
ui_file = QFile(path)
ui_file.open(QFile.ReadOnly)
loader.load(ui_file, self)
ui_file.close()
if __name__ == "__main__":
#os.environ['PYSIDE_DESIGNER_PLUGINS']='.'
app = QApplication(sys.argv)
widget = MainWindow()
widget.show()
sys.exit(app.exec())
I am using python 3.10.5 and PySide6 version 6.4.0.1

Why is the word wrap (QTableWidget, PYQT5) painted differently when running .py from cmd than running with anaconda prompt?

I wrote a GUI in pyqt5 where you can enter two paths (file paths, directory paths, ...). Now my problem is the following:
(1) when I run it with the Anaconda Prompt window, and enter any longer path then it does the word wrap how I want it (and afai can tell correctly):
in this case using setTextElideMode works as well.
(2) when I run it with the windows command prompt (C:\[...]\Desktop>C:\[...]\python\3.8.1.0.0\python-3.8.1.amd64\python.exe C:\[...]\Desktop\cmd_problems.py) it begins wrapping the text directly after "C:" by inserting the normal ellipsis "..." - I have to stretch the column (manually) until the whole path is visible to make it show more than that:
using setTextElideMode does nothing.
Does anyone know how to get the first behavior when running the code from the windows cmd line? (I need this because I use a batch script to launch the program similar to making an .exe file.)
Here is my code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtWidgets import QTableWidget, QVBoxLayout
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Very Important Window")
cen = QWidget()
self.layout = QVBoxLayout()
self.setCentralWidget(cen)
cen.setLayout(self.layout)
self.tbl = QTableWidget()
self.tbl.setRowCount(1)
self.tbl.setColumnCount(2)
self.tbl.setTextElideMode(Qt.ElideRight)
col_names = ["FROM", "TO"]
self.tbl.setHorizontalHeaderLabels(col_names)
self.layout.addWidget(self.tbl)
def main():
app = QApplication([])
win = MyWindow()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

i have designed ui from pyqt designer now i want to connect that button and label together [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
How define find Qlabel, Qpushbutton and QlineEdit to fix that attribute error?
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
from PyQt5.uic import loadUiType
Ui, _ = loadUiType('tempconverter.ui')
class MainApp(QMainWindow , Ui):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
self.pushButton.clicked.connect(self.cal)
def cal(self):
temp = self.temp_in.text
far=int(temp)*9/5+32
self.answer.setText(str(far))
def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
app.exec_()
if __name__ == "__main__":
main()
Traceback (most recent call last):
File "d:/pythonproj/temp_test2.py", line 17, in cal
temp = self.temp_in.text
AttributeError: 'MainApp' object has no attribute 'temp_in'``
You should really consider posting the section from the .ui file where temp_in is defined, but I can see a couple of things wrong.
First, you have this line:
temp = self.temp_in.text
This should be:
temp = self.temp_in.text()
For QLineEdits to retrieve the text you need to run the function text() (it's not a parameter).
From the error message, it looks like you are using the wrong name for the QLineEdit. Is it possible that you are accidentally using the name for the QLabel? What might be helpful is to run pyuic5 to convert the .ui file to Python code. This will let you use code completion to see what elements are defined within your IDE.

How to determine what to import for, for example, the matchFlags used with QTreeWidget.findItems?

I am trying to use function QTreeWidget.findItems to find an exact match (the item is named "Things")
I saw an example using this ... Qt.MatchExactly ... as the 'match flag'.
even though i had imported Qt module from PyQt5, the MatchExactly was not found.
I got it to work by importing ANOTHER Qt module found in QtCore in PyQt5. but that was after many hours over several days of poking, guessing, and reading stackOverFlow posts.
My question is - how to know what module contains (and therefore must be imported) the stuff I need? how would I know that Qt.MatchExactly is in the PyQt5.QtCore.Qt module (and NOT in PyQt5.Qt module)?
This is my code: Note it reads in a QtDesigner .ui file, so its not gonna work for you. but having you run this code is not the point.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMainWindow, QApplication, QTreeWidgetItem
from PyQt5 import uic, QtWidgets, Qt #<<flags are not here
from PyQt5 import QtCore
from PyQt5.QtCore import Qt #<<<this is where i found the match flag "MatchExactly"
qtCreatorFile = "Main2.ui" # Enter qt Designer file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.InitModelContentTree()
def InitModelContentTree (self):
modelContentTree = self.ui.ModelContentTree
ThingsItemList = modelContentTree.findItems("Things", Qt.MatchExactly)
ThingsItem = ThingsItemList[0]
QTreeWidgetItem(ThingsItem, ["New Thing"])
print("pause")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
i'm hoping there is a decoder ring, some basic thing i'm missing. i'm proving to be a very bad, very inefficient guesser.
Actually Qt.MatchExactly is in Qt but you must import it in another way:
from PyQt5 import Qt
# ...
ThingsItemList = modelContentTree.findItems("Things", Qt.Qt.MatchExactly)
TL; DR
The Qt submodule is a fake module that allows access to any module such as an alias, for example it is similar to:
from PyQt5 import QtCore as Qt
from PyQt5 import QtGui as Qt
from PyQt5 import QtWidgets as Qt
# ...
# The same for all submodules
For example it can be checked for Qt.MatchExactly:
from PyQt5 import Qt, QtCore
assert(QtCore.Qt.MatchExactly == Qt.Qt.MatchExactly)
So in general the following import:
from PyQt5 import somemodule
somemodule.someclass
It is equivalent to:
from PyQt5 import Qt
Qt.someclass
How to know what submodule a class belongs to?: Well, if you have an IDE that can do a self-report like pycharm, the task is simple since the IDE itself does it. But if I do not have access to the IDE the other option is to use the docs of Qt, for example the docs of Qt::MatchExactly is in this link that in the first part is the following table:
And observe Qt += core so all the elements of that docs belong to the core sub-module of Qt that in PyQt/PySide corresponds to QtCore (in general if the docs of Qt indicate Qt += mymodule in PyQt/PySide in QtMyModule).Also the Qt::MatchExactly of C ++ corresponds to Qt.MatchExactly in python. So in conclusion you should use:
from PyQt5 import QtCore
QtCore.Qt.MatchExactly

Categories