Access untranslated string in PyQt? - pyqt5

I am writing a little pyqt application. Now I have start using Qtranslator with *.ts and *.qm files to get a Swedish translation.
I use e.g. self.tr(“Test this”) “Swedish Testar detta”. I am wondering while using the Swedish translation, if it is possible to get back the original untranslated string, in this case “Test this” in the program?
This i my little program and I want the "translate_string" method to print the original string.
from PyQt5.QtWidgets import (QApplication, QDialog, QPushButton, QVBoxLayout)
import sys
from PyQt5.QtCore import (QTranslator)
class Form(QDialog):
def __init__(self):
super(Form, self).__init__()
button = QPushButton(self.tr("&Close"))
self.test_lang = QPushButton(self.tr("Translate"))
self.string = self.tr("Test this")
layout = QVBoxLayout()
layout.addWidget(self.test_lang)
layout.addWidget(button)
self.setLayout(layout)
self.test_lang.clicked.connect(self.translate_string)
button.clicked.connect(self.close)
def translate_string(self):
print(self.string)
if __name__ == '__main__':
app = QApplication(sys.argv)
translator = QTranslator()
translator.load("test_trans_sv_SE.qm")
app.installTranslator(translator)
form = Form()
form.show()
sys.exit(app.exec_())

Related

Python, tkinter, multiprocessing Variable name not defined problem

from multiprocessing import Process
from tkinter import *
def th():
p = Process(target=Button1)
p.start()
class Button1:
def __init__(self):
btn1.config(state="disabled")
btn1.update()
if __name__ == "__main__":
root = Tk()
root.title("test")
root.resizable(False, False)
btn1 = Button(root, text="시작", width=10, height=5, command=th)
btn1.grid(row=0, column=0, sticky=N+E+W+S, padx=5, pady=5)
root.mainloop()
btn1.config(state="disabled")
NameError: name 'btn1' is not defined
I would appreciate it if you could tell me how to solve it.
I want the button to be disabled when pressed using multi processing.

Qpushbutton in custom QlistWidgetItem doesn't respond when running on embedded device

