How to control QProgressBar with Signal - python

Pushing the button starts 100 rounds cycle. With QLabel.setText() we update self.label from inside of scope of clicked() function.
Aside from updating self.label we would like to update the progressbar as well.
But since progressbar is a local variable we can't update it from inside of onClick() function.
import time
class ProgressBar(QtGui.QProgressBar):
def __init__(self, parent=None, total=20):
super(ProgressBar, self).__init__(parent=parent)
self.setMinimum(1)
self.setMaximum(105)
self.setTextVisible(True)
def set_to_value(self, value):
self.setValue(value)
QtGui.qApp.processEvents()
def closeEvent(self, event):
self._active=False
class Dialog(QtGui.QDialog):
def __init__(self):
super(QtGui.QDialog,self).__init__()
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.label = QtGui.QLabel('idle...')
layout.addWidget(self.label)
progressbar = ProgressBar(self)
layout.addWidget(progressbar)
button = QtGui.QPushButton('Process')
button.clicked.connect(self.onClick)
layout.addWidget(button)
def onClick(self):
for i in range(101):
message = '...processing %s of 100'%i
self.label.setText(message)
QtGui.qApp.processEvents()
time.sleep(1)
if __name__ == '__main__':
app = QtGui.QApplication([])
dialog = Dialog()
dialog.resize(300, 100)
dialog.show()
app.exec_()

Declare the progress bar as:
self.progressbar = ProgressBar(self)

The code declares a local progressbar object connected to a custom 'customSignal` using:
QtCore.QObject.connect(self, QtCore.SIGNAL("customSignal(int)"), progressbar, QtCore.SLOT("setValue(int)"))
with four arguments passed to QtCore.QObject.connect().
The first argument self is the object that will be emitting the signal. Since the function that will do the "sleep-every-second-processing" is declared under the main Dialog instance we pass self here.
The second argument is the name of the signal itself: 'customSignal'.
The progressbar object is used as third and its method setValue as fourth last argument.
class ProgressBar(QtGui.QProgressBar):
def __init__(self, parent=None):
super(ProgressBar, self).__init__(parent=parent)
class Dialog(QtGui.QDialog):
def __init__(self):
super(QtGui.QDialog,self).__init__()
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.label = QtGui.QLabel('idle...')
layout.addWidget(self.label)
progressbar = ProgressBar(self)
QtCore.QObject.connect(self, QtCore.SIGNAL("customSignal(int)"), progressbar, QtCore.SLOT("setValue(int)"))
layout.addWidget(progressbar)
button = QtGui.QPushButton('Process')
button.clicked.connect(self.clicked)
layout.addWidget(button)
def clicked(self):
for value in range(101):
message = '...processing %s of 100'%value
self.label.setText(message)
self.emit(QtCore.SIGNAL("customSignal(int)"), value)
QtGui.qApp.processEvents()
time.sleep(1)
if __name__ == '__main__':
app = QtGui.QApplication([])
dialog = Dialog()
dialog.resize(300, 100)
dialog.show()
app.exec_()
--------------------
Here is variation of the same solution except linking to the progressbar method.
import time
class ProgressBar(QtGui.QProgressBar):
def __init__(self, parent=None):
super(ProgressBar, self).__init__(parent=parent)
def set_to_value(self, value):
self.setValue(value)
QtGui.qApp.processEvents()
return True
def closeEvent(self, event):
self._active=False
class Dialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self, parent=None)
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.label = QtGui.QLabel('idle...')
layout.addWidget(self.label)
progressbar = ProgressBar(self)
QtCore.QObject.connect(self, QtCore.SIGNAL("customSignal(int)"), progressbar.set_to_value )
layout.addWidget(progressbar)
button = QtGui.QPushButton('Process')
button.clicked.connect(self.clicked)
layout.addWidget(button)
def clicked(self):
for value in range(101):
message = '...processing %s of 100'%value
self.label.setText(message)
self.emit(QtCore.SIGNAL("customSignal(int)"), value)
QtGui.qApp.processEvents()
time.sleep(1)
if __name__ == '__main__':
app = QtGui.QApplication([])
dialog = Dialog()
dialog.resize(300, 100)
dialog.show()
app.exec_()
======================
This code now links a custom signal to a function referred as Slot in Qt.
from PySide import QtCore, QtGui
import time
class ProgressBar(QtGui.QProgressBar):
def __init__(self, parent=None):
super(ProgressBar, self).__init__(parent=parent)
#QtCore.Slot(int)
def set_to_value(self, value):
self.setValue(value)
QtGui.qApp.processEvents()
return True
def closeEvent(self, event):
self._active=False
class Dialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self, parent=None)
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
self.label = QtGui.QLabel('idle...')
layout.addWidget(self.label)
progressbar = ProgressBar(self)
# QtCore.QObject.connect(self, QtCore.SIGNAL("customSignal(int)"), progressbar.set_to_value )
QtCore.QObject.connect(self, QtCore.SIGNAL("customSignal(int)"), progressbar, QtCore.SLOT("set_to_value(int)"))
layout.addWidget(progressbar)
button = QtGui.QPushButton('Process')
button.clicked.connect(self.clicked)
layout.addWidget(button)
def clicked(self):
for value in range(101):
message = '...processing %s of 100'%value
self.label.setText(message)
self.emit(QtCore.SIGNAL("customSignal(int)"), value)
QtGui.qApp.processEvents()
time.sleep(1)
if __name__ == '__main__':
dialog = Dialog()
dialog.resize(300, 100)
dialog.show()

