How to transfer QLineEdit value into console? - python

Assume we have an interface with Buttons and LineEdits in one .py file. I have this code in another, which inherits it:
import Inter_Input_Blasting as interf
from PyQt6 import QtCore,QtWidgets,QtGui
from functools import partial
class MainWindow(QtWidgets.QMainWindow):
def on_clicked(self):
print("Button Pushed")
def __init__(self,parent=None):
super(MainWindow, self).__init__(parent)
self.ui = interf.Ui_MainWindow()
self.ui.setupUi(self)
self.ui.calc_button.clicked.connect(MainWindow.on_clicked)
self.ui.input_overall_1.textChanged.connect(MainWindow.gather_data)
def gather_data(self):
return self.ui.input_overall_1.text()
if __name__== "__main__":
import sys
app = interf.QtWidgets.QApplication(sys.argv)
Form = MainWindow()
Form.show()
sys.exit(app.exec())
So, i need to print my values into console when i put it in the lineedit fiels. The .textChanged() method is working, but the .gather_data() isn't.

Provide a variable for storing the text:
def __init__(self,parent=None):
self.txt = None
Then in method gather_data, store the text in that variable:
def gather_data(self):
sef.txt = self.ui.input_overall_1.text()
then before sys.exit, print that value:
r = app.exec()
print(Form.txt)
sys.exit(r)

Related

Pyqt5 open child windows of class of another file *.py Pb [duplicate]

I am trying to display a loading gif after a button is pressed. This is the code I currently have
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainWindow (QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow,self).__init__(parent)
self.setGeometry(50,50,240,320)
self.home()
def home(self):
but = QtGui.QPushButton("Example", self)#Creates the brew coffee button
but.clicked.connect(self.gif_display)
but.resize(200,80)
but.move(20,50)
self.show()
def gif_display(self):
l = QMovieLabel('loading.gif')
l.show()
class QMovieLabel(QLabel):
def __init__(self, fileName):
QLabel.__init__(self)
m = QMovie(fileName)
m.start()
self.setMovie(m)
def setMovie(self, movie):
QLabel.setMovie(self, movie)
s=movie.currentImage().size()
self._movieWidth = s.width()
self._movieHeight = s.height()
def run():
app = QtGui.QApplication(sys.argv)
GUI = MainWindow()
sys.exit(app.exec_())
run()
I would like to display the gif called "loading.gif" after the button is pressed. Nothing appears after pressing the button and I am unsure of what to do to get the gif to properly appear. The gif is the same size as the screen that I created (240x320).
The problem is that QMovieLabel is a local variable within gif_display so it will be deleted when the function finishes running, so the solution is to avoid deleting it. There are 2 options: make it an attribute of the class or make it a child of the window , I will show the second method since I think it is the one you want:
import sys
from PyQt4 import QtCore, QtGui
class MainWindow (QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow,self).__init__(parent)
self.setGeometry(50,50,240,320)
self.home()
def home(self):
but = QtGui.QPushButton("Example", self) # Creates the brew coffee button
but.clicked.connect(self.gif_display)
but.resize(200,80)
but.move(20,50)
self.show()
#QtCore.pyqtSlot()
def gif_display(self):
l = QMovieLabel('loading.gif', self)
l.adjustSize()
l.show()
class QMovieLabel(QtGui.QLabel):
def __init__(self, fileName, parent=None):
super(QMovieLabel, self).__init__(parent)
m = QtGui.QMovie(fileName)
self.setMovie(m)
m.start()
def setMovie(self, movie):
super(QMovieLabel, self).setMovie(movie)
s=movie.currentImage().size()
self._movieWidth = s.width()
self._movieHeight = s.height()
def run():
app = QtGui.QApplication(sys.argv)
GUI = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
run()

How to return value from the QWidget

