Python2 + PyQt5: how to get value of QDoubleSpinBox? - python

I would like ask how to get the value of QDoubleSpinBox. It confuses me as a new user. Hier is my code:
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QDoubleSpinBox
import sys
class MyApp(QWidget):
def __init__(self, parent=None):
super(MyApp, self).__init__(parent)
dsbox = QDoubleSpinBox(self)
dsbox.setDecimals(1)
dsbox.setValue(100.00)
dsbox.setMinimum(1.00)
dsbox.setMaximum(3500.00)
dsbox.setSingleStep(1.00)
dsbox.setSuffix("mm")
dsbox.valueChanged.connect(self.on_value_changed)
self.show()
def on_value_changed(self):
print "You are now in the sub function."
print self.dsbox.value() #Problem is hier
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyApp()
sys.exit(app.exec_())
The result is:
You are now in the sub function.
Process finished with exit code 1
It means something is wrong with this line: print self.dsbox.value()
I have checked that there is a "value" public function for QDoubleSpinBox Class:
http://doc.qt.io/qt-5/qdoublespinbox.html
So what have I done wrong hier? Thanks for your help!

Related

PyQt5 - how to avoid crashing gui while updating progresssbar in a multi-threading setting (Qthread)?

I am new in multi threading. The video file I use work fine and the progress-bar at the start shows a percent in progress-bar. When I want to change the progress-bar value continuously for example the current cpu usage value the below code keeps crashing when i run the code. Why is the code not working??
I think the problem is emit and connect. If so what can i do? And how do I correct this? Thanks in advance for the help.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal
import sysinfo
from multi import Ui_Form
class main(QtWidgets.QWidget ,Ui_Form):
cpu_value = pyqtSignal()
def __init__(self, parent = None):
super(main,self).__init__(parent)
self.setupUi(self)
self.threadclass = ThreadClass()
self.threadclass.start()
self.cpu_value.connect(self.updateProgressBar)
def updateProgressBar(self):
val = sysinfo.getCPU()
self.progressBar.setValue(val)
class ThreadClass(QtCore.QThread):
def __init__(self, parent = None):
super(ThreadClass,self).__init__(parent)
def run(self):
while 1:
val = sysinfo.getCPU()
self.cpu_value.emit(val)
if __name__ == '__main__':
a = QtWidgets.QApplication(sys.argv)
app = main()
app.show()
a.exec_()
env: python3.5 + pyqt5.9
I use a timer to update the CPU info like that:
#!/usr/bin/python3
# 2017.12.10 13:20:11 CST
# 显示 CPU
import sys
from PyQt5 import QtCore, QtWidgets
import psutil
class CPU(QtWidgets.QProgressBar):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("CPU Info")
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(lambda : self.setValue(psutil.cpu_percent()))
self.timer.start(1000)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
win = CPU()
win.show()
app.exec_()

create main script to use PyQt4 windows with other objects