Related

Using QThread to Prevent Freeze when Clicking on QTreeWidget

Every time the user clicks on an item in QTreeWidget, the computer starts to perform some heavy duty tasks. My only objective is to use QThread to prevent freeze.
Consider the following code:
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('MainWindow')
self.layout = QVBoxLayout()
self.treewidget = MyTreeWidget()
self.treewidget.itemClicked.connect(self.tree_click)
self.layout.addWidget(self.treewidget)
self.label = QLabel("Label", self)
self.layout.addWidget(self.label)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
self.show()
#pyqtSlot(QTreeWidgetItem)
def tree_click(self, item):
time.sleep(2)
self.label.setText(item.text(0))
class MyTreeWidget(QTreeWidget):
def __init__(self):
super().__init__()
item_1 = QTreeWidgetItem()
item_1.setText(0, 'one item')
item_2 = QTreeWidgetItem()
item_2.setText(0,'another item')
self.addTopLevelItem(item_1)
item_1.addChild(item_2)
self.setHeaderHidden(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main = MainWindow()
app.exec()
How to modify the above code to prevent freeze and what is the most appropriate way of doing it?
I tried by following the protocol given in Background thread with QThread in PyQt, the second answer:
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('MainWindow')
self.layout = QVBoxLayout()
self.treewidget = MyTreeWidget()
self.treewidget.itemClicked.connect(self.tree_click)
self.layout.addWidget(self.treewidget)
self.label = QLabel("Label", self)
self.layout.addWidget(self.label)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
self.show()
#pyqtSlot(QTreeWidgetItem)
def tree_click(self, item):
self.obj = Worker()
self.thread = QThread()
self.obj.finished.connect(self.change_text)
self.obj.moveToThread(self.thread)
self.obj.finished.connect(self.thread.quit)
self.thread.started.connect(self.obj.work)
self.thread.start()
def change_text(self):
self.label.setText(item.text(0))
class Worker(QObject):
finished = pyqtSignal()
#pyqtSlot()
def work(self):
time.sleep(2)
finished = pyqtSignal()
class MyTreeWidget(QTreeWidget):
def __init__(self):
super().__init__()
item_1 = QTreeWidgetItem()
item_1.setText(0, 'one item')
item_2 = QTreeWidgetItem()
item_2.setText(0,'another item')
self.addTopLevelItem(item_1)
item_1.addChild(item_2)
self.setHeaderHidden(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main = MainWindow()
app.exec()
It does not look like I am doing the right thing.
I made a couple of minor adjustments to make your worker class run properly. This will prevent the rest of the gui from freezing but the label text that depends on the long running process will continue to take that long to update.
Also if the task implemented in the separate thread is repeated frequently you may want to consider using a QThreadPool.
I also included some inline comments to explain some of the changes.
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
import time
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('MainWindow')
self.layout = QVBoxLayout()
self.treewidget = MyTreeWidget()
self.treewidget.itemClicked.connect(self.tree_click)
self.layout.addWidget(self.treewidget)
self.label = QLabel("Label", self)
self.layout.addWidget(self.label)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
self.show()
self.threads = [] # make shift threads container
#pyqtSlot(QTreeWidgetItem)
def tree_click(self, item):
self.obj = Worker()
thread = QThread()
self.obj.text = item.text(0) # the obj needs a copy of the text to emit
self.obj.textReady.connect(self.change_text)
self.obj.moveToThread(thread)
self.obj.finished.connect(thread.quit)
thread.finished.connect(thread.deleteLater) # delete the threads once finished
thread.started.connect(self.obj.work)
thread.start()
self.threads.append(thread)
def change_text(self, text):
self.label.setText(text)
class Worker(QObject):
finished = pyqtSignal()
textReady = pyqtSignal([str])
#pyqtSlot()
def work(self):
time.sleep(2)
self.textReady.emit(self.text) # emit the text that needs to be changed
self.finished.emit()
class MyTreeWidget(QTreeWidget):
def __init__(self):
super().__init__()
item_1 = QTreeWidgetItem()
item_1.setText(0, 'one item')
item_2 = QTreeWidgetItem()
item_2.setText(0,'another item')
self.addTopLevelItem(item_1)
item_1.addChild(item_2)
self.setHeaderHidden(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main = MainWindow()
app.exec()

How to show another window

The project occurs loging in and signing in.
Im trying a transition from registerwindow to mainwindow and when we submit the window is automatically transit to mainwindow. There is only way to do this (at least for me) i have to import two python doc which named mainwindow.py and register.py, they are in same doc by the way.
This is the mainmenu.py
from PyQt5 import QtCore,QtGui,QtWidgets
from window.register import Ui_Form
class Ui_MainWindow(object):
def login(self):
self.window = QtWidgets.QWidget()
self.ui = Ui_Form()
self.ui.setupUi(self.window)
self.window.show()
MainWindow.hide()
and this is register.py
from PyQt5 import QtCore, QtGui, QtWidgets
from window.mainmenu import Ui_MainWindow
import sqlite3
class Ui_Form(object):
def submit(self):
sorgu2 = "Select * From users where nickname = ?"
sorgu = "INSERT INTO users values(?,?)"
self.cursor.execute(sorgu,(self.lineEdit.text(),self.lineEdit.text()))
self.connect.commit()
Form.hide()
self.window2 = QtWidgets.QMainWindow()
self.ui2 = Ui_MainWindow()
self.ui2.setupUi(self.window2)
self.window2.show()
Its supposed to be when i clicked to the button the register window will be hidden and mainmenu window will be show. Same thing for the mainmenu but the direct opposite
I know i am doing circular dependent imports but there is no other way but importing them to each other
If second window will be QDialog then you can hide main window, use exec() for QDialog and main window will wait till you close QDialog, and when it returns to main window then you can show it again.
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.button = QtWidgets.QPushButton("Show Second Window", self)
self.button.clicked.connect(self.show_second_window)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
self.show()
def show_second_window(self):
self.hide() # hide main window
self.second = SecondWindow()
self.second.exec() # will wait till you close second window
self.show() # show main window again
class SecondWindow(QtWidgets.QDialog): # it has to be dialog
def __init__(self):
super().__init__()
self.button = QtWidgets.QPushButton("Close It", self)
self.button.clicked.connect(self.show_second_window)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
self.show()
def show_second_window(self):
self.close() # go back to main window
app = QtWidgets.QApplication([])
main = MainWindow()
app.exec()
The other popular method is to create two widgets with all contents and replace widgets in one window.
from PyQt5 import QtWidgets
class MainWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.button = QtWidgets.QPushButton("Show Second Window", self)
self.button.clicked.connect(self.show_second_window)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
self.show()
def show_second_window(self):
self.close()
self.parent.set_content("Second")
class SecondWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.button = QtWidgets.QPushButton("Close It", self)
self.button.clicked.connect(self.show_second_window)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
self.show()
def show_second_window(self):
self.close()
self.parent.set_content("Main")
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout(self)
self.set_content("Main")
self.show()
def set_content(self, new_content):
if new_content == "Main":
self.content = MainWidget(self)
self.layout.addWidget(self.content)
elif new_content == "Second":
self.content = SecondWidget(self)
self.layout.addWidget(self.content)
app = QtWidgets.QApplication([])
main = MainWindow()
app.exec()
EDIT: Change window's content using QStackedLayout
from PyQt5 import QtWidgets
class FirstWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
layout = QtWidgets.QVBoxLayout(self)
self.button = QtWidgets.QPushButton("Show Second Stack", self)
self.button.clicked.connect(self.change_stack)
layout.addWidget(self.button)
def change_stack(self):
self.parent().stack.setCurrentIndex(1)
class SecondWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
layout = QtWidgets.QVBoxLayout(self)
self.button = QtWidgets.QPushButton("Show First Stack", self)
self.button.clicked.connect(self.change_stack)
layout.addWidget(self.button)
def change_stack(self):
self.parent().stack.setCurrentIndex(0)
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.stack = QtWidgets.QStackedLayout(self)
self.stack1 = FirstWidget(self)
self.stack2 = SecondWidget(self)
self.stack.addWidget(self.stack1)
self.stack.addWidget(self.stack2)
self.show()
app = QtWidgets.QApplication([])
main = MainWindow()
app.exec()

PyQt5 passing argument between two classes: lambda vs partial

I am trying to pass an argument between two PyQt5 classes. I used three methods:
Using lambda functions.
Wrapper function (similar to lambda function).
partial from functools module.
In the example below, I have two windows:
MainWindow has QLineEdit mw_line_edit and a QPushButton mw_open_new_dialog_button.
Dialog: has a QLineEdit line_edit and aQPushButton push_button.
When I click the button push_button, I want it to insert the content of line_edit to mw_line_edit.
Here is a minimal example:
import sys
from functools import partial
from PyQt5 import QtWidgets, QtGui, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.central_widget = QtWidgets.QWidget(self)
self.setCentralWidget(self.central_widget)
self.mw_open_new_dialog_button = QtWidgets.QPushButton('Open New dialog', self)
self.mw_line_edit = QtWidgets.QLineEdit(self)
self.hlayout = QtWidgets.QHBoxLayout(self)
self.hlayout.addWidget(self.mw_open_new_dialog_button)
self.hlayout.addWidget(self.mw_line_edit)
self.central_widget.setLayout(self.hlayout)
self.mw_open_new_dialog_button.clicked.connect(self.open_new_dialog)
def open_new_dialog(self):
self.dlg = Dialog()
#self.dlg.clicked.connect(partial(self.write_something, self.dlg.line_edit.text())) # <<<<<<< This does not work
self.dlg.clicked.connect(lambda: self.write_something(self.dlg.line_edit.text())) # this works
#self.dlg.clicked.connect(self.wrapper(self.dlg.line_edit.text()))# <<<<<<<<<<This does not work
self.dlg.exec()
#QtCore.pyqtSlot()
def write_something(self, text):
self.mw_line_edit.setText(text)
def wrapper(self, text):
return lambda: self.write_something(text)
class Dialog(QtWidgets.QDialog):
clicked = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(QtWidgets.QDialog, self).__init__(parent)
self.hlayout = QtWidgets.QHBoxLayout(self)
self.line_edit = QtWidgets.QLineEdit(self)
self.push_button = QtWidgets.QPushButton('Click me', self)
self.hlayout.addWidget(self.line_edit)
self.hlayout.addWidget(self.push_button)
self.label = QtWidgets.QLabel('I am a Qlabel', self)
self.hlayout.addWidget(self.label)
self.setLayout(self.hlayout)
self.push_button.clicked.connect(self.clicked)
def write_something(self, text):
print(text)
app = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
As you can see in the commented lines, only the following method works:
self.dlg.clicked.connect(lambda: self.write_something(self.dlg.line_edit.text()))
Why the other two do not work, i.e:
self.dlg.clicked.connect(partial(self.write_something, self.dlg.line_edit.text())) # <<<<<<< This does not work
self.dlg.clicked.connect(self.wrapper(self.dlg.line_edit.text()))# <<<<<<<<<<This does not work
Thanks
1) functools.partial()
What arguments are you passing to partial? You are passing the method write_something and the text of self.dlg.line_edit at the time the connection is made.
And what is the value of that text? it is an empty string, this explains the failure.
Is there any solution for this case? Yes, instead of passing the text, pass the QLineEdit, and in the method write_something get the text and set it in the other QLineEdit:
def open_new_dialog(self):
self.dlg = Dialog()
self.dlg.clicked.connect(partial(self.write_something, self.dlg.line_edit))
self.dlg.exec()
def write_something(self, le):
self.mw_line_edit.setText(le.text())
2) wrapper
It is the same problem, you are passing the empty text that you have at the moment of the connection
Is there any solution? Yes, the same solution as the previous one.
def open_new_dialog(self):
self.dlg = Dialog()
self.dlg.clicked.connect(self.wrapper(self.dlg.line_edit))
self.dlg.exec()
def write_something(self, text):
self.mw_line_edit.setText(text)
def wrapper(self, line):
return lambda: self.write_something(line.text())
Will there be a clean solution? Yes, create a signal that transports the text when you click.
from PyQt5 import QtWidgets, QtGui, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
self.mw_open_new_dialog_button = QtWidgets.QPushButton('Open New dialog')
self.mw_line_edit = QtWidgets.QLineEdit()
hlayout = QtWidgets.QHBoxLayout(central_widget)
hlayout.addWidget(self.mw_open_new_dialog_button)
hlayout.addWidget(self.mw_line_edit)
self.mw_open_new_dialog_button.clicked.connect(self.open_new_dialog)
#QtCore.pyqtSlot()
def open_new_dialog(self):
self.dlg = Dialog()
self.dlg.textSignal.connect(self.mw_line_edit.setText)
self.dlg.exec()
class Dialog(QtWidgets.QDialog):
textSignal = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(QtWidgets.QDialog, self).__init__(parent)
hlayout = QtWidgets.QHBoxLayout(self)
self.line_edit = QtWidgets.QLineEdit()
self.push_button = QtWidgets.QPushButton('Click me')
hlayout.addWidget(self.line_edit)
hlayout.addWidget(self.push_button)
self.label = QtWidgets.QLabel('I am a Qlabel')
hlayout.addWidget(self.label)
self.push_button.clicked.connect(self.sendText)
#QtCore.pyqtSlot()
def sendText(self):
self.textSignal.emit(self.line_edit.text())
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())