I have a widget that ends with pressing OK button. I want that the widget returns a value to the main program (which is in simple example below the obtained value increased by 1). How can I do this?
Also, is there any more elegant way to show the same QWidget with the different title?
MWE:
import sys
from PyQt5 import QtGui, QtCore, QtWidgets
class MainWindow(QtWidgets.QWidget):
def __init__(self,val):
self.val=val
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.End= QtWidgets.QPushButton('OK', self)
self.End.clicked.connect(self.end)
MainLayout = QtWidgets.QVBoxLayout()
MainLayout.addWidget(self.End)
self.setLayout(MainLayout)
self.setWindowTitle(str(self.val))
self.show()
def end(self):
# return self.val+1
self.close()
def main():
app = QtWidgets.QApplication(sys.argv)
for i in range(10):
ex = MainWindow(i)
ex.show()
res = app.exec_()
print(res)
sys.exit()
if __name__ == '__main__':
main()
If you want to use a widget to get some value after some processing, the correct thing is to use QDialog, that prevents any other window from opening if you use exec_():
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Dialog(QtWidgets.QDialog):
def __init__(self, val, parent=None):
super(Dialog, self).__init__(parent)
self.val = val
self.initUI()
def initUI(self):
endButton = QtWidgets.QPushButton('OK')
endButton.clicked.connect(self.on_clicked)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(endButton)
self.setWindowTitle(str(self.val))
#QtCore.pyqtSlot()
def on_clicked(self):
self.val += 1
self.accept()
def main():
app = QtWidgets.QApplication(sys.argv)
for i in range(10):
ex = Dialog(i)
ex.setAttribute(QtCore.Qt.WA_DeleteOnClose)
if ex.exec_() == QtWidgets.QDialog.Accepted:
print(ex.val)
if __name__ == '__main__':
main()
It is unclear what exactly your intention is with this code. If val is supposed to be a counter for the number of MainWindow instances, then you must declare it as a static:
class MainWindow(QtWidgets.QWidget):
val = 0
def __init__(self):
super(MainWindow, self).__init__()
MainWindow.val += 1
self.initUI()
def initUI(self):
# ...
self.setWindowTitle(str(MainWindow.val))
# ...
def main():
# ...
for i in range(10):
ex = MainWindow()
# ...
# ...
There is nothing wrong in calling QWidget::setWindowTitle() so I don't see a problem here.
If you really want to have it as a non-static class member and each MainWindow uses it as some sort of ID, you can easily call the value right after the ex.show():
def main():
app = QtWidgets.QApplication(sys.argv)
for i in range(10):
ex = MainWindow()
ex.show()
print(MainWindow.val)
res = app.exec_()
print(res)
sys.exit()
Just because you close a widget doesn't mean you have destroyed it so calling the values stored inside the object is not an issue.
However it appears you are not familiar what QApplication::exec() is intended for. It runs the main loop of the given application and returns the exit status (you can set it when calling exit() as the parameter passed to that function). If you simply want to get the value of val upon closing a widget you can simply override the closeEvent handler and emit a signal. Create a QObject instance and connect each MainWindow instance's custom close signal to a slot and do with the value whatever you want to.

Trouble with PyQt4 List Widget

