Pyqt English to Finnish Translation - python

I want to convert the langauge of pyqt application from english to finnish . I saw that pyqt has some methods for it and i try to use it but it didnt help me
app = QtGui.QApplication(sys.argv)
translator = QtCore.QTranslator()
translator.load("qt_fr.qm")
app.installTranslator(translator)
.qm file is present at right path (right now its taking french i guess) and on button i use this text
name = "File"
button.setText(self.tr(QtCore.QString(name)))

It seems you are mixing two things: the translations of Qt itself (which are provided via qt_xx.qm files and distributed along with Qt) and your own translations.
Here you have an example using the russian translation file of Qt itself:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyWindow(QWidget):
def __init__(self, parent=None):
super(QWidget, self).__init__(parent)
self.hbox = QHBoxLayout(self)
self.myButtons = QDialogButtonBox(self)
self.hbox.addWidget(self.myButtons)
button = self.myButtons.addButton(QDialogButtonBox.Open)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
translator = QTranslator()
print translator.load("qt_ru", QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app.installTranslator(translator)
ui = MyWindow()
ui.show()
sys.exit(app.exec_())
If you need your own translations then the Produce translations section of the i18n with Qt can be of help to you. You will need to provide a project file, your translation files (.ts) and use the Qt Linguist tool.
You can mix both the Qt itself translation and your own app translation by installing multiple translators.
Please note that when loading the translator you don't have to add the .qm extension to the filename.

Please read the Qt Manual on Translation or just have a look at a very basic yet illustrative example here: http://doc.qt.digia.com/qt/linguist-hellotr.html. Please note: you may need to provide the translation files yourself using f.i. Qt Linguist.

If you're doing this inside your window's __init__(), you must save (retain a reference to) your translator:
self.translator = translator
Otherwise your translator will get garbage-collected, even after installation. In that case, self.tr() will stop working (fails silently).

Related

How could I implement live markdown preview in the same text input box?

I'm building a note-taking GUI with QT Designer and Python. I'm envisioning something that saves the notes as *.txt files with simple markdown. For the GUI, however, I'd like the main text editing box to be able to render markdown live while you're in "edit mode" and typing away. So if you typed *italic* or **bold**, the text box would recognize this and italicize or bold it with those markdown symbols still in the text. Once you exit "edit mode," you'd be left with a preview of the note properly formatted with rich text and none of the markdown symbols. If anybody is familiar with Notable, I'm pretty much looking to replicate that (honorable mention would be the Bear app as well, but that functions differently in that it always stays in the "live preview" mode).
I'm trying to figure out how to go about this with QT and Python and this is all I could come up with so far:
There's a example on the QT website that demonstrates a live preview using QWebEngineView, but that's side-by-side with a normal text box and not what I had in mind.
I wonder if this could also be implemented with some sort of syntax highlighting? So in that sense, I'd be building more a code editor or something? So the QT text box would be configured (as rich text or HTML? I don't know) so that any instances of *(italic text)* would get the italicized formatting the moment you finished typing that second asterisk. I guess in the syntax highlighting definition, I'd be able to use some sort of wildcard character to say "anything between these markdown symbols?"
Does anybody have any suggestions on a solution?
Since Qt 5.14 QTextEdit supports the markdown format so you can use 2 QTextEdit that show the different editing modes. To swap the QTextEdit you can use a QStackedWidget:
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.stacked_widget = QtWidgets.QStackedWidget()
self.setCentralWidget(self.stacked_widget)
self.markdown_editor = QtWidgets.QTextEdit()
self.markdown_viewer = QtWidgets.QTextEdit(readOnly=True)
self.stacked_widget.addWidget(self.markdown_editor)
self.stacked_widget.addWidget(self.markdown_viewer)
foo_menu = self.menuBar().addMenu("&FooMenu")
self.edit_action = foo_menu.addAction("&Edit")
self.edit_action.setCheckable(True)
self.edit_action.triggered.connect(self.handle_edit_mode)
def handle_edit_mode(self):
self.stacked_widget.setCurrentWidget(
self.markdown_viewer
if self.edit_action.isChecked()
else self.markdown_editor
)
if self.stacked_widget.currentWidget() == self.markdown_viewer:
self.markdown_viewer.setMarkdown(self.markdown_editor.toPlainText())
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

