Matplotlibwidget in QT gui graph update - python

I'm new in Python and I want to developp a GUI program.
I have installed pythonxy and I have developped a QT4 GUI that I have transformed in py with pyuic4.
In my program, I would like to update the mplwidget with new variables when I click on the button. I would like to update only the widget without restart the ui. How can I modify the solution below in order to update only the widget.
Thank you very much for your help and indications
from PyQt4 import QtCore, QtGui
from matplotlibwidget import MatplotlibWidget
import numpy as np
global y
global x
x=[1,2,3]
y=[1, 2, 1]
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.mplwidget = MatplotlibWidget(self.centralwidget)
self.mplwidget.setGeometry(QtCore.QRect(170, 150, 400, 300))
self.mplwidget.setObjectName("mplwidget")
self.mplwidget.setFocus()
self.mplwidget.axes.plot(x,y)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(170, 60, 75, 23))
self.pushButton.setObjectName("pushButton")
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.plot)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def plot(self):
global y
global x
x = [2,3,4]
y = [2,2,1]
self.replot()
def replot(self):
Ui_MainWindow()
ui.setupUi(MainWindow)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

I am not familiar with matplotlibwidget, so there may be an easier way to do this, but you can grab the Axes object and do what ever you want to it:
def replot_(self, x, y):
# plot the data and keep a reference to the `Line2D` object
ln, = self.matplotlibwidget.axes.plot(x, y)
# force the canvas to re-draw,
# matplotlibwidget may provide more direct access to the canvas
self.matplotlibwidget.axes.figure.canvas.draw()
return ln

Related

strange behaviour of pyplotlib upper menubar

