Render python list in pyqt Qwidget - python

So i have a problem writing what i have as list in a python code into my Qwidget , what i want is : as i have a list of tweets , when i click on the button i want my code to write what i have in a list in the Qwidget i don't know what to use for the writing part , i thought of using QPlainTextEdit which i think is not right , can you give me an idea of what to use and how ?
here is my code
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
import gettweet
app = QApplication.instance()
if not app:
app = QApplication(sys.argv)
widget = QWidget()
get = QPushButton(widget)
get.setText("Get tweet")
get.move(64,32)
widget.setGeometry(50,50,800,600)
widget.setWindowTitle("Sentiments tweets")
QtWidgets.QPlainTextEdit(widget).setGeometry(300,0 , 500,600)
def window() :
get.clicked.connect(button1_clicked)
widget.show()
app.exec_()
def button1_clicked() :
tweets = gettweet.get()
for i in tweets :
pass
if __name__ == '__main__':
window()

i do not know if you want it like this but i made the application put the items that are in the list to the QPlainTextEdit.
you should edit and fix the code to make it like what you want because i edited it.
from re import I
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
app = QApplication.instance()
if not app:
app = QApplication(sys.argv)
widget = QWidget()
def button1_clicked() :
tweets = ["My love is mohammed almalki","i love mohammed almalki very much"]
for i in tweets :
MyQPlainTextEdit.setPlainText(i)
get = QPushButton(widget)
get.setText("Get tweet")
get.move(64,32)
widget.setGeometry(50,50,800,600)
widget.setWindowTitle("Sentiments tweets")
MyQPlainTextEdit = QtWidgets.QPlainTextEdit(widget)
MyQPlainTextEdit.setGeometry(300,0 , 500,600)
def window() :
get.clicked.connect(button1_clicked)
widget.show()
app.exec_()
if __name__ == '__main__':
window()
and i will give you an idea
you can create a container and put in it a lot of QPlainTextEdit like you have of tweets for example you have 10 tweets and you want to show them you can make it like this:
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
class ForExample:
Tweets = ["Oh i do not know if i will meet mohammed almalki or not i love him very much",
"One of my favorite people is mohammed almalki",
"OMG did you meet Mohammed?? oh my god i think that is your best day right?"]
def __init__(self):
self.Application = QtWidgets.QApplication([])
self.Window = QtWidgets.QWidget()
self.Window.resize(800,500)
self.WindowLayout = QtWidgets.QGridLayout()
self.ScrollArea = QtWidgets.QScrollArea()
self.ScrollArea.setWidgetResizable(True)
self.GroupBox = QtWidgets.QGroupBox()
self.GroupBoxLayout = QtWidgets.QGridLayout()
self.GroupBox.setLayout(self.GroupBoxLayout)
self.ScrollArea.setWidget(self.GroupBox)
def FunctionToDoTheWord():
for i in range(len(self.Tweets)):
self.GroupBoxLayout.addWidget(QtWidgets.QPlainTextEdit(self.Tweets[i]))
self.ButtonToShowTheTweets = QtWidgets.QPushButton("Show Tweets")
self.ButtonToShowTheTweets.clicked.connect(FunctionToDoTheWord)
self.WindowLayout.addWidget(self.ScrollArea)
self.WindowLayout.addWidget(self.ButtonToShowTheTweets)
self.Window.setLayout(self.WindowLayout)
self.Window.show()
self.Application.exec()
ForExample()
try this and tell me.

Related

Qaction Shortcut in extended contextmenu not triggered