PyQt5 Automatic drawing from input value

I have recently created a widget with Qpaint, which I want to pass value to it, at the same time force the Qpaint Widget to draw from input values. The idea is to define a data value from a Qdialog and pass it to main widget, and pass the value to Qpaint Widget class. I would like to have, when user clicks on the button 'Getting values' a dialog widget would appear and insert some int values, then pass it to main Widget. from there pass value to correct class Paint. Which would draw and display the result. I tried with Qlabel, to assign value first to Qlabel or QlineEdit,
class Button(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Button, self).__init__(parent)
---------
self.value = QtWidgets.QLabel()
--------
Then inside the paint class call the value or text of those. then assign it to Qpaint event. But seems does not work.'
class Paint(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Paint, self).__init__(parent)
self.button = Button()
self.Value = self.button.value
---------
painter.drawRect(100,100,250,250) <----- instead of value 250 having self.Value
The code Main.py
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from datainput import *
class Foo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 800, 800))
self.button = Button()
self.paint = Paint()
self.lay = QtWidgets.QVBoxLayout()
self.lay.addWidget(self.paint)
self.lay.addWidget(self.button)
self.setLayout(self.lay)
class Paint(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Paint, self).__init__(parent)
self.button = Button()
self.Value = self.button.value
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
def paintEvent(self, event):
self.pen = QtGui.QPen()
self.brush = QtGui.QBrush( QtCore.Qt.gray, QtCore.Qt.Dense7Pattern)
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(self.pen)
painter.setBrush(self.brush)
painter.drawRect(100,100,250,250)
painter.setBrush(QtGui.QBrush())
class Button(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Button, self).__init__(parent)
getbutton = QtWidgets.QPushButton('Getting values')
Alay = QtWidgets.QVBoxLayout(self)
Alay.addWidget(getbutton)
self.value = QtWidgets.QLabel()
getbutton.clicked.connect(self.getbuttonfunc)
def getbuttonfunc(self):
subwindow=Dinput()
subwindow.setWindowModality(QtCore.Qt.ApplicationModal)
if subwindow.exec_() == QtWidgets.QDialog.Accepted:
self._output = subwindow.valueEdit.text()
return self.value.setText(self._output)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Foo()
w.show()
sys.exit(app.exec_())
Input Qdialog code, datainput.py
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Dinput(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Dinput, self).__init__(parent)
valuelabel = QtWidgets.QLabel('Input: ')
self.valueEdit = QtWidgets.QLineEdit()
buttonBox = QtWidgets.QDialogButtonBox()
buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.close)
self.Alay = QtWidgets.QHBoxLayout()
self.Alay.addWidget(valuelabel)
self.Alay.addWidget(self.valueEdit)
self.Blay = QtWidgets.QVBoxLayout()
self.Blay.addLayout(self.Alay)
self.Blay.addWidget(buttonBox)
self.setLayout(self.Blay)
def closeEvent(self, event):
super(Dinput, self).closeEvent(event)
def accept(self):
super(Dinput, self).accept()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Dinput()
w.show()
sys.exit(app.exec_())
Visualization
I appreciate any help. Thankssss
datainput is irrelevant, your task is only to obtain a number so for space question I will not use it and instead I will use QInputDialog::getInt(). Going to the problem, the strategy in these cases where the value can be obtained at any time is to notify the change to the other view through a signal, in the slot that receives the value is to update a variable that stores the value and call update so that it calls when necessary to paintEvent, and in the paintEvent use the variable that stores the value.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Foo(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 800, 800))
self.button = Button()
self.paint = Paint()
self.button.valueChanged.connect(self.paint.set_size_square)
self.lay = QtWidgets.QVBoxLayout(self)
self.lay.addWidget(self.paint)
self.lay.addWidget(self.button)
class Paint(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Paint, self).__init__(parent)
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
self._size_square = 250
#QtCore.pyqtSlot(int)
def set_size_square(self, v):
self._size_square = v
self.update()
def paintEvent(self, event):
pen = QtGui.QPen()
brush = QtGui.QBrush( QtCore.Qt.gray, QtCore.Qt.Dense7Pattern)
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(pen)
painter.setBrush(brush)
r = QtCore.QRect(QtCore.QPoint(100, 100), self._size_square*QtCore.QSize(1, 1))
painter.drawRect(r)
class Button(QtWidgets.QWidget):
valueChanged = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(Button, self).__init__(parent)
getbutton = QtWidgets.QPushButton('Getting values')
Alay = QtWidgets.QVBoxLayout(self)
Alay.addWidget(getbutton)
self.value = QtWidgets.QLabel()
getbutton.clicked.connect(self.getbuttonfunc)
#QtCore.pyqtSlot()
def getbuttonfunc(self):
number, ok = QtWidgets.QInputDialog.getInt(self, self.tr("Set Number"),
self.tr("Input:"), 1, 1)
if ok:
self.valueChanged.emit(number)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Foo()
w.show()
sys.exit(app.exec_())