I am willing to integrate a matplotlib figure into a GUI designed with pyqt5:
I wrote the code above:
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
class Ui_MainWindow(QMainWindow):
def setupUi(self, MainWindow):
self.vbox = QtWidgets.QVBoxLayout()
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1056, 600)
self.vbox2 = MainWindow.layout()
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit_x = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_x.setGeometry(QtCore.QRect(550, 430, 40, 20))
self.lineEdit_x.setObjectName("lineEdit_x")
self.lineEdit_x.setText(str(1))
self.lineEdit_y = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_y.setGeometry(QtCore.QRect(595, 430, 40, 20))
self.lineEdit_y.setObjectName("lineEdit_y")
self.lineEdit_y.setText(str(1))
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(490, 430, 66, 13))
self.label_3.setObjectName("label_3")
self.figure = plt.figure()#figsize=(40, 10), dpi=18)
self.canvas = FigureCanvas(self.figure)
#self.canvas.mpl_connect("button_release_event", self.on_release)
self.canvas.mpl_connect("button_press_event", self.on_press)
self.canvas.setGeometry(QtCore.QRect(0,30, 400, 400))
self.toolbar = NavigationToolbar(self.canvas, self)
self.vbox2.addWidget(self.toolbar)
self.vbox2.addWidget(self.canvas)
self.plot()
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1056, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def plot(self):
data = [random.random() for i in range(23)]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-', linewidth=0.5)
ax.set_title('PyQt Matplotlib Example')
self.canvas.draw()
def on_press(self, event):
self.lineEdit_x.setText(str(event.x))
self.lineEdit_y.setText(str(event.y))
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_3.setText(_translate("MainWindow", "Center (x,y)"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
as one can see I have 2 issues:
the menu bar is detached from the figure and reduced
the axes are smaller than the figure field.
so can someone please check my code to address these two issues with minimum modifications
thanks
There are many issues with your code, and most of them are caused by the fact that you're editing a pyuic file, which is considered a bad practice, and one of the many reasons of that consideration is that the class pyuic provides is often being used in the wrong way, like in this case.
First of all, you're creating instances for both QMainWindow and Ui_MainWindow, which already inherits from QMainWindow, so the first one is completely pointless.
Then, you're trying to access the main window layout, but that's also wrong, as QMainWindow has its own private layout. The only proper way to add widgets to a main window is using the provided API, and, in your case:
setCentralWidget() to set the central widget, which is the main content of the window, and set its layout to which the actual widgets are being added;
addToolBar() to add tool bars;
So, this is a proper rewriting of your expected result.
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.resize(1056, 600)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.canvas.mpl_connect('button_press_event', self.on_press)
self.toolbar = NavigationToolbar(self.canvas, self)
self.addToolBar(self.toolbar)
self.label = QtWidgets.QLabel('Center (x,y)')
self.lineEdit_x = QtWidgets.QLineEdit()
self.lineEdit_x.setText(str(1))
self.lineEdit_y = QtWidgets.QLineEdit()
self.lineEdit_y.setText(str(1))
central = QtWidgets.QWidget(self)
self.setCentralWidget(central)
mainLayout = QtWidgets.QVBoxLayout(central)
mainLayout.addWidget(self.canvas)
bottomLayout = QtWidgets.QHBoxLayout()
mainLayout.addLayout(bottomLayout)
bottomLayout.addWidget(self.label)
bottomLayout.addWidget(self.lineEdit_x)
bottomLayout.addWidget(self.lineEdit_y)
self.plot()
def plot(self):
data = [random.random() for i in range(23)]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-', linewidth=0.5)
ax.set_title('PyQt Matplotlib Example')
self.canvas.draw()
def on_press(self, event):
self.lineEdit_x.setText(str(event.x))
self.lineEdit_y.setText(str(event.y))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
Note that if you still want to use Designer, then keep in mind that:
as said above, you should not edit the pyuic generated file (but, instead, follow the official guidelines about using Designer;
add the canvas by code, or use a promoted widget (do some research on the subject);
always use layout managers for all widgets;

How to link QGraphicsScene to QGraphicsView inside a QtDesigner generated code

I want to display an image using QGraphicsView in a window. I have a basic QGraphicsView and a button based test.ui file generated from QtDesigner tool. Corresponding test.py file:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setObjectName("graphicsView")
self.verticalLayout.addWidget(self.graphicsView)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I made use of QGraphicsScene to display an image inside this QGraphicsView. My current working solution is to mess up the above .py file as follows:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.scene = QtWidgets.QGraphicsScene(self.centralwidget) #added
self.graphicsView = QtWidgets.QGraphicsView(self.scene) #edited
self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setObjectName("graphicsView")
self.verticalLayout.addWidget(self.graphicsView)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.pushButton.clicked.connect(self.display)
def display(self):
import imageio, numpy
self.scene.clear()
input_image = imageio.imread('image.jpg').copy()
height, width, channels = input_image.shape
bytesPerLine = channels * width
qimg = QtGui.QImage(input_image, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)
self.pixmap = QtGui.QPixmap.fromImage(qimg)
self.scene.addPixmap(self.pixmap) #add pixmap to scene
self.graphicsView.scale(0.5,0.5)
self.scene.update()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
However, this solution is not systematic. I want to do the same without editing the original test.ui generated test.py file.
So, I tried following code which to me appears like a systematic translation of the previous working code. However, it fails to produce any display on button click:
from PyQt5 import QtCore, QtGui, QtWidgets
from test import Ui_MainWindow
class myWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent=parent)
self.setupUi(self)
self.scene = QtWidgets.QGraphicsScene(self.centralwidget) #append scene method
self.graphicsView = QtWidgets.QGraphicsView(self.scene) #graphicsView re-assigned with scene
self.pushButton.clicked.connect(self.display)
def display(self):
import imageio, numpy
self.scene.clear()
input_image = imageio.imread('image.jpg').copy()
height, width, channels = input_image.shape
bytesPerLine = channels * width
qimg = QtGui.QImage(input_image, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)
self.pixmap = QtGui.QPixmap.fromImage(qimg)
self.scene.addPixmap(self.pixmap) #add pixmap to scene
self.graphicsView.scale(0.5,0.5)
self.scene.update()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = myWindow()
w.show()
sys.exit(app.exec_())
I am likely messing up something due to my limited understanding of class inheritance, QGraphicsView, and QGraphicsScene. Any pointers to my mistakes would be very helpful.
Note: I am using a myWindow class to integrate some key press functionality in future. I think the issue is more to do with how to selectively append/redefine few lines inside a parent class function. Is this even possible without re-writing the whole setupUi method? Or, is there another smarter way to perform the same task?
You have to set the scene to the existing QGraphicsView instead of creating a new QGraphicsView:
class myWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.scene = QtWidgets.QGraphicsScene(self.centralwidget)
self.graphicsView.setScene(self.scene)
self.pushButton.clicked.connect(self.display)
def display(self):
# ...

Start a QT Thread when button is clicked

This is a sample code with just a push button and a textedit, i need to write line x line using a loop in a textedit when button is clicked.
The problem is that i need to implement threads because without them the program crashes or it doesn't write line x line, but all together when the loop ends;
and i need to implement in my application a textedit that shows info while the program loads "something".
So my question is, how to rewrite this code using threads to write in textedit when button is clicked?
The method i should run when the button is clicked is "write"
it should work like a print inside a for loop , it would print not all at once
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(150, 220, 321, 71))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(240, 100, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.pushButton.clicked.connect(self.write)
def write(self):
string=""
for i in range(1000):
string="\n"+str(i)
self.textEdit.insertPlainText(string)
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
First of all it is recommended not to modify the class generated by Qt Designer so you must regenerate the file and assume that it is called mainwindow.py: pyuic5 your_file.ui -o mainwindow.py -x.
Considering the above, the logic is to generate the information in another thread and send it to the GUI to modify it:
main.py
import threading
from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow import Ui_MainWindow
class WriterWorker(QtCore.QObject):
textChanged = QtCore.pyqtSignal(str)
def start(self):
threading.Thread(target=self._execute, daemon=True).start()
def _execute(self):
string = ""
for i in range(1000):
string = "\n"+str(i)
self.textChanged.emit(string)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.writer_worker = WriterWorker()
self.writer_worker.textChanged.connect(self.on_text_changed)
self.pushButton.clicked.connect(self.writer_worker.start)
#QtCore.pyqtSlot(str)
def on_text_changed(self, text):
self.textEdit.insertPlainText(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Code only works when PDB is active

I am currently trying to create a main window that can interact with a dialog window, but I came across an issue I thought was interesting.
Basically, I'm trying to get test_1 to interact with test_2. When I test the code by itself, works, and does what it's supposed to do, but when I use Test_1 to interact with Test_2, the script regarding test 2 no longer has its full functionality.
Interestingly enough, when I go through the code, it's able to print "hello", and the function that I link to print("hello") isn't tied to a class. However, the function that doesn't work (the function where I just ask to insert "hello" into a text box) is tied to a class and that is the function that is not working. Also, the code works just fine if I use pdb within the Test_1.
Here is my code regarding test 1 and test 2 (you'll probably have to install PyQT5 if you haven't already):
Test_1
import test_2 as t2
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Test_1(object):
def setupUi(self, Test_1):
Test_1.setObjectName("Test_1")
Test_1.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(Test_1)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(130, 120, 461, 281))
self.pushButton.setObjectName("pushButton")
Test_1.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(Test_1)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
Test_1.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(Test_1)
self.statusbar.setObjectName("statusbar")
Test_1.setStatusBar(self.statusbar)
self.retranslateUi(Test_1)
QtCore.QMetaObject.connectSlotsByName(Test_1)
self.pushButton.clicked.connect(self.connect_test_2)
def retranslateUi(self, Test_1):
_translate = QtCore.QCoreApplication.translate
Test_1.setWindowTitle(_translate("Test_1", "MainWindow"))
self.pushButton.setText(_translate("Test_1", "Open Dialog"))
def connect_test_2(self):
#import pdb; pdb.set_trace()
self.t2 = QtWidgets.QDialog()
ui = t2.Ui_Test_2()
ui.setupUi(self.t2)
self.t2.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Test_1()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Test 2
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Test_2(object):
def setupUi(self, Test_2):
Test_2.setObjectName("Test_2")
Test_2.resize(400, 300)
self.buttonBox = QtWidgets.QDialogButtonBox(Test_2)
self.buttonBox.setGeometry(QtCore.QRect(290, 20, 81, 241))
self.buttonBox.setOrientation(QtCore.Qt.Vertical)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.pushButton = QtWidgets.QPushButton(Test_2)
self.pushButton.setGeometry(QtCore.QRect(20, 90, 341, 161))
self.pushButton.setObjectName("pushButton")
self.textEdit = QtWidgets.QTextEdit(Test_2)
self.textEdit.setGeometry(QtCore.QRect(20, 10, 104, 71))
self.textEdit.setObjectName("textEdit")
self.retranslateUi(Test_2)
#self.buttonBox.accepted.connect(Test_2.accept)
#self.buttonBox.rejected.connect(Test_2.reject)
QtCore.QMetaObject.connectSlotsByName(Test_2)
self.pushButton.clicked.connect(self.printHello)
self.pushButton.clicked.connect(dummyCode)
def printHello(self):
self.textEdit.setText("Hello")
def retranslateUi(self, Test_2):
_translate = QtCore.QCoreApplication.translate
Test_2.setWindowTitle(_translate("Test_2", "Dialog"))
self.pushButton.setText(_translate("Test_2", "PushButton"))
def dummyCode():
print("Hello")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Test_2()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

Get the values from the vertical slider in pyqt4 and save that value into one variable

I am new to the world of qt and python. I have created vertical slider in pyqt4. I want to access the vertical slider(int) value and assign it to a variable since I have to pass value of this variable to another function. Here is my code please suggest me what should I add to my code so as to get value from slider.
Code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Thu Sep 25 13:08:56 2014
# by: PyQt4 UI code generator 4.9.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(698, 455)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.verticalSlider = QtGui.QSlider(self.centralWidget)
self.verticalSlider.setGeometry(QtCore.QRect(100, 70, 19, 251))
self.verticalSlider.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider.setObjectName(_fromUtf8("verticalSlider"))
self.lcdNumber = QtGui.QLCDNumber(self.centralWidget)
self.lcdNumber.setGeometry(QtCore.QRect(250, 130, 211, 81))
self.lcdNumber.setObjectName(_fromUtf8("lcdNumber"))
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 698, 21))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.verticalSlider, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.lcdNumber.display)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Suppose you have the following in your code:
sld = QtGui.QSlider(QtCore.Qt.Vertical, self)
You can connect the changes in the slider to an other function like:
sld.valueChanged[int].connect(self.funcThatTakeAnIntAsArg)
and define the method
def funcThatTakeAnIntAsArg(self, valueOfSlider):
self.someWidget.doSomethingWith(valueOfSlider)
As the QSlider inherists QAbstractSlider, you can get the value with QSlider.value.
Add this,
self.verticalSlider.valueChanged[int].connect(self.func)
where func is defined as:
def func(self, value):
print value

Categories

Resources