How can I take a value from a line edit to another window's line edit by using Python and PyQt5? - python-3.x

What I need:
I need to create a simple project that can take value from window to another window
My research effort:
So, I create two classes for two windows then connect to classes with each other, so when I click in button it takes the value from 1st window then open the other window but the value=nothing because the clickMethod returns nothing.
Below is my code:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("First Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('1st:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
pybutton = QPushButton('OK', self)
pybutton.clicked.connect(self.second_wind) #connect button to open second window
pybutton.clicked.connect(self.clickMethod)
pybutton.resize(200,32)
pybutton.move(80, 60)
def clickMethod(self):
value =self.line.text() #take value from the line edit
return value
def second_wind(self): #object from secod_window class
self.SW = Second_Window()
self.SW.show()
class Second_Window(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("Second Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('Name:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
self.f = MainWindow() #make object from MainWindow class to execute clickMethod() to reutrn value
a=self.f.clickMethod()
print(a)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )
I expect the Clickmethod to return the value
but it returns nothing

Try it:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("First Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('1st:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
pybutton = QPushButton('OK', self)
pybutton.clicked.connect(self.second_wind)
# pybutton.clicked.connect(self.clickMethod)
pybutton.resize(200,32)
pybutton.move(80, 60)
# def clickMethod(self):
# value =self.line.text()
# return value
def second_wind(self):
text = self.line.text() # +++
self.SW = Second_Window(text) # +++ (text)
self.SW.show()
class Second_Window(QMainWindow):
def __init__(self, text): # +++ (text)
QMainWindow.__init__(self)
self.text = text # +
self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("Second Window")
self.nameLabel = QLabel(self)
self.nameLabel.setText('Name:')
self.line = QLineEdit(self)
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)
# self.f = MainWindow()
# a=self.f.clickMethod()
self.line.setText(self.text) # +
print(self.text)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )

Related

PyQt5 does not redrawing widget

Force repainting does not repaint PyQt5 widget (Qlabel, QTextEdit, even QProgressBar and etc)
Tested platforms: Linux, MacOS
PyQt5 version: 5.15.7
Installed from pip
As example I created simple app that updating text in QLabel widget in for loop. Force repainting doesnt working
import sys
from time import sleep
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QLabel)
class Example(QWidget):
def __init__(self):
super().__init__()
self.text = QLabel('Test', self)
self.text.move(10, 10)
self.text.resize(60,20)
self.button = QPushButton('Run', self)
self.button.move(17,40)
self.button.clicked.connect(self.some_activity)
self.setGeometry(300, 300, 100, 80)
self.show()
def some_activity(self):
for i in range(100):
text = f'i = {i}'
self.text.setText(text)
# self.text.update() -> Nothing happens (it shouldnt: https://doc.qt.io/qt-5/qwidget.html#update)
self.text.repaint() # -> Nothing happens
self.repaint() # -> Nothing happens
print(f'Text updated: {text}')
sleep(0.03)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Video demonstration: link
Just needed to use QThread to use for loop in my program
Thanks #musicamante for helping.
import sys
from time import sleep
from PyQt5 import QtCore
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QLabel)
class Thread(QtCore.QThread):
signal = QtCore.pyqtSignal(str)
def __init__(self, parent=None): QtCore.QThread.__init__(self, parent)
def run(self):
for i in range(100):
text = f'i = {i}'
print(f'Text updated: {text}')
self.signal.emit(text)
sleep(.3)
class Example(QWidget):
def __init__(self):
super().__init__()
self.text = QLabel('Test', self)
self.text.move(10, 10)
self.text.resize(60,20)
self.thread = Thread()
self.thread.signal.connect(self.signal, QtCore.Qt.QueuedConnection)
self.button = QPushButton('Run', self)
self.button.move(17,40)
self.button.clicked.connect(self.thread.start)
self.setGeometry(300, 300, 100, 80)
self.show()
def signal(self, text): self.text.setText(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

Get a selected font in a subclassed QFontDialog

I'm trying to subclass QFontDialog and would like to retrieve the characteristics of the selected font. If I use getFont() a QFontDialog window appears first, ... I'm certainly doing something wrong.
Here's my example code :
from PyQt5.QtWidgets import (QFontDialog, QPushButton,
QMainWindow, QApplication,
QTabWidget, QWidget, QVBoxLayout)
import sys
class FontSelection(QFontDialog) :
def __init__(self, parent=None):
super(FontSelection, self).__init__(parent)
self.setOption(self.DontUseNativeDialog, True)
self.bouton = self.findChildren(QPushButton)
self.intitule_bouton = self.bouton[0].text().lower()
self.ouvertureBouton = [x for x in self.bouton if self.intitule_bouton in str(x.text()).lower()][0]
self.ouvertureBouton.clicked.disconnect()
self.ouvertureBouton.clicked.connect(self.font_recup)
def font_recup(self) :
self.font_capture()
def font_capture(self) :
if self.intitule_bouton in ['ok', '&ok'] :
font, self.intitule_bouton = self.getFont()
print(font)
class MainQFontDialogTry(QMainWindow):
def __init__(self):
super(MainQFontDialogTry, self).__init__()
self.setWindowTitle('QFontDialog subclassed try')
self.setGeometry(0, 0, 1000, 760)
self.setMinimumSize(1000, 760)
self.tab_widget = QTabWidget()
self.win_widget_1 = FontSelection(self)
widget = QWidget()
layout = QVBoxLayout(widget)
self.tab_widget.addTab(self.win_widget_1, "QFontDialog Tab")
layout.addWidget(self.tab_widget)
self.setCentralWidget(widget)
self.qfont = FontSelection()
self.qfont.font_recup()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainQFontDialogTry()
ex.show()
sys.exit(app.exec_())

pyqt5 trying to use QGridLayout to organise my QLabel, QLineEdit, QPushButton, and "Pop-up" QLabel

I am trying to get the "Game Name:" (QLabel), input box (QLineEdit), and QPushButton on one line and the "Pop-up" QLabel) to appear on the bottom
but am having difficulties with get QGridLayout to work
With this code:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QPushButton, QLabel, QLineEdit, QGridLayout, QGroupBox, QDialog
from PyQt5.QtCore import pyqtSlot
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("Project PiBu!!")
self.createGridLayout()
self.windowLayout = QVBoxLayout()
self.windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(self.windowLayout)
self.game_name = QLabel("Game Name:", self)
self.game_line_edit = QLineEdit(self)
self.search_button = QPushButton("Search", self)
self.search_button.clicked.connect(self.on_click)
self.game = QLabel(self)
self.show()
def createGridLayout(self):
self.horizontalGroupBox = QGroupBox()
self.layout = QGridLayout()
self.layout.setColumnStretch(1, 4)
self.layout.setColumnStretch(2, 4)
self.layout.addWidget(self.game_name, 0, 0)
self.layout.addWidget(self.game_line_edit, 0, 1)
self.layout.addWidget(self.search_button, 0, 2)
self.layout.addWidget(self.game, 1, 0)
self.horizontalGroupBox.setLayout(layout)
#pyqtSlot()
def on_click(self):
self.game.setText(self.game_line_edit.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
I am getting this error:
AttributeError: 'Window' object has no attribute 'game_name'
Why?
have a feeling its something simple rather than something more complicated but maybe I'm wrong
Please help!!!
Thank you!
You call the createGridLayout method earlier than you define the variables used in it.
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout,
QVBoxLayout, QPushButton, QLabel, QLineEdit,
QGridLayout, QGroupBox, QDialog)
from PyQt5.QtCore import pyqtSlot
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("Project PiBu!!")
# self.createGridLayout()
# self.windowLayout = QVBoxLayout()
# self.windowLayout.addWidget(self.horizontalGroupBox)
# self.setLayout(self.windowLayout)
self.game_name = QLabel("Game Name:", self)
self.game_line_edit = QLineEdit(self)
self.search_button = QPushButton("Search", self)
self.search_button.clicked.connect(self.on_click)
self.game = QLabel(self)
self.createGridLayout() # < --
self.windowLayout = QVBoxLayout() # < --
self.windowLayout.addWidget(self.horizontalGroupBox) # < --
self.setLayout(self.windowLayout) # < --
self.show()
def createGridLayout(self):
self.horizontalGroupBox = QGroupBox()
self.layout = QGridLayout()
self.layout.setColumnStretch(1, 4)
self.layout.setColumnStretch(2, 4)
# AttributeError: 'Window' object has no attribute 'game_name'
self.layout.addWidget(self.game_name, 0, 0)
self.layout.addWidget(self.game_line_edit, 0, 1)
self.layout.addWidget(self.search_button, 0, 2)
self.layout.addWidget(self.game, 1, 0)
self.horizontalGroupBox.setLayout(self.layout) # +++ self.
#pyqtSlot()
def on_click(self):
self.game.setText(self.game_line_edit.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

Spin box not showing up

I'm unsure why all aspects of my GUI are showing up apart from the spin box (the code for it is within the home function).
I've tried moving it to the init(self) function, but that doesn't work. I thought it would be intuitive for it to be within the home function as that is where all my other GUI (e.g. buttons) resides.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QAction, QMessageBox, QDoubleSpinBox
from temperature import MplWindow
from filament import MplWindow1
from highvoltage import MplWindow2
class window(QMainWindow):
def __init__(self):
super(window, self).__init__()
self.setGeometry(50, 50, 300, 300)
self.setWindowTitle('Temperature Control')
self.setWindowIcon(QIcon('adn.png'))
extractAction = QAction('&Quit', self)
extractAction.setShortcut('Ctrl+Q')
extractAction.setStatusTip('leave the app')
extractAction.triggered.connect(self.close_application)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(extractAction)
self.matplWindow = MplWindow()
self.matplWindow1 = MplWindow1()
self.matplWindow2 = MplWindow2()
self.home()
def home(self):
btn = QPushButton('quit', self)
btn.clicked.connect(self.close_application)
btn.resize(btn.sizeHint())
btn.move(200, 260)
button = QPushButton('Temperature',self)
button.clicked.connect(self.opengraph)
button.move(100,50)
button = QPushButton('Filament voltage',self)
button.clicked.connect(self.openfilament)
button.move(100,80)
button = QPushButton('High voltage',self)
button.clicked.connect(self.openhigh)
button.move(100,110)
self.doubleSpinBox = QtWidgets.QDoubleSpinBox()
self.doubleSpinBox.setGeometry(180, 110, 62, 22)
self.show()
def opengraph(self):
self.matplWindow.funAnimation()
def openfilament(self):
self.matplWindow1.funAnimation1()
def openhigh(self):
self.matplWindow2.funAnimation2()
def close_application(self):
choice = QMessageBox.question(self, 'Message',
"Are you sure to quit?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if choice == QMessageBox.Yes:
sys.exit()
else:
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
Gui = window()
sys.exit(app.exec_())
I worked it out - I moved the code to the init function.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QAction, QMessageBox, QDoubleSpinBox, QLabel, QVBoxLayout
from temperature import MplWindow # +++
from filament import MplWindow1
from highvoltage import MplWindow2
class window(QMainWindow):
def __init__(self):
super(window, self).__init__()
self.setGeometry(50, 50, 300, 300)
self.setWindowTitle('Temperature Control')
self.setWindowIcon(QIcon('adn.png'))
extractAction = QAction('&Quit', self)
extractAction.setShortcut('Ctrl+Q')
extractAction.setStatusTip('leave the app')
extractAction.triggered.connect(self.close_application)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(extractAction)
self.matplWindow = MplWindow() # +++
self.matplWindow1 = MplWindow1()
self.matplWindow2 = MplWindow2()
# vBoxLayout = QVBoxLayout()
self.label = QLabel("Set point Temp:", self)
self.label.move(50,150)
self.spinBox = QDoubleSpinBox(self)
self.spinBox.move(70,150)
self.home()
def home(self):
btn = QPushButton('quit', self)
btn.clicked.connect(self.close_application)
btn.resize(btn.sizeHint())
btn.move(200, 260)
button = QPushButton('Temperature',self)
button.clicked.connect(self.opengraph)
button.move(100,50)
button = QPushButton('Filament voltage',self)
button.clicked.connect(self.openfilament)
button.move(100,80)
button = QPushButton('High voltage',self)
button.clicked.connect(self.openhigh)
button.move(100,110)
self.show()
def opengraph(self):
self.matplWindow.funAnimation() # +++
def openfilament(self):
self.matplWindow1.funAnimation1()
def openhigh(self):
self.matplWindow2.funAnimation2()
def close_application(self):
choice = QMessageBox.question(self, 'Message',
"Are you sure to quit?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if choice == QMessageBox.Yes:
sys.exit()
else:
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
Gui = window()
sys.exit(app.exec_())

QWidget cannot display on QMainWindow instance PyQt5

I am learning PyQt5 now and tried to do something little on my own. I have made a very basic custom toolbox, which has just 6 QPushButtons buttons on it, which inherits from QWidget class.
My problem is that I can't display my toolbox on my QMainWidow instance. Let me show you what I did;
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class ToolBox(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn = [QPushButton('B', self) for i in range(6)]
for Btn in btn:
Btn.resize(30, 30)
self.resize(60, 90)
k = 0
for i in range(6):
btn[i].move((i%2)*30, k*30)
k += 1 if i % 2 == 1 else 0
self.show()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(300, 200)
self.statusBar().showMessage('Ready!')
exitAction = QAction(QIcon('idea.png'), 'Exit', self)
exitAction.setStatusTip('Exit application')
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('File')
fileMenu.addAction(exitAction)
t = ToolBox()
t.move(150, 150)
t.show() #With and without this line, it doesn't work.
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
m = MainWindow()
sys.exit(app.exec_())
You just need to position your widget somewhere in the QMainWindow canvas. All you have to do is position it in the MainWindow. Just for an example, I use setCentralWidget() to position your QWidget.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class ToolBox(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn = [QPushButton('B', self) for i in range(6)]
for Btn in btn:
Btn.resize(30, 30)
self.resize(60, 90)
k = 0
for i in range(6):
btn[i].move((i%2)*30, k*30)
k += 1 if i % 2 == 1 else 0
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(300, 200)
self.statusBar().showMessage('Ready!')
exitAction = QAction(QIcon('idea.png'), 'Exit', self)
exitAction.setStatusTip('Exit application')
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('File')
fileMenu.addAction(exitAction)
t = ToolBox()
self.setCentralWidget(t)
if __name__ == '__main__':
app = QApplication(sys.argv)
m = MainWindow()
m.show()
sys.exit(app.exec_())

Resources