Qt and python - how to refer to another class

I have main window which contains scene and button in widget from where I need to call scene:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class Widget(QWidget):
def __init__(self, scene):
super(Widget, self).__init__()
self.refreshButton = QPushButton("Refresh", self)
self.refreshButton.clicked.connect(self.Refresh)
# THIS ACTION SHOULD PROCEED ARGUMENTS
# TO FUNCION "Refresh"
layout = QHBoxLayout()
layout.addWidget(self.refreshButton)
self.setLayout(layout)
self.show()
def Refresh(self, scene):
mainWinScene = scene
print "On Refresh! - ", mainWinScene.items()
class MainScene(QGraphicsScene):
def __init__(self):
super(MainScene, self).__init__()
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.scene = MainScene()
self.scene.setSceneRect(0,0,200,100)
self.scene.addLine(20,10,150,80)
self.view = QGraphicsView()
self.view.setScene(self.scene)
drawRectAct = QAction('&Add Rectangle', self)
drawRectAct.triggered.connect(self.drawRect)
shapeInspectorAct = QAction('&Show Inspector', self)
shapeInspectorAct.triggered.connect(self.showInspector)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&Shapes')
fileMenu.addAction(drawRectAct)
fileMenu.addAction(shapeInspectorAct)
self.setCentralWidget(self.view)
def drawRect(self):
self.scene.addRect(50,50,20,30)
def showInspector(self):
self.I = Widget(self.scene)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
How to proceed "scene" argument with action - to "Refresh" function?
You can pass a scene in Widget's constructor:
class Widget(QWidget):
def __init__(self, scene):
...
self.scene = scene
...
def Refresh(self):
print "On Refresh! - ", self.scene.items()
class MainWindow(QMainWindow):
...
def showInspector(self):
self.I = Widget(self.scene)
...

Categories