I'm quite new to pyqt5 and applications on embedded devices, and was hoping someone may have any tips or suggestions on the problems I'm facing.
I am working with a pyqt5 appliaction where the widget contains a QListWidget and two buttons. I have made a seperate widget that I use as a customized QListWidgetItem. The customized QListWidgetItem contains a textfield and a QPushButton.
Everything works perfectly on Ubuntu on my computer, but when I deploy and run the app on an embedded device, the buttons in the customized QListWidgetItem no longer responds. The "normal" buttons, that are not in the customized QListWidgetItem, still works normally.
I can't find a reason or fixes for this, and am quite stuck..
Here's my code, very simplified:
Edit! After some feedback I've created a smaller representation of the app/problem, which hopefully can make it easier to debug.
I no longer use pyqtSignal between the classes, only connected the buttons to different functions directly.
In this case, both the printing and color changing will happen if the buttons respond correctly.
python file:
import sys
from CustomListItem import Ui_custom_list_widget
from CollectorWidget import Ui_collector_widget
from PyQt5.QtWidgets import QWidget, QListWidgetItem, QApplication, QStackedWidget, QMainWindow
def main():
app = QApplication(sys.argv)
stack = QStackedWidget()
collector = CollectorWidget()
stack.addWidget(collector)
stack.setCurrentWidget(collector)
stack.show()
sys.exit(app.exec_())
class CollectorWidget(Ui_collector_widget, QWidget):
temp_list_items = []
def __init__(self, parent=None):
super(CollectorWidget, self).__init__(parent)
self.setupUi(self)
self.create_item_button.clicked.connect(self.create_item_clicked)
self.another_button.clicked.connect(lambda: print("this one works"))
def create_item_clicked(self):
self.listItem = QListWidgetItem()
self.item = CustomListItem()
self.item.custom_item_button.clicked.connect(self.test_signal)
self.qlistwidget_list.addItem(self.listItem)
self.qlistwidget_list.setItemWidget(self.listItem, self.item)
self.temp_list_items.append((self.listItem, self.item))
def test_signal(self):
print("--------------IT'S WORKING!--------------------------")
class CustomListItem(Ui_custom_list_widget, QWidget):
def __init__(self):
super().__init__()
self.setupUi(self)
self.item_name.setText("testing testing")
self.custom_item_button.clicked.connect(self.button_clicked)
def setItemText(self, text):
self.item_name.setText(text)
def button_clicked(self):
self.item_name.setStyleSheet("background-color: red;")
if __name__ == "__main__":
main()
Ui files (collector):
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'CollectorWidget.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_collector_widget(object):
def setupUi(self, collector_widget):
collector_widget.setObjectName("collector_widget")
collector_widget.resize(625, 514)
self.verticalLayout = QtWidgets.QVBoxLayout(collector_widget)
self.verticalLayout.setObjectName("verticalLayout")
self.qlistwidget_list = QtWidgets.QListWidget(collector_widget)
self.qlistwidget_list.setObjectName("qlistwidget_list")
self.verticalLayout.addWidget(self.qlistwidget_list)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.create_item_button = QtWidgets.QPushButton(collector_widget)
self.create_item_button.setObjectName("create_item_button")
self.horizontalLayout.addWidget(self.create_item_button)
self.another_button = QtWidgets.QPushButton(collector_widget)
self.another_button.setObjectName("another_button")
self.horizontalLayout.addWidget(self.another_button)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(collector_widget)
QtCore.QMetaObject.connectSlotsByName(collector_widget)
def retranslateUi(self, collector_widget):
_translate = QtCore.QCoreApplication.translate
collector_widget.setWindowTitle(_translate("collector_widget", "Form"))
self.create_item_button.setText(_translate("collector_widget", "Create"))
self.another_button.setText(_translate("collector_widget", "Just a button"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
collector_widget = QtWidgets.QWidget()
ui = Ui_collector_widget()
ui.setupUi(collector_widget)
collector_widget.show()
sys.exit(app.exec_())
Ui files (custom_list_item):
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'CustomListItem.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_custom_list_widget(object):
def setupUi(self, custom_list_widget):
custom_list_widget.setObjectName("custom_list_widget")
custom_list_widget.resize(608, 40)
self.horizontalLayout = QtWidgets.QHBoxLayout(custom_list_widget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.item_name = QtWidgets.QLabel(custom_list_widget)
font = QtGui.QFont()
font.setKerning(True)
self.item_name.setFont(font)
self.item_name.setStyleSheet("")
self.item_name.setWordWrap(True)
self.item_name.setObjectName("item_name")
self.horizontalLayout_2.addWidget(self.item_name)
self.custom_item_button = QtWidgets.QPushButton(custom_list_widget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.custom_item_button.sizePolicy().hasHeightForWidth())
self.custom_item_button.setSizePolicy(sizePolicy)
self.custom_item_button.setMaximumSize(QtCore.QSize(20, 20))
self.custom_item_button.setStyleSheet("")
self.custom_item_button.setText("")
self.custom_item_button.setObjectName("custom_item_button")
self.horizontalLayout_2.addWidget(self.custom_item_button)
self.horizontalLayout.addLayout(self.horizontalLayout_2)
self.retranslateUi(custom_list_widget)
QtCore.QMetaObject.connectSlotsByName(custom_list_widget)
def retranslateUi(self, custom_list_widget):
_translate = QtCore.QCoreApplication.translate
custom_list_widget.setWindowTitle(_translate("custom_list_widget", "Form"))
self.item_name.setText(_translate("custom_list_widget", "TextLabel"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
custom_list_widget = QtWidgets.QWidget()
ui = Ui_custom_list_widget()
ui.setupUi(custom_list_widget)
custom_list_widget.show()
sys.exit(app.exec_())
Picture of app:

PyQt5 input text can't be executed as code in QPlainTextEdit

I have a QMainWindow which contains a QPlainTextEdit and a button with clicked even connected. When user finishes text input and press the button, I just want to execute user input for example "1+1". I should get "2", but it is "1+1". Very appreciated for your reply, thanks!
import sys
from PyQt5.QtWidgets import QMainWindow, QPushButton, \
QApplication, QVBoxLayout, QPlainTextEdit, QWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(600, 600)
l_layout = QVBoxLayout()
self.edit = QPlainTextEdit()
self.edit.setFixedSize(400, 300)
self.edit1 = QPlainTextEdit()
self.edit1.setFixedSize(100, 100)
self.btn = QPushButton('Test')
self.btn.clicked.connect(self.press)
l_layout.addWidget(self.edit)
l_layout.addWidget(self.edit1)
l_layout.addWidget(self.btn)
dummy_widget = QWidget()
dummy_widget.setLayout(l_layout)
self.setCentralWidget(dummy_widget)
def press(self):
text = self.edit.toPlainText()
try:
code = """print(text)"""
exec(code)
except Exception as e:
print('not ok!')
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
You should evaluate the input text and then print it, like so:
def press(self):
text = self.edit.toPlainText()
try:
print(eval(text))
except Exception as e:
print('not ok!')
Pay attention, because eval() use can lead to security issues (people executing python code on your app). Make sure your input is sanitized.

Using a search bar to find items in a list

I want to use a line edit as a search bar in order to find items in a Qlistwidget. I also want the qlistwidget to scroll up/down (in search) as text is being changed in the line edit.
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QGridLayout, QWidget, QListWidget, QLineEdit
class Window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.ListBox = QListWidget()
self.ListBox.insertItem(0,'Temperature')
self.ListBox.insertItem(1,'Mass')
self.ListBox.insertItem(2,'Length')
self.ListBox.insertItem(3,'Height')
self.ListBox.insertItem(4,'Width')
self.ListBox.insertItem(5,'Volume')
self.ListBox.insertItem(6,'Surface_Area')
self.ListBox.insertItem(7,'Material')
self.ListBox.insertItem(8,'Location')
self.ListBox.insertItem(9,'Strength')
self.ListBox.insertItem(10,'Color')
self.Search_Bar = QLineEdit()
layout = QGridLayout(centralWidget)
layout.addWidget(self.ListBox)
layout.addWidget(self.Search_Bar)
self.Search_Bar.textChanged.connect(self.Search)
def Search(self):
if self.Search_Bar.text() == 'Strength':
pass
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
The internally implemented match function provided by all Qt item models is usually faster than cycling through the list via Python.
def Search(self, text):
model = self.ListBox.model()
match = model.match(
model.index(0, self.ListBox.modelColumn()),
QtCore.Qt.DisplayRole,
text,
hits=1,
flags=QtCore.Qt.MatchStartsWith)
if match:
self.ListBox.setCurrentIndex(match[0])
This will automatically select and scroll to the first item found (if any).

How to change ipython qtconsole input

I'm making a guide with pyqt and I'm including an ipython qtconsole widget.
try:
from qtconsole.rich_jupyter_widget import RichJupyterWidget as ipythonWidget
from qtconsole.inprocess import QtInProcessKernelManager
except:
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget as ipythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager
I want to modify the qtconsole input from my code but is not working. I've tried the set_next_input function but it doesn't work and I can't find another function I can use to acomplish what I want. Is even possible to achieve what I want? and if so, how can I do it?
Here is my code:
try:
from qtconsole.rich_jupyter_widget import RichJupyterWidget as ipythonWidget
from qtconsole.inprocess import QtInProcessKernelManager
except:
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget as ipythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager
import sys
from PyQt4 import QtGui
class sympyIpython(QtGui.QWidget):
def __init__(self):
super().__init__()
self.ipython = IpythonWidget()
v = QtGui.QVBoxLayout(self)
button = QtGui.QPushButton('append to input')
v.addWidget(self.ipython)
v.addWidget(button)
button.clicked.connect(self.symClicked)
def symClicked(self):
self.ipython.kernel.shell.set_next_input(' appended text')
class IpythonWidget(ipythonWidget):
def __init__(self):
super().__init__()
self.kernel_manager = QtInProcessKernelManager()
self.kernel_manager.start_kernel()
self.kernel = self.kernel_manager.kernel
self.kernel.gui = 'qt4'
self.kernel_client = self.kernel_manager.client()
self.kernel_client.start_channels()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
m = sympyIpython()
m.show()
sys.exit(app.exec_())
Reposting as an answer:
To change the text at the prompt in the Qt console, set input_buffer on the widget object:
jupyter_widget.input_buffer = 'text'