I tried to load Ui file from Python script as follow.
from PyQt5 import uic, QtWidgets
import sys
class Ui(QtWidgets.QDialog):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi('SomeUi.ui', self)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.ex
When I debug and reach to the line window = Ui(), I have error as
-> window = Ui()
(Pdb) n
TypeError: TypeErro...ndow')),)
What is wrong with my code?
You can compile .ui file into .py file by pyuic utility, which is part of PyQt.
Find the utility somewhere in python dist-packages, for example, on my system (debian linux), it's placed in
/usr/lib/python3/dist-packages/PyQt5/uic/pyuic.py
Run it with python, specifying source .ui file and -o parameter with result py file.
cd /usr/lib/python3/dist-packages/PyQt5/uic/
python3 ./pyuic.py /home/user/my-app/my-file.ui -o /home/user/my-app/my-file.py
You'll get .py file, that would contain something like this:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(555, 470)
// and so on... lots of lines...
Import this file, and subclass this Ui_MainWindow (the name can be different) by your window class.
Related
Is there a way to change default menu title for native menu on MacOS for a simple pyqt5 app?
I'm trying to change "Python" menu entry on above image. Is there a way to rename it? Can I hide it somehow?
This code prints only "File":
menubar = self.menuBar()
for item in menubar.actions():
print(item.text())
menubar.setNativeMenuBar(False) doesn't help too (just move "File" into the MainWindow).
Update Sample app code:
from PyQt5 import QtCore, QtWidgets, uic
import sys
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
# QtCore.QCoreApplication.setApplicationName('QtFoo') # doesn't work
uic.loadUi('App.ui', self)
self.show()
# app = QtWidgets.QApplication(sys.argv)
app = QtWidgets.QApplication(["MyCoolApp"])
# app.setApplicationName("QtFoo") # doesn't work
# app.setApplicationDisplayName("Display Name")
window = Ui()
app.exec()
If you are not willing to package your app, you could create a temporary symbolic link to python as described here. This link can be used to execute python apps while displaying a custom name in the title bar:
go to the location of your app (e.g. my_app.py) file in the terminal
create symbolic link (replace location to your python interpreter, replace "BeautifulNaming" with desired name)
ln -s /Users/Christian/miniconda3/bin/python BeautifulNaming
call link to python with your script
./BeautifulNaming my_app.py
The "python" in the system menu bar appears because you run the script from the python, as soon as you package the application the title will disappear. For example the following code
# FileName PyQt5MenuProblem.py
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow
class AppTest(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("My application")
self._createMenuBar()
def _createMenuBar(self):
self.menuBar = self.menuBar()
self.menuBar.setNativeMenuBar(False)
fileMenu = self.menuBar.addMenu("&File")
editMenu = self.menuBar.addMenu("&Edit")
if __name__== "__main__":
app = QApplication(sys.argv)
plotWindow = AppTest()
plotWindow.showMaximized()
sys.exit(app.exec_())
after packaging with
pyinstaller --onefile PyQt5MenuProblem.py
looks like
Key words: MacOS, User Interface, LSUIElement, pyinstaller, pyqt5
I'm still new with python and Qt designer. I would like to develop an application where user need to press the 'pushbutton' in order to view the image(from local directory path) on GUI mainwindow.This will keep repeating until complete number of cycle.
Did tried using QLabel and QGraphiscView widget but doesn't work.(probably due to lack of knowledge). Could anyone help me to solve it?
Below is the code:
#!/usr/bin/env python
from __future__ import division
import sys
from PyQt4 import QtCore, QtGui, uic
gui_file = 'image.ui'
Ui_MainWindow, QtBaseClass = uic.loadUiType(gui_file)
class showImage(QtGui.QMainWindow,Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.get_image_button.clicked.connect(self.getImage)
def getImage(self):
image_path='c:/Users/mohd_faizal4/Desktop/Python/Image/image1.jpg' #path to image file
self.label_image.QPixmap(image_path)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
myWindow = showImage()
myWindow.show()
sys.exit()
app.exec_()
Really appreciate!
In Pycharm 4.5.2, if I had an error in PyQt5 slots, when the slots was called, Pycharm only shows Process finished with exit code 1, but not where and why the error happends. This doesn't happen when the error is in __init__.
It makes it very difficult to debug. How do I fix this?
This widget is generated by Qt Designer
For example, if I wrote button.setText('a'+1) when clicked on the button:
# -*- coding: utf-8 -*-
import sys
from PyQt5 import Qt
from test import Ui_Form
Application = Qt.QApplication(sys.argv)
class myWidget(Qt.QWidget):
def __init__(self):
super(myWidget, self).__init__()
self.main = Ui_Form()
self.main.setupUi(self)
# self.main.pushButton.setText('a'+1)
# prints `TypeError: Can't convert 'int' object to str implicitly ` normally
self.show()
self.main.pushButton.clicked.connect(self.show_error)
def show_error(self):
self.main.pushButton.setText('a'+1)
# only print "Process finished with exit code 1" when clicked on the button, and crash.
my_Qt_Program = myWidget()
my_Qt_Program.show()
sys.exit(Application.exec_())
It works fine in windows console:
test.py(generated by Qt Designer):
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.5
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(115, 58)
self.verticalLayout = QtWidgets.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "Show \'a\' +1"))
As has been pointed out in the comments and indeed suggested on this pycharm thread:
In your run configuration, enable the option Emulate terminal in output console. You can find this in the Execution section.
Running your example
On my machine (Windows 10, PyCharm Professional 2018.3.1) this changed the behaviour when clicking the show 'a' + 1 button from exiting with exit code (-1073740791 (0xC0000409)) to showing
Traceback (most recent call last):
File "path/to/file/so.py", line 25, in show_error
self.main.pushButton.setText('a' + 1)
TypeError: can only concatenate str (not "int") to str
In order to run your example I had to change
from PyQt5 import Qt
into
from PyQt5.QtWidgets import QApplication, QWidget
and change the Qt.Q... calls into Q... accordingly, but this might depend on my setup.
Perhaps not exactly what you want but this works for me:
import logging
def main():
x = 1/0
if __name__ == '__main__':
logging.basicConfig(level='INFO')
main()
Edit: The above mention method works if you got a single file but it doesnt fix the root of the problem
A better anwser can be found here PyQt: No error msg (traceback) on exit
This example creates a single QListWidget with its items right-click enabled.
Right-click brings up QMenu. Choosing a menu opens a OS File Browser in a current user's home directory.
After a File Browser is closed QMenu re-appears which is very annoying.
How to avoid this undesirable behavior?
import sys, subprocess
from os.path import expanduser
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.listWidget = QtGui.QListWidget()
self.listWidget.addItems(('One','Two','Three','Four','Five'))
self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listWidget.connect(self.listWidget,QtCore.SIGNAL('customContextMenuRequested(QPoint)'),self.showMenu)
self.menu=QtGui.QMenu()
menuItem=self.menu.addAction('Open Folder')
self.connect(menuItem,QtCore.SIGNAL('triggered()'),self.openFolder)
layout.addWidget(self.listWidget)
def showMenu(self, QPos):
parentPosition=self.listWidget.mapToGlobal(QtCore.QPoint(0, 0))
menuPosition=parentPosition+QPos
self.menu.move(menuPosition)
self.menu.show()
def openFolder(self):
if sys.platform.startswith('darwin'):
subprocess.call(['open', '-R',expanduser('~')])
if sys.platform.startswith('win'):
subprocess.call(['explorer','"%s"'%expanduser('~')])
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Two ideas come to my mind:
Try adding self as a constructor parameter when defining QMenu(), passing your QWidget as a parent.
Call self.menu.hide() in the openFolder() method.
Tip: instead of using subprocess to open up explorer, there's an arguably better, cross platform solution in Qt called QDesktopServices - see http://pyqt.sourceforge.net/Docs/PyQt4/qdesktopservices.html
I am a bit of a novice so be kind ;-)
I had a GUI that I made using PyQt4 and python 2.6 with a working file dialog, (ie you clicked a button and a window popped up and allowed you to pick a file to load/save). The code for the GUI is like 2000 lines, so i will include the bits i think are important:
from PyQt4 import QtGui as qt
from PyQt4 import QtCore as qc
class NuclearMotion(qt.QWidget):
def __init__(self, parent=None):
super(NuclearMotion, self).__init__(parent)
file_button = qt.QPushButton("Use data from file")
mainLayout = qt.QGridLayout()
mainLayout.addWidget(file_button, 14, 8, 1, 2)
def choose_file():
file_name = qt.QFileDialog.getOpenFileName(self, "Open Data File", "", "CSV data files (*.csv)")
self.connect(file_button, qc.SIGNAL("clicked()"), choose_file)
self.setLayout(mainLayout)
if __name__ == '__main__':
import sys
app = qt.QApplication(sys.argv)
NuclearMotionWidget = NuclearMotion()
NuclearMotionWidget.show()
sys.exit(app.exec_())
The above works absolutely fine. I typed all the code for it manually using various tutorials. I have now made a new GUI using QT designer and pyuic4 to convert it to a .py file. Now I can't make the file dialog work. The below code results in a Type error:
from PyQt4 import QtCore, QtGui
class Ui_mainLayout(object):
def setupUi(self, mainLayout):
mainLayout.setObjectName(_fromUtf8("mainLayout"))
mainLayout.resize(598, 335)
mainLayout.setTabPosition(QtGui.QTabWidget.North)
mainLayout.setTabShape(QtGui.QTabWidget.Rounded)
mainLayout.setElideMode(QtCore.Qt.ElideLeft)
self.basic_tab = QtGui.QWidget()
self.file_button = QtGui.QPushButton(self.basic_tab)
QtCore.QObject.connect(self.file_button, QtCore.SIGNAL("clicked()"), self.choose_file)
def choose_file(self):
file_name = QtGui.QFileDialog.getOpenFileName(self, "Open Data File", "", "CSV data files (*.csv)")
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
mainLayout = QtGui.QTabWidget()
ui = Ui_mainLayout()
ui.setupUi(mainLayout)
mainLayout.show()
sys.exit(app.exec_())
This code produces the GUI just fine and everything else works ok including signals. Any idea what I am doing wrong!?
Your class should inherit (directly or indirectly) from QtCore.QObject to be able to handle signals. The first one inherits from QWidget, which does the job.