PyInstaller generated exe file error : qt.qpa.plugin: could not load the qt platform plugin "windows" in "" even though it was found

I have created a program to read certain data from files on a drive, display results on a PyQt5 ui and accept corrections if any from user.
The program worked fine when run as a python file. However, when i converted it into a standalone exe using PyInstaller, it works fine upto the point where the pyqt5 gui needs to be launched. At this point, it stops throwing the following error :
qt.qpa.plugin: Could not load the Qt platform plugin "windows" in "" even though it was found. This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. Available platform plugins are: minimal, offscreen, windows.
I have read this, this and this but they dont resolve my issue.
The code of the gui is very big but here is the structure :
from PyQt5 import uic, QtWidgets
import sys
import os
#baseUIClass, baseUIWidget = uic.loadUiType('gui.ui')
baseUIClass, baseUIWidget = uic.loadUiType(r'C:\mypath\gui.ui')
class Ui(baseUIClass, baseUIWidget ):
def __init__(self, *args, **kwargs):
baseUIWidget.__init__(self, *args, **kwargs)
self.setupUi(self)
# More code to perform the desired actions
def run(input_variables):
app = QtWidgets.QApplication(sys.argv)
ui = Ui()
ui.show()
# More code to make the Ui perform desired actions
app.exec_()
return(output_variables)
The code was converted to a standalone exe with the following arguments :
pyinstaller --hiddenimport <hidden import> --onefile <python filename>
Would you know how to troubleshoot this please?
Thanks
I ran into the same error message with my compiled application.
To track down the issue, I first stripped down the app to its skeleton with minimal imports, which worked flawlessly when compiled. I then partially added back all imports of my "big" application until the error reappeared.
In the end (for me at least) pandas is the culprit:
Minimal reproducibale examples, this works:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
window = QtWidgets.QMainWindow()
window.show()
app.exec()
This (added pandas import in line 2) throws the error you describe:
from PyQt5 import QtWidgets
import pandas as pd # import after pyqt5
app = QtWidgets.QApplication([])
window = QtWidgets.QMainWindow()
window.show()
app.exec()
However, when first importing pandas and then importing PyQt 5, my compiled version works again:
import pandas as pd # import before pyqt5
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
window = QtWidgets.QMainWindow()
window.show()
app.exec()
So, in my case the solution was to track down the "erroneous import", fiddle with the import order and get lucky (I am far too unexperienced to even try to understand why the import order leads to this error)
If you are not using pandas, maybe the whole "strip down to skeleton and start importing piece by piece"-approach will help you to further clarify the root cause of the error.
If you are using pandas and the order switch-up did not help, there is another thread which describes which tries to deal with pandas compiling issues.

Correct way to address Pyside Qt widgets from a .ui file via Python