I try to extend the contextmenu of a QLineEdit with an additional entry for replacing text. I can extend the contextmenu with .createStandardContextMenu(), which works fine. But when I try to add a shortcut with .setShortcut(QKeySequence(Qt.CTRL + Qt.Key_R)) it will not react on the key. Same with different keys, which I tried. In addition the shortcut made with QAction('&Replace', self) doesn't work too.
Some examples here in SO and other sources are constructed in the same way, so I'm wondering that nobody else has got the same problem. Seems that I'm missing anything. But what? I can't figure out, checked the docs multiple times.
Working Example:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class ECM(QWidget):
def __init__(self):
super(ECM, self).__init__()
self.setWindowTitle("Extended Context Menu")
self.lineEdit = QLineEdit()
self.lineEdit.setContextMenuPolicy(Qt.CustomContextMenu)
self.lineEdit.customContextMenuRequested.connect(self.my_contextMenuEvent)
layout = QVBoxLayout()
layout.addWidget(self.lineEdit)
self.setLayout(layout)
self.setFixedSize(800,200)
self.show()
def replace(self):
print("replace")
def my_contextMenuEvent(self):
print("my_contextMenuEvent")
menu = self.lineEdit.createStandardContextMenu()
action = QAction('&Replace', self)
action.setStatusTip('Replace values')
action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_R))
action.triggered.connect(self.replace)
menu.addAction(action)
menu.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
sender = ECM()
app.exec_()
Based on musicamante's comment I came to the following solution:
Extract from the docs:
If you want to extend the standard context menu, reimplement this
function, call createStandardContextMenu() and extend the menu
returned.
The default use of the QAction list (as returned by actions()) is to
create a context QMenu.
It's not totally logically to me, not for the 1st time ;-)
Final code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class ECM(QWidget):
def __init__(self):
super(ECM, self).__init__()
self.setWindowTitle("Extended Context Menu")
self.lineEdit = QLineEdit()
self.lineEdit.setContextMenuPolicy(Qt.CustomContextMenu)
self.lineEdit.customContextMenuRequested.connect(self.my_contextMenuEvent)
layout = QVBoxLayout()
layout.addWidget(self.lineEdit)
self.setLayout(layout)
self.setFixedSize(800,200)
action = QAction('&Replace', self)
action.setStatusTip('Replace values')
action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_R))
action.triggered.connect(self.replace)
self.lineEdit.addAction(action)
self.show()
def replace(self):
print("replace")
def my_contextMenuEvent(self):
menu = self.lineEdit.createStandardContextMenu()
menu.addActions(self.lineEdit.actions())
menu.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
sender = ECM()
app.exec_()

Switch widget in QStackWidget from a button in another file