I am trying to learn how to use python and pyQt.
I have done a window with Qtcreator then I used pyuic4, I have also created a class called Ruban I would like to use it with my window interface. In my window I have a button called nouveauRuban. I would like to create an object from my class Ruban when this button is clicked.
I know my code is wrong, the problem may be at the initial part of mainTN, on the __init__ ?
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from mainwindow import Ui_MainWindow
from Ruban import Ruban
class mainTM(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None): #, parent=None ??
super (mainTM, self).__init__(self, parent) #(parent) ??
self.createWidgets()
self.nouveauRuban.connect(nouveauRuban, QtCore.SIGNAL(_fromUtf8("clicked()")), self.nvRuban)
def nvRuban(self):
self.ruban=Ruban()
self.ruban.info_ruban()
def createWidgets(self):
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
if __name__== "__main__":
app=QApplication(sys.argv)
myapp=mainTM()
myapp.show()
sys.exit(app.exec_())
Here is a re-write of your script which should fix all the problems:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from mainwindow import Ui_MainWindow
from Ruban import Ruban
class mainTM(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(mainTM, self).__init__(parent)
self.setupUi(self)
self.nouveauRuban.clicked.connect(self.nvRuban)
def nvRuban(self):
self.ruban = Ruban()
self.ruban.info_ruban()
if __name__== '__main__':
app = QApplication(sys.argv)
myapp = mainTM()
myapp.show()
sys.exit(app.exec_())
If you're connecting a signal to a slot, you need to define that slot using a decorator:
#QtCore.pyqtSlot()
def nvRuban(self):
self.ruban=Ruban()
self.ruban.info_ruban()
Then connect it:
self.nouveauRuban.clicked.connect(nvRuban)

PyQt - Track Sender for contextMenu

What is the way of getting the Sender of a right-mouse-click on a QLabel()? I want to know on which Widget the right-mouse-click happened. I have code to get the position, but how can i get the Sender?
Getting the Sender i could retrieve the accessibleName()
Here is my current minimal Code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import * #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# qbtn = QtGui.QPushButton('Quit', self)
label = QLabel("BG Sessions", self)
label.setContextMenuPolicy(Qt.CustomContextMenu)
label.setObjectName("title")
label.customContextMenuRequested.connect(self.clearCache)
label.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Quit button')
self.show()
def clearCache(self, pos):
print pos
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
if you want to use sender() as suggested by Alexander Lutsenko keep this in mind:
QT-documentation
Warning: This function violates the object-oriented principle of modularity. However, getting access to the sender might be useful when many signals are connected to a single slot.
if all widgets sending the signal are from the same type,findChild() can be used instead. this is working with my tableViews:
# create signalMapper
self.signalMapper = QtCore.QSignalMapper(self)
self.signalMapper.mapped[str].connect(<slot>)
# connect the widgets with signalMapper
self.<widget>.<yourSignal>.connect(self.signalMapper.map)
self.signalMapper.setMapping(self.<widget>, self.<widget>.objectName()) # sends objectName() to slot
# in slot:
obj = self.findChild(QtWidgets.QLabel,objectname)
You could change the way you connect your signal such that you pass in a reference to the object you are connecting the signal from.
For instance:
my_object.customContextMenuRequested.connect(lambda pos, obj=my_object: self.clearCache(pos, obj))
(you will of course need to modify clearCache() so that it accepts this extra argument)
Note: the obj=my_object line is not redundant, see here for details.
self.sender() inside the slot does this job.

In PyQT4, how can I hide the window title of a child widget?

I am working in PyQT4 with Qt Designer. My goal is to hide the title bar of a widget.
I know there is a method like widget.setWindowFlags (QtCore.Qt.CustomizeWindowHint) or widget.setWindowFlags (QtCore.Qt.FramelessWindowHint), but it doesn't work in my case.
My widget is a child of QWorkspace. That means my widget was added to Qworspace. I am trying to hide the title bar in the same way, but it doesn't work.
Does anybody knows how to remove the program's title bar in this case?
My Code: I tried with both methods. They have been commented out.
Edit:
modul: search.py
from PyQt4.QtGui import QWidget
from PyQt4.uic import loadUi
from PyQt4.QtCore import Qt
class Search_Window(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent, Qt.FramelessWindowHint)
self.getPath_search_ui = os.path.join(os.path.abspath("."), 'files', "qt_ui", 'pp_search.ui')
self.ui_pp_search = loadUi(self.getPath_search_ui, self)
modul: mdi.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
from PyQt4.QtGui import QMainWindow, QWorkspace
from PyQt4.QtCore import Qt
from PyQt4.uic import loadUi
from ..modules_ui.ui_pp_search import Search_Window
class Mdi_Main(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.getPath_mdi = os.path.join(os.path.abspath("."), 'files', "qt_ui", 'pp_mdi.ui')
self.ui_TestMainWorkSpace = loadUi(self.getPath_mdi, self)
self.ui_TestMainWorkSpace.showMaximized()
self.workspace = QWorkspace()
self.workspace.setScrollBarsEnabled(True)
self.setCentralWidget(self.workspace)
def create_action_menu(self):
self.ui_TestMainWorkSpace.actionSearch.triggered.connect(self.show_search_form)
def show_search_form(self):
search_form = Search_Window()
self.workspace.addWindow(search_form, Qt.FramelessWindowHint)
search_form.show()
You can see I try to hide the title bar by adding search_form to workspace. Its also doesn't work.
The following snippet works for me, by specifying the window flags to the addWindow method:
from PyQt4.QtGui import QApplication, QWorkspace, QTableView
from PyQt4.QtCore import Qt
def main():
app = QApplication([])
workspace = QWorkspace()
view = QTableView()
workspace.addWindow(view, Qt.FramelessWindowHint)
workspace.show()
app.exec_()
if __name__ == '__main__':
main()

PyQt4 multithreading using QThread

There is an endless block when xml.etree.ElementTree.fromstring() function is called in the QThread. Also lots of other calls makes the QThread blocked like multiprocessing.Process().
Important to say that it is a pure block, no exception or break.
Here is the code (a little edited but same principle as the source):
from PyQt4.QtGui import *
from Ui_mainwindow import Ui_MainWindow
import sys
import xml.etree
class Bruton(QThread):
def __init__(self, mw):
super(Bruton, self).__init__(mw)
self.mw = mw
def run(self):
print("This message I see.")
tree = xml.etree.ElementTree.fromstring("<element>text</element>")
print("But this one never.")
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.init_bruton()
# When the form is shown...
def showEvent(self, arg1):
self.bruton.start()
def init_bruton(self):
self.bruton = Bruton(self)
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
The code as posted doesn't actually run, but with a couple minor changes it runs and works fine. Here is the code with modifications:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import xml.etree.ElementTree
class Bruton(QThread):
def __init__(self, mw):
super(Bruton, self).__init__(mw)
self.mw = mw
def run(self):
print("This message I see.")
tree = xml.etree.ElementTree.fromstring("<element>text</element>")
print("But this one never.")
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.init_bruton()
# When the form is shown...
def showEvent(self, arg1):
self.bruton.start()
def init_bruton(self):
self.bruton = Bruton(self)
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
And here is the output:
$ python test.py
This message I see.
But this one never.
This is with Python 2.6.6, PyQt4 4.8.3, on Debian Unstable.
Can you try it in your environment and see if my modified example works for you? If so, you are on the road to a solution for your real code. =)
The code I've shown here is shortened (the source is divided to two files and __ini__.py). I noticed that the main module must be the module that starts the QApplication. So I added app.exec_() to the __init__.py which is the main module of my program.

Categories

Resources