I have created a GUI with Qt Designer and accessed it via
def loadUiWidget(uifilename, parent=None):
loader = QtUiTools.QUiLoader()
uifile = QtCore.QFile(uifilename)
uifile.open(QtCore.QFile.ReadOnly)
ui = loader.load(uifile, parent)
uifile.close()
return ui
MainWindow = loadUiWidget("form.ui")
MainWindow.show()
children = MainWindow.children()
button1 = MainWindow.QPushButton1
"children" does already contain the widgets "QPushButton1", "QTextBrowser1" created in the UI but shouldn't the be accessed by the recoursive findChildren() method?
What is an elegant way to access the widgets of the .ui File?
References:
Find correct instance,
Load .ui file
Since widget names in Qt Designer must be unique, the hierarchy (at least for getting references to the widgets) is flattened (with no risk of conflict), and so the best way is just to access them via:
loader = QtUiTools.QUiLoader()
ui = loader.load('filename.ui', parent)
my_widget = ui.my_widget_name
This would place a reference to the widget called 'my_widget_name' in Qt Designer in the variable my_widget.
I would say the above is the most pythonic way of accessing the widgets created when you load the .ui file.
There are two disadvantages of loading UI at run time:
overhead each time the program is run (actually, each time the loader is used)
lack of support of code completion and checking, since IDE doesn't know the code behind ui until the uifile has been loaded.
An alternative, assuming you are using the modern version of PySide called "Qt for Python", is to "compile" the .ui file to a Python class (see docs). For this, after saving filename.ui, execute
pyside2-uic filename.ui -o ui_mainwindow.py
while within your virtual environment, if any. The new class will be called Ui_MainWindow. Assuming you have a text_box widget in your UI, you can now access its properties and methods. Here is a full working example:
import sys
from PySide2.QtWidgets import QApplication, QMainWindow
from ui_mainwindow import Ui_MainWindow
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.text_box.setPlainText('test') # here we are addressing widget
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Notes:
pyside2-uic should be called after every change of the .ui file. This is a disadvantage of this approach in comparison to OP. It also means that you should either version-control both .ui and .py files for your UI, or somehow call uic during deployment.
The big advantage is that IDE like PyCharm has access to all widget methods and properties for autocompletion and code checking.
As of today, pyside2-uic creates non-PEP8 compliant code. However, as long as you give your widgets PEP8-compliant names, your own code will be OK.

Using Qt designer and python in ubuntu

I am a new Ubuntu user and want to do my coding using Python and incorporating Qt designer for my forms (interface). I open the designer and put up some controls on the forms or widgets but I get problems on how to include the form I made in my Python codes. I try using the Import style for my .ui but to no avail. Please help on how I should go about this issue. Here is what I have: Mwakenya is the .ui file I created on Qt designer.
from pyQt import *
from mwakenya.ui import *
class at(mwakenya):
def __init__(self, parent=None, name=None, fl=0):
mwakenya.__init__(self,parent,name,fl)
if __name__ == "__main__":
import sys
a = QApplication(sys.argv)
QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
w = at()
a.setMainWidget(w)
w.show()
a.exec_loop()
You need to compile your .ui files, into python code.
You can do this with the pyuic command.
eg.
pyuic mwakenya.ui -o mwakenya_ui.py
You then import mwakenya_ui.py
See here for more information:
http://manpages.ubuntu.com/manpages/hardy/man1/pyuic4.1.html
Users of KDE should look for pykdeuic, which performs the same job.

How to create full transparency in a QTextEdit

