pyside QGraphicsScene: Why it is not working? - python

I am new to Qt and PySyde. I trying to create a small app to visualize sime line drawings.
In order to do that I try to use QGraphicsView an QGraphicsScene. I made a test to learn how it is working but it isn't. I googled a lot around, I do not understan why it isn't working.
Can somebody explain me the reason and bring me the light?
My code (just want to put a line and a sample text on the scene):
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox=QtGui.QHBoxLayout()
leftpanel=QtGui.QFrame()
leftpanel.setGeometry(0,0,300,400)
scene=QtGui.QGraphicsScene()
scene.addText("Hello, world!")
view=QtGui.QGraphicsView(scene,leftpanel)
view.setSceneRect(0,0,300,400)
pen=QtGui.QPen(QtCore.Qt.black,2)
scene.addLine(0,0,200,200,pen)
hbox.addWidget(leftpanel)
rightpanel=QtGui.QFrame()
hbox.addWidget(rightpanel)
szoveg=QtGui.QLabel(rightpanel)
szoveg.setText(u"Hello World!")
self.setLayout(hbox)
self.resize(500,500)
self.setWindowTitle('blabla')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

You need to save reference to scene somewhere, e.g. in Example instance:
def initUI(self):
# ...
scene = QtGui.QGraphicsScene()
self.scene = scene # save reference to scene, or it will be destroyed
scene.addText("Hello, world!")
# ...
In another function, you'll be able to add more items to the scene:
def anotherFunction(self):
self.scene.addText("Another Hello, world!")

Related

PyQT QListWidget drag and drop does not work

I am trying to implement in my project a QListWidget with the possibility of moving elements by drag and drop
I try to integrate it into the project in the simplest way without success, while outside I have no problem executing it.
EDIT:The problem seems to come from the realsense library, without its, DAD works
Here is its implementation:
priorityContainer.py:
class priorityContainer(QListWidget):
def __init__(self):
super().__init__()
self.setIconSize(QSize(124, 124))
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDefaultDropAction(Qt.MoveAction)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
self.setDragEnabled(True)
for i in range(5):
QListWidgetItem( 'Item '+str(i), self)
main_interface.py:
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
import traceback, sys, os
import pyrealsense2 as rs
from ressource.interface import priorityContainer
class UI_main(QMainWindow):
def __init__(self):
super(UI_main, self).__init__()
self.setupUi()
self.show()
def setupUi(self):
self.centralwidget = QWidget(self)
self.mainVcontainer = QVBoxLayout(self.centralwidget)
self.listWidget = priorityContainer.priorityContainer()
self.mainVcontainer.addWidget(self.listWidget)
self.setCentralWidget(self.centralwidget)
def root_path(self):
return os.path.abspath(os.sep)
if __name__ == "__main__":
app = QApplication(sys.argv)
ui = UI_main()
sys.exit(app.exec_())
I have solved my problem by adding these lines before any other imports where I import my pyrealsense2 librairies:
import sys
sys.coinit_flags = 2
import pythoncom
Reference to the fix: https://github.com/IntelRealSense/librealsense/issues/6174

Internationalization (translation) of dialog and the main window in a pyqt5 application