I got two py files. One has the main window with a QStackedWidget inside, the setCurrentWidget is set according to a condition. The other file has a widget which is dynamically added into the stacked widget and set as current widget when a button in the main window is clicked.
The widget in the second file has a dialog with a button in it. What I'm trying to do is, on clicking the button inside the dialog, the dialog should be closed and the setCurrentWidget is set according to the condition and the widget is removed from the stacked widget.
Here is what I've tried:
mainwindow.py
import sys
import os
import pathlib
from PySide2.QtWidgets import *
from PySide2 import *
from PySide2.QtCore import *
from PySide2.QtGui import *
list1 = ["item1", "item2", "item3"]
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.resize(400, 300)
self.toolbar = QWidget()
self.toolbar.setFixedHeight(30)
self.toolbar.setStyleSheet("background: grey;")
self.button = QPushButton("Click here!")
t_layout = QHBoxLayout()
t_layout.setMargin(0)
t_layout.addWidget(self.button)
self.toolbar.setLayout(t_layout)
self.p1_label = QLabel("Such empty!")
self.p1_label.setStyleSheet("font-size: 30px;")
self.p1_label.setAlignment(Qt.AlignCenter)
self.p2_widget = QWidget()
self.p2_widget.setStyleSheet("background: orange;")
self.sw = QStackedWidget()
self.sw.addWidget(self.p1_label)
self.sw.addWidget(self.p2_widget)
if not list1:
self.sw.setCurrentWidget(self.p1_label)
else:
self.sw.setCurrentWidget(self.p2_widget)
self.mw_layout = QVBoxLayout()
self.mw_layout.addWidget(self.toolbar)
self.mw_layout.addWidget(self.sw)
self.setLayout(self.mw_layout)
def switch_widget():
import widget_test
p3 = widget_test.widget()
self.sw.addWidget(p3)
self.sw.setCurrentWidget(p3)
self.button.clicked.connect(switch_widget)
def switch_back(self):
import widget_test
p3 = widget_test.widget()
mwin = MainWindow()
sw_ = mwin.sw
sw_.removeWidget(p3)
p1 = mwin.p1_label
p2 = mwin.p2_widget
if not list1:
sw_.setCurrentWidget(p1)
else:
sw_.setCurrentWidget(p2)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
widget.py
import sys
import os
import pathlib
import datetime
from PySide2.QtWidgets import *
from PySide2 import *
from PySide2.QtCore import *
from PySide2.QtGui import *
class widget(QWidget):
def __init__(self):
super(widget, self).__init__()
self.setStyleSheet("background: teal;")
widget_label = QLabel("fluid dynamics is cool")
show_pop_up = QPushButton("show pop up")
pop_up = QDialog(self)
pop_up_label = QLabel("click below to, hopefully, get outta here")
get_outta_here = QPushButton("get outta here")
pop_up_layout = QVBoxLayout()
pop_up_layout.addWidget(pop_up_label)
pop_up_layout.addWidget(get_outta_here)
pop_up.setLayout(pop_up_layout)
def show_popup():
pop_up.show()
def get_out():
from main_test import MainWindow
MainWindow.switch_back(self)
pop_up.reject()
get_outta_here.clicked.connect(get_out)
show_pop_up.clicked.connect(show_popup)
widget_layout = QVBoxLayout()
widget_layout.addWidget(widget_label)
widget_layout.addWidget(show_pop_up)
self.setLayout(widget_layout)
I could merge the code together and make it work but I'm trying to keep the directory clean.
There is a lot going on here, but let's break it down.
The main problem seems to be juggling between modules. Eventhough it might seem appealing to import the modules back and forth, it doesn't really work. What you need to look for, is the built-in Signals module that you can utilize.
Another bigger problem is that you are re-assigning some attributes eventhough you really shouldn't. You also should revisit the condition you are using to assign the .setCurrentWidget. Currently the condition reads as if list1 doesn't exist, do this. Else, do the other. Also, switch_widget should be outside of the def __init__(self):.
I rewrote some parts of the code to make it work with signals as an example for you.
mainwindow.py
import sys
import os
import pathlib
from PySide2.QtWidgets import *
from PySide2 import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from widget_test import widget
list1 = ["item1", "item2", "item3"]
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.resize(400, 300)
self.toolbar = QWidget()
self.toolbar.setFixedHeight(30)
self.toolbar.setStyleSheet("background: grey;")
self.button = QPushButton("Click here!")
t_layout = QHBoxLayout()
t_layout.setMargin(0)
t_layout.addWidget(self.button)
self.toolbar.setLayout(t_layout)
self.p1_label = QLabel("Such empty!")
self.p1_label.setStyleSheet("font-size: 30px;")
self.p1_label.setAlignment(Qt.AlignCenter)
self.p2_widget = QWidget()
self.p2_widget.setStyleSheet("background: orange;")
self.p3 = None
self.sw = QStackedWidget()
self.sw.addWidget(self.p1_label)
self.sw.addWidget(self.p2_widget)
if not list1:
self.sw.setCurrentWidget(self.p1_label)
else:
self.sw.setCurrentWidget(self.p2_widget)
self.mw_layout = QVBoxLayout()
self.mw_layout.addWidget(self.toolbar)
self.mw_layout.addWidget(self.sw)
self.setLayout(self.mw_layout)
self.button.clicked.connect(self.switch_widget)
def switch_widget(self):
self.p3 = widget()
self.p3.update_signal.connect(self.switch_back)
self.sw.addWidget(self.p3)
self.sw.setCurrentWidget(self.p3)
def switch_back(self):
self.sw.removeWidget(self.p3)
if list1:
self.sw.setCurrentWidget(self.p1_label)
else:
self.sw.setCurrentWidget(self.p2_widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
widget.py
import sys
import os
import pathlib
import datetime
from PySide2.QtWidgets import *
from PySide2 import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtCore import Signal
class widget(QWidget):
update_signal = Signal()
def __init__(self):
super(widget, self).__init__()
self.setStyleSheet("background: teal;")
widget_label = QLabel("fluid dynamics is cool")
show_pop_up = QPushButton("show pop up")
pop_up = QDialog(self)
pop_up_label = QLabel("click below to, hopefully, get outta here")
get_outta_here = QPushButton("get outta here")
pop_up_layout = QVBoxLayout()
pop_up_layout.addWidget(pop_up_label)
pop_up_layout.addWidget(get_outta_here)
pop_up.setLayout(pop_up_layout)
def show_popup():
pop_up.show()
def get_out():
self.update_signal.emit()
pop_up.reject()
get_outta_here.clicked.connect(get_out)
show_pop_up.clicked.connect(show_popup)
widget_layout = QVBoxLayout()
widget_layout.addWidget(widget_label)
widget_layout.addWidget(show_pop_up)
self.setLayout(widget_layout)
Finally, check Python coding conventions for naming and other "minor" details.

Extracting certain parts of a webpage using PyQt5 and displaying them

I want to make GUI application which asks the user for the champion they want to check and then their role (e.g Middle, Jungle, Top, ADC, Support) and then it will display the "Most Frequent Runes" and some other data on the website. I believe PyQt5 would be the best python GUI for this as it has embedded webpages but please suggest alternatives.
With this code:
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QApplication
import sys
#champion = input("What champion would you like to check? ")
champions = "Katarina"
#role = input("What role are you playing (Middle, Jungle, Top, ADC, Support)? ")
roles = "Middle"
URL = f"https://champion.gg/champion/{champions.capitalize()}/{roles.capitalize()}?"
app = QApplication(sys.argv)
web = QWebEngineView()
web.load(QUrl(URL))
web.show()
sys.exit(app.exec_())
It displays the whole webpage but I only want the "Most frequent Runes" section shown like it is like this:
and then hold it as a variable (QLabel?) that can then be placed wherever I want it. I have tried to look over how to do this but i couldn't find a solution. I would rather have done it using tkinter but it seems that isn't possible (or as far as I have been able to gather - if their is a way please explain as much as you can how).
I tried scraping the website using bs4 and requests with this code:
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import *
from bs4 import BeautifulSoup
import requests
import time
import sys
#champion = input("What champion would you like to check? ")
champions = "Katarina"
#role = input("What role are you playing (Middle, Jungle, Top, ADC, Support)? ")
roles = "Middle"
URL = f"https://champion.gg/champion/{champions.capitalize()}/{roles.capitalize()}?"
app = QApplication(sys.argv)
page = requests.get('https://champion.gg/champion/Katarina/Middle?')
soup = BeautifulSoup(page.text, 'lxml')
championData = soup.find('div', 'summoner-text')
window = QWidget()
window.setWindowTitle("League of Legends helper")
window.setGeometry(100, 100, 550, 250)
runes = QLabel(championData, parent=window)
but it just produces errors which I haven't fully been able to understand.
Error:
Traceback (most recent call last):
File "(FILEPATH)", line 32, in <module>
runes = QLabel(championData, parent=window)
TypeError: arguments did not match any overloaded call:
QLabel(parent: QWidget = None, flags: Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags()): argument 1 has unexpected type 'Tag'
QLabel(str, parent: QWidget = None, flags: Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags()): argument 1 has unexpected type 'Tag'
BeautifulSoup's is an HTML parser so each node of the DOM has a wrapper that allows access to its properties, so championData is not a string causing the error.
Even so, you would extract the HTML from the node, it would be useless because the "requests" library does not obtain the HTML generated dynamically by javascript, in addition, the styles would not be kept as they depend on other files.
A possible solution for this case is to extract the HTML from that node and place it in the same document using javascript:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
def main(*, champions, roles):
url = f"https://champion.gg/champion/{champions.capitalize()}/{roles.capitalize()}?"
app = QtWidgets.QApplication(sys.argv)
web = QtWebEngineWidgets.QWebEngineView()
web.resize(640, 480)
progress_dialog = QtWidgets.QProgressDialog()
progress_dialog.setLabelText(
"""""<p><span style=" font-size:20pt; font-weight:600;">Loadding ...</span></p>"""
)
progress_dialog.resize(640, 480)
progress_dialog.show()
web.loadProgress.connect(progress_dialog.setValue)
button = progress_dialog.findChild(QtWidgets.QPushButton)
if button is not None:
button.clicked.connect(QtCore.QCoreApplication.quit)
def on_load_finished():
codes = [
"""var iterator = document.evaluate("/html[1]/body[1]/div[1]/div[2]/div[3]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[3]", document, null, XPathResult.ANY_TYPE, null)""",
"""var e = iterator.iterateNext() """,
"""document.body.innerHTML = e.innerHTML""",
"""document.body.children[0].style.marginTop = "10px" """,
]
for code in codes:
web.page().runJavaScript(code)
web.move(progress_dialog.pos())
web.show()
progress_dialog.close()
web.loadFinished.connect(on_load_finished)
web.load(QtCore.QUrl(url))
sys.exit(app.exec_())
if __name__ == "__main__":
main(champions="Katarina", roles="Middle")
Update:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self._champion_le = QtWidgets.QLineEdit(placeholderText=self.tr("champion"))
self._role_cb = QtWidgets.QComboBox()
self._web = QtWebEngineWidgets.QWebEngineView()
self._search_btn = QtWidgets.QPushButton(self.tr("Search"))
self._stacked = QtWidgets.QStackedWidget()
self._progress_bar = QtWidgets.QProgressBar()
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QGridLayout(central_widget)
lay.addWidget(self._champion_le, 0, 0)
lay.addWidget(self._role_cb, 0, 1)
lay.addWidget(self._search_btn, 0, 2)
lay.addWidget(self._stacked, 1, 0, 1, 3)
container = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(container)
lay.addWidget(
QtWidgets.QLabel(
self.tr(
"""<p><span style="font-size:20pt; font-weight:600;">Loadding ...</span></p>"""
)
)
)
lay.addWidget(self._progress_bar)
self._stacked.addWidget(QtWidgets.QWidget())
self._stacked.addWidget(container)
self._stacked.addWidget(self._web)
self._role_cb.addItems(["Top", "Jungle", "Middle", "ADC", "Support"])
self._search_btn.clicked.connect(self.on_clicked)
self._web.loadFinished.connect(self.on_load_finished)
self._web.loadProgress.connect(self._progress_bar.setValue)
self.resize(640, 480)
self._champion_le.setText("Aatrox")
self._role_cb.setCurrentText("Top")
#QtCore.pyqtSlot()
def on_clicked(self):
champion = self._champion_le.text()
role = self._role_cb.currentText()
if champion:
self._stacked.setCurrentIndex(1)
self.change(champion, role)
def change(self, champion, role):
url = f"https://champion.gg/champion/{champion.capitalize()}/{role}?"
self._web.load(QtCore.QUrl(url))
#QtCore.pyqtSlot(bool)
def on_load_finished(self, ok):
if ok:
codes = [
"""var iterator = document.evaluate("/html[1]/body[1]/div[1]/div[2]/div[3]/div[2]/div[2]/div[1]/div[1]/div[2]/div[1]/div[3]", document, null, XPathResult.ANY_TYPE, null)""",
"""var e = iterator.iterateNext() """,
"""document.body.innerHTML = e.innerHTML""",
"""document.body.children[0].style.marginTop = "10px" """,
]
for code in codes:
self._web.page().runJavaScript(code)
self._stacked.setCurrentIndex(2)
def main():
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

How to change languages(translations) dynamically on PyQt5?

I wonder if it is possible to change the languages(translations) dynamically without using qt designer to make the UI? That means I don't want to use the function retranslateUi() to update the program interface.
Here is my code, but I'm stuck on lines marked #1 #2 #3. Don't know what I should use to update the interface.
import sys
from PyQt5.QtCore import Qt, QTranslator
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel,
QComboBox, QVBoxLayout
class Demo(QWidget):
def __init__(self):
super(Demo, self).__init__()
self.button = QPushButton(self.tr('Start'), self)
self.label = QLabel(self.tr('Hello, World'), self)
self.label.setAlignment(Qt.AlignCenter)
self.combo = QComboBox(self)
self.combo.addItem('English')
self.combo.addItem('中文')
self.combo.addItem('français')
self.combo.currentTextChanged.connect(self.change_func)
self.trans = QTranslator(self)
self.v_layout = QVBoxLayout()
self.v_layout.addWidget(self.combo)
self.v_layout.addWidget(self.button)
self.v_layout.addWidget(self.label)
self.setLayout(self.v_layout)
def change_func(self):
print(self.combo.currentText())
if self.combo.currentText() == '中文':
self.trans.load('eng-chs')
_app = QApplication.instance()
_app.installTranslator(self.trans)
# 1
elif self.combo.currentText() == 'français':
self.trans.load('eng-fr')
_app = QApplication.instance()
_app.installTranslator(self.trans)
# 2
else:
_app = QApplication.instance()
_app.removeTranslator(self.trans)
# 3
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = Demo()
demo.show()
sys.exit(app.exec_())
Any help would be appreciated.
TL; DR; It is not necessary to use Qt Designer
You should not use Qt Designer necessarily but you should use the same technique, that is, create a method that could be called retranslateUi() and in it set the texts using translate() instead of tr() (for more details read the docs). Calling that method when you change language for it must use the changeEvent() event. For example in your case the code is as follows:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Demo(QtWidgets.QWidget):
def __init__(self):
super(Demo, self).__init__()
self.button = QtWidgets.QPushButton()
self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
self.combo = QtWidgets.QComboBox(self)
self.combo.currentIndexChanged.connect(self.change_func)
self.trans = QtCore.QTranslator(self)
self.v_layout = QtWidgets.QVBoxLayout(self)
self.v_layout.addWidget(self.combo)
self.v_layout.addWidget(self.button)
self.v_layout.addWidget(self.label)
options = ([('English', ''), ('français', 'eng-fr' ), ('中文', 'eng-chs'), ])
for i, (text, lang) in enumerate(options):
self.combo.addItem(text)
self.combo.setItemData(i, lang)
self.retranslateUi()
#QtCore.pyqtSlot(int)
def change_func(self, index):
data = self.combo.itemData(index)
if data:
self.trans.load(data)
QtWidgets.QApplication.instance().installTranslator(self.trans)
else:
QtWidgets.QApplication.instance().removeTranslator(self.trans)
def changeEvent(self, event):
if event.type() == QtCore.QEvent.LanguageChange:
self.retranslateUi()
super(Demo, self).changeEvent(event)
def retranslateUi(self):
self.button.setText(QtWidgets.QApplication.translate('Demo', 'Start'))
self.label.setText(QtWidgets.QApplication.translate('Demo', 'Hello, World'))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
demo = Demo()
demo.show()
sys.exit(app.exec_())
Then generate the .ts:
pylupdate5 main.py -ts eng-chs.ts
pylupdate5 main.py -ts eng-fr.ts
Then use Qt Linguist to do the translations.
And finally the .qm:
lrelease eng-fr.ts eng-chs.qm
The complete project you find here.
No you will have to use a technique like Qt Designer does with retranslateUi because the Qt widget system does not have a way to redo the translation on it's own (otherwise QT Designer would be using that to).
Building such a system would require a fundamental change to the widgets as for each string property you would need to know that it contains a translatable string (not a data value) and knowing the original string for looking up the new translation would be best (reversing translations could be ambiguous).

TreeWidget setItemWidget Issue Qt

I am adding a Qwidget(QPushButton) into a QTreeWidget through setItemWidget method, but Button is not appearing as expected.
Need some help in this case.
Code:
import sys
from PyQt4 import QtGui, QtCore
class Test_Ui(QtGui.QMainWindow):
def __init__(self):
super(Test_Ui, self).__init__()
self.setMainWidget()
self.setTree()
self.show()
def setMainWidget(self):
self.QwCentral = QtGui.QWidget()
self.setCentralWidget(self.QwCentral)
self.QglCentral = QtGui.QGridLayout()
self.QwCentral.setLayout(self.QglCentral)
def setTree(self):
self.QtwExp = QtGui.QTreeWidget()
self.QtwExp.headerItem().setText(0, 'First')
self.QtwExp.headerItem().setText(1, 'Second')
self.QglCentral.addWidget(self.QtwExp, 0,0)
Qcategory = QtGui.QTreeWidgetItem()
Qcategory.setText(0, 'TEST')
self.QtwExp.addTopLevelItem(Qcategory)
Qbutton = QtGui.QPushButton()
Qbutton.setText('BUTTON')
# setItem Widget Command
self.QtwExp.setItemWidget(Qcategory, 1, Qbutton)
def main():
global wapp
app = QtGui.QApplication(sys.argv)
wapp = Test_Ui()
sys.exit(app.exec_())
Simple typo:
Replace following
self.QtwExp.addToplevelItem(Qcategory)
with
self.QtwExp.addTopLevelItem(Qcategory)
# ^
Its the PyQt4 version issue.
when i use PyQt4 version 4.7.x it works fine.

Categories