I have been trying for many days to figure out a way to create a transparent Qtextedit with opaque text. Because the term "transparency" is often ambiguous, I define Qtextedit"transparency" as being able to see the text in the Qtextedit overlaid upon whatever is directly behind the main window (such as the desktop background, windows media player etc.) If possible I would like to be able to set the transparency at various levels and cross system compatible, but this is not required.
I am an extreme beginner, as I have only been using pyqt4 for 3 weeks and python 3.x for a few months and this is all the experience with programming that I have obtained in my existence. I have been attempting to decipher the Pyqt documentation with regard to this matter, but it is written in a way that seems to assume that one has been a gui programer for decades, not to mention having knowlege of C++. Furthermore, when this question is asked online it never seems to be resolved in way that is either: a) well documented or b) generalizable
This is very surprising because it seems like a basic operation that people would want to do
This solution works but doesn't seem to be directly useful for anything but displaying transparent images. I also don't really understand it all that well, as simply changing the base class from QWidget to QMainWindow makes the whole thing fail
http://www.loopbacking.info/blog/2008/07/11/transparent-windows-howto/
The following link embodies the common ways people suggest to solve problems similar to this, their pitfalls and why they don't work, but unfortunately they use the C++ version of Qt and are also a bit advanced for my skills at this point.
http://www.qtcentre.org/threads/18072-How-to-set-Qt-window-transparent
My system is windows 7 ultimate 32 bit on a dell latitude d830 with a Quadro NVS 140 whose driver version is current as of this post (Verde 275.33) My version of Pyqt is 4.8 (PyQt-Py3.2-x86-gpl-4.8.5-1.exe Windows 32 bit installer) I am also using Python 3.2.1 (Open Source version)
A basic example of my code lies beneath with the relevant (and failed) lines commented out:
When I tried the commented out code the color I generally just saw blackness. Also, when I resized my windows the darkness would randomly change intensity and the display of the main window seemed to get corrupted when maximized.
I would greatly appreciate any help on this matter!
import sys
import PyQt4
from PyQt4 import QtGui, QtCore
class Transparent(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
self.initialize()
def initialize(self):
#self.colorset(self,'Window',200,255,100,20)
#self.colorset(self,'Base',200,255,100,20)
#self.setBackgroundRole(QtGui.QPalette.Base)
#self.setAttribute(QtCore.Qt.WA_NoSystemBackground)
#self.setAutoFillBackground(True)
#self.mask()
self.setWindowTitle("Chernobyl-like Failure")
self.answerlabel = QtGui.QLabel('Text Response Display')
self.answerlabel.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised)
self.answerlabel.setMinimumHeight(25)
self.questionlabel = QtGui.QLabel("Question:")
self.questionlabel.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised)
self.questionbox = QtGui.QLineEdit()
self.questionbox.setMinimumWidth(500)
self.askbutton = QtGui.QPushButton("Ask it!")
self.historybox = QtGui.QTextEdit('Question & Answer history will be displayed here')
self.historybox.setReadOnly(True)
#self.colorset(self.historybox,'Base',200,255,100,127)
self.grid = QtGui.QGridLayout()
widgetlist = [['answerlabel',0,0,1,3],['questionlabel',1,0,1,1],
['questionbox',1,1,1,1],['askbutton',1,2,1,1],['historybox',2,0,1,3]]
for widget in widgetlist:
self.grid.addWidget(eval("self.{0}".format(widget[0])),*widget[1:])
self.centralwidget = QtGui.QFrame()
self.centralwidget.setFrameStyle(QtGui.QFrame.Box|QtGui.QFrame.Raised)
self.centralwidget.setLineWidth(5)
self.centralwidget.setLayout(self.grid)
#self.colorset(self.centralwidget,'Base',200,255,100,127)
self.setCentralWidget(self.centralwidget)
def colorset(self,widget,part,h,s,l,a):
pal = widget.palette()
color = QtGui.QColor()
color.setHsl(h,s,l,a)
pal.setColor(eval('QtGui.QPalette.{0}'.format(part)),color)
widget.setPalette(pal)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main_window = Transparent()
main_window.show()
sys.exit(app.exec_())
To make your main window transparent, you have to set the Qt.WA_TranslucentBackground attribute (using setAttribute(Qt.WA_TranslucentBackground)). Under Windows, you also must set the Qt.FramelessWindowHint attribute on your main window. According to the docs, however, "The user cannot move or resize a borderless window via the window system." So, if you want that functionality, you have to implement it manually. Here is a thread giving an example of that in C++.
Once you have a transparent MainWindow you can control the opacity of it and any child widgets by setting the background color to an RGBA value. Here is a dumb example,
from PyQt4 import QtGui, QtCore
import sys
class Main(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
frame = QtGui.QFrame(parent=self)
frame.setStyleSheet("QFrame {background: rgba(0,255,0,20%)}")
box=QtGui.QHBoxLayout()
edit = QtGui.QTextEdit()
edit.setStyleSheet("background: rgba(0,0,255,20%)")
box.addWidget(edit)
edit2=QtGui.QTextEdit()
edit2.setStyleSheet("background: rgb(255,0,0)")
box.addWidget(edit2)
frame.setLayout(box)
pushbutton = QtGui.QPushButton('Quit')
pushbutton.clicked.connect(self.close)
box.addWidget(pushbutton)
self.setCentralWidget(frame)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
app.exec_()

Categories

Resources