I am trying to translate my small application written in pyside2/pyqt5 to several languages, for example, Chinese. After googling, I managed to change the main window to Chinese after select from the menu -> language -> Chinese. However, the pop up dialog from menu -> option still remains English version. It seems the translation info is not transferred to the dialog. How do I solve this?
Basically, I build two ui files in designer and convert to two python files:One mainui.py and one dialogui.py. I then convert the two python file into one *.ts file using
pylupdate5 -verbose mainui.py dialogui.py -ts zh_CN.ts
after that, in linguist input the translation words. I can see the items in the dialog, which means this information is not missing. Then I release the file as zh_CN.qm file. All this supporting file I attached below using google drive.
Supporting files for the question
The main file is as
import os
import sys
from PySide2 import QtCore, QtGui, QtWidgets
from mainui import Ui_MainWindow
from dialogui import Ui_Dialog
class OptionsDialog(QtWidgets.QDialog,Ui_Dialog):
def __init__(self,parent):
super().__init__(parent)
self.setupUi(self)
self.retranslateUi(self)
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.actionConfigure.triggered.connect(self.showdialog)
self.actionChinese.triggered.connect(self.change_lang)
def showdialog(self):
dlg = OptionsDialog(self)
dlg.exec_()
def change_lang(self):
trans = QtCore.QTranslator()
trans.load('zh_CN')
QtCore.QCoreApplication.instance().installTranslator(trans)
self.retranslateUi(self)
if __name__=='__main__':
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
ret = app.exec_()
sys.exit(ret)
I think it should be a typical task because almost no application will only have a mainwindow.
You have to overwrite the changeEvent() method and call retranslateUi() when the event is of type QEvent::LanguageChange, on the other hand the QTranslator object must be a member of the class but it will be deleted and it will not exist when the changeEvent() method is called.
Finally assuming that the Language menu is used to establish only translations, a possible option is to establish the name of the .qm as data of the QActions and to use the triggered method of the QMenu as I show below:
from PySide2 import QtCore, QtGui, QtWidgets
from mainui import Ui_MainWindow
from dialogui import Ui_Dialog
class OptionsDialog(QtWidgets.QDialog,Ui_Dialog):
def __init__(self,parent):
super().__init__(parent)
self.setupUi(self)
def changeEvent(self, event):
if event.type() == QtCore.QEvent.LanguageChange:
self.retranslateUi(self)
super(OptionsDialog, self).changeEvent(event)
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.m_translator = QtCore.QTranslator(self)
self.actionConfigure.triggered.connect(self.showdialog)
self.menuLanguage.triggered.connect(self.change_lang)
# set translation for each submenu
self.actionChinese.setData('zh_CN')
#QtCore.Slot()
def showdialog(self):
dlg = OptionsDialog(self)
dlg.exec_()
#QtCore.Slot(QtWidgets.QAction)
def change_lang(self, action):
QtCore.QCoreApplication.instance().removeTranslator(self.m_translator)
if self.m_translator.load(action.data()):
QtCore.QCoreApplication.instance().installTranslator(self.m_translator)
def changeEvent(self, event):
if event.type() == QtCore.QEvent.LanguageChange:
self.retranslateUi(self)
super(MainWindow, self).changeEvent(event)
if __name__=='__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
ret = app.exec_()
sys.exit(ret)

Create another window of same class in PySide

I am creating a small GUI program using PySide. I am having difficulty creating another object of same class. What exactly I am trying to do is that when clicked on a button on MainWindow it should create another independent window of same class.
import sys
from PySide import QtCore, QtGui
class Sticky(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
self.initUI()
def initUI(self):
....
self.addToolBarElements()
....
self.show()
def addToolBarElements(self):
....
self.newwindow = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__),'icons/new.png')),"New Note",self)
self.newwindow.setStatusTip("New")
self.newwindow.triggered.connect(newwindow)
self.toolBar.addAction(self.newwindow)
def newwindow(self):
#how to create new object of same class
def run():
app = QtGui.QApplication(sys.argv)
notes = Sticky()
sys.exit(app.exec_())
Here is what I have tried:
I have tried multiprocessing but I didn't understand much. I tried calling run() method again but it gives error.
Do not call with the same name 2 different elements, in your case self.newwindow refers to the QAction as the method of the class, avoid it, that is a type of error easy to commit but difficult to find.
going to the point, you just have to create a new object of the class, but the problem is that the garbage collector will eliminate it, to avoid it there are 2 possible options, the first is to make the new window member of the class, or second store it in a list, that's the one I choose because I think you want to have several windows.
import sys
import os
from PySide import QtCore, QtGui
class Sticky(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
self.others_windows = []
self.initUI()
def initUI(self):
self.addToolBarElements()
self.show()
def addToolBarElements(self):
self.toolBar = self.addToolBar("toolBar")
self.newwindow = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__),'icons/new.png')), "New Note",self)
self.newwindow.setStatusTip("New")
self.newwindow.triggered.connect(self.on_newwindow)
self.toolBar.addAction(self.newwindow)
def on_newwindow(self):
w = Sticky()
w.show()
self.others_windows.append(w)
def run():
app = QtGui.QApplication(sys.argv)
notes = Sticky()
sys.exit(app.exec_())
run()