So my problem is the following:
I have a program that I created in QT Designer and added some code in Python.
There is an main window and two windows wich appear when you click an button in the window before.
The List Widget is in the second window:
Hope with this picture you can understand what I mean
So now I want to add some Items to my list widget.
def add_number_to_list(self):
self.ui.list_of_numbers.addItem('test')
So I call this function on another place but it didn't happen anything.
If I add an print command, to test if the function works: The print is showed. But nothing appears in the list widget...
What is wrong?
import sys
from PyQt4 import QtGui
import p_design, p_edit_numbers, p_add_number
number_to_add = ''
class Example(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = p_design.Ui_MainWindow()
self.ui.setupUi(self)
self.ui.manually_alarm.clicked.connect(self.alarm)
self.ui.edit_numbers.clicked.connect(self.open_edit_numbers)
def alarm(t1,t2):
#send sms to numbers
print('ALARM!')
def open_edit_numbers(self):
self.test = EditNumbers(self)
self.test.show()
class EditNumbers(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = p_edit_numbers.Ui_MainWindow()
self.ui.setupUi(self)
self.ui.add_number.clicked.connect(self.open_add_number)
### Problem! ###
def add_number_to_list(self):
self.ui.list_of_numbers.addItems('test')
################
def open_add_number(self):
self.t3 = AddNumber(self)
self.t3.show()
class AddNumber(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = p_add_number.Ui_MainWindow()
self.ui.setupUi(self)
self.ui.add.clicked.connect(self.add_number)
def add_number(self):
global number_to_add
editnumbers=EditNumbers()
editnumbers.add_number_to_list()
def main():
app = QtGui.QApplication(sys.argv)
form = Example()
form.show()
sys.exit(app.exec_())
main()

PyQt signal slot issue with signal outside creating class

I am trying to create a toolbar that can be modified to change actions on the fly.
However signals are not being sent when I add actions from outside the class that creates the toolbar.
In the example below the new action is never triggered. Any idea on how this can be done?
import sys
from PyQt4 import QtGui
from toolbarmodifier import ToolbarModifier
class FluidToolbar(QtGui.QMainWindow):
def __init__(self):
super(FluidToolbar, self).__init__()
self.initUI()
def initUI(self):
createAction = QtGui.QAction( 'create Action', self)
createAction.triggered.connect(self.createActions)
self.toolbar = self.addToolBar('create Action')
self.toolbar.addAction(createAction)
self.setGeometry(300, 300, 300, 200)
self.show()
def createActions(self):
print(">>createActions()")
toolbarModifier = ToolbarModifier()
toolbarModifier.addAction(self)
def main():
app = QtGui.QApplication(sys.argv)
ex = FluidToolbar()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
toolbarmodifier.py
from PyQt4 import QtGui
from PyQt4.QtGui import QWidget
class ToolbarModifier(QWidget):
def __init__(self):
super(ToolbarModifier, self).__init__()
def newActionTriggered(self):
print(">>newActionTriggered()")
def addAction(self, gui):
triggerAction = QtGui.QAction( 'New action', gui)
triggerAction.triggered.connect(self.newActionTriggered)
gui.toolbar.addAction(triggerAction)
print("<<addAction()")
Not having a link back to parent was the issue. In FluidToobar modify code in createActions method to include self in call:
toolbarModifier = ToolbarModifier(self)
In ToolbarModifier change first few lines to:
class ToolbarModifier(QtCore.QObject):
def __init__(self, parent=None):
super(ToolbarModifier, self).__init__(parent)

How can I get the previous activated widget in PyQt?

I have a button and two tablewidgets.Pressing the button does two different things depending on which one of the tablewidgets was activated before the push of the button.How can I get the right widget?
You could for example use the focusInEvent to store the activated widget and return it when pressing the button, something like this:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore
class MyTableWidget(QtGui.QTableWidget):
focusIn = QtCore.pyqtSignal(QtCore.QObject)
def __init__(self, parent=None):
super(MyTableWidget, self).__init__(parent)
def focusInEvent(self, event):
self.focusIn.emit(self)
return super(MyTableWidget, self).focusInEvent(event)
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.lastFocusedTableWidget = None
self.tableWidgetFirst = MyTableWidget(self)
self.tableWidgetFirst.setObjectName("tableWidgetFirst")
self.tableWidgetFirst.focusIn.connect(self.on_tableWidget_focusIn)
self.tableWidgetSecond = MyTableWidget(self)
self.tableWidgetSecond.setObjectName("tableWidgetSecond")
self.tableWidgetSecond.focusIn.connect(self.on_tableWidget_focusIn)
self.pushButtonLastFocused = QtGui.QPushButton(self)
self.pushButtonLastFocused.setText("Print the last focused QTableWidget!")
self.pushButtonLastFocused.clicked.connect(self.on_pushButtonLastFocused_clicked)
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.tableWidgetFirst)
self.layoutVertical.addWidget(self.tableWidgetSecond)
self.layoutVertical.addWidget(self.pushButtonLastFocused)
#QtCore.pyqtSlot(QtCore.QObject)
def on_tableWidget_focusIn(self, obj):
self.lastFocusedTableWidget = obj
#QtCore.pyqtSlot()
def on_pushButtonLastFocused_clicked(self):
print self.lastFocusedTableWidget.objectName()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.resize(333, 111)
main.show()
sys.exit(app.exec_())

Categories