My new python gui window opened from another window exits as soon as it opens.How do I fix this

I have written python pyqt code to open a new window with a label from another window on a button click. The issue is ,new window exits as soon as it opens.How do i fix this.
The code I wrote is
import sys
from PyQt4 import QtGui,QtCore
class Window(QtGui.QWidget):
def __init__(self):
super(Window,self).__init__()
self.btn=QtGui.QPushButton('button',self)
self.btn.clicked.connect(display)
self.show()
class display(QtGui.QWidget):
def __init__(self):
super(display,self).__init__()
self.lab=QtGui.QLabel()
self.lab.setText("hi")
self.show()
def main():
App=QtGui.QApplication(sys.argv)
Gui=Window()
sys.exit(App.exec_())
main()
You need to keep a reference to the QWidget object for your second window. Currently when you click the button, the clicked signal is fired and it calls disp1. That creates the widget, but then it is immediately garbage collected.
Instead do this to keep a reference:
import sys
from PyQt4 import QtGui,QtCore
class Window(QtGui.QWidget):
def __init__(self):
super(Window,self).__init__()
self.btn=QtGui.QPushButton('button',self)
self.btn.clicked.connect(self.open_new_window)
self.show()
def open_new_window(self):
# creates the window and saves a reference to it in self.second_window
self.second_window = disp1()
class displ(QtGui.QWidget):
def __init__(self):
super(displ,self).__init__()
self.lab=QtGui.QLabel()
self.lab.setText("hello")
self.show()
def main():
App=QtGui.QApplication(sys.argv)
Gui=Window()
sys.exit(App.exec_())
main()
When passing a function as parameter, maybe it's better not to include the parentheses? Try
sys.exit(App.exec_)
Instead of
sys.exit(App.exec_())

pyqt4 QLineEdit realtime output using other py module

i want to show dialog like this:
test 0
test 1
test 2
test 3
........
test success
i try..... but it do not working!
it show only success....
is there way to output during execution by realtime?
this is example code
test.py
# -*- coding: utf-8 -*-
import sys
import test2
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.btn = QtGui.QPushButton('Dialog', self)
self.btn.move(20, 20)
self.btn.clicked.connect(self.showDialog)
self.le = QtGui.QLineEdit(self)
self.le.move(130, 22)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('test')
self.show()
def showDialog(self):
self.le.setText(test2.main("10",self.le))
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
test2.py
import time
def main(num,text_edit_box):
for i in range(int(num)):
text_edit_box.setText(str(i))
print i
time.sleep(1)
return "success"
Yes, you can do that using processEvents. Often when code runs continuously (e.g. like in your for loop in test2.main) the program is never told to update, so it doesn't. processEvents is the simple way to force a GUI update. It must be called on the QApplication class, so I've included a reference to that (app) that is passed along to test2.main.
test.py
import sys
import test2
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self, app):
self.app = app
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.btn = QtGui.QPushButton('Dialog', self)
self.btn.move(20, 20)
self.btn.clicked.connect(self.showDialog)
self.le = QtGui.QLineEdit(self)
self.le.move(130, 22)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('test')
self.show()
def showDialog(self):
self.le.setText(test2.main("10",self.le, self.app))
def main():
app = QtGui.QApplication(sys.argv)
ex = Example(app)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
test2.py
import time
def main(num,text_edit_box, app):
for i in range(int(num)):
text_edit_box.setText(str(i))
print i
time.sleep(.1)
app.processEvents()
return "success"
Depending on what you are trying to this may not be the best method, but it's the simplest way to just make your code work.
A better overall method to redraw the GUI might be to have an update_gui method in your GUI class that can be called either directly by other modules, or a slot that listens for signals sent by other modules.

Categories

Resources