How can i save the content of lable entry while click on a switch using pygtk - pygtk

import gtk
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_title("Entry")
self.set_size_request(300, 300)
self.set_position(gtk.WIN_POS_CENTER)
fixed = gtk.Fixed()
self.label = gtk.Label("Entry")
fixed.put(self.label, 40, 40)
entry = gtk.Entry()
fixed.put(entry, 80, 40)
self.button1 = gtk.Button(" OK ")
button1 = gtk.Button(stock=gtk.STOCK_CLOSE)
fixed.put(self.button1, 130, 90)
self.connect("destroy", gtk.main_quit)
self.add(fixed)
self.show_all()
PyApp()
gtk.main()
How to save this label entry as a text file?

If you want to save the text of the GtkEntry after clicking the button, you have to connect to the clicked signal:
import gtk
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_title("Entry")
self.set_size_request(300, 300)
self.set_position(gtk.WIN_POS_CENTER)
fixed = gtk.Fixed()
self.label = gtk.Label("Entry")
fixed.put(self.label, 40, 40)
self.entry = gtk.Entry()
fixed.put(self.entry, 80, 40)
button1 = gtk.Button("OK")
button1.connect('clicked', self.button_clicked)
fixed.put(button1, 130, 90)
self.connect("destroy", gtk.main_quit)
self.add(fixed)
self.show_all()
def button_clicked(self, widget):
with open('entry.txt', 'w') as f:
f.write(self.entry.get_text())
PyApp()
gtk.main()

Related

PyQt5) When I try to open Second window, it is closed without any error messages

I'm trying to open second window on main window.
I made 2 classes for each windows, and run the code. when I click the button on main window, the main window is closed and second windows show. but after 1 seconds the second window is closed and the process ends.
Really I don't know why it does...
from PyQt5 import QtWidgets
import sys
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.resize(400, 300)
# Button
self.button = QtWidgets.QPushButton(self)
self.button.setGeometry(0, 0, 400, 300)
self.button.setText('Open Sub Window')
self.button.setStyleSheet('font-size:40px')
self.button.clicked.connect(self.sub_show)
def sub_show(self):
self.hide()
self.sub_window = SubWindow()
self.sub_window.exec()
self.show()
class SubWindow(QtWidgets.QWidget):
def __init__(self):
super(SubWindow, self).__init__()
self.resize(400, 300)
self.button2 = QtWidgets.QPushButton(self)
self.button2.setGeometry(0, 0, 400, 300)
self.button2.setText('Back to Main window')
self.button2.setStyleSheet('font-size:40px')
self.button2.clicked.connect(self.home)
self.show()
def home(self):
self.close()
if __name__ == "__main__" :
app = QtWidgets.QApplication([])
mw = MainWindow()
mw.show()
sys.exit(app.exec())
You are calling show a few to many times. Also QWidget doesn't have an exec method. You will also want the first window to reappear when you close the second I assume.
I made some changes in the example below. Give it a try:
from PyQt5 import QtWidgets
import sys
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.resize(400, 300)
self.button = QtWidgets.QPushButton(self)
self.button.setGeometry(0, 0, 400, 300)
self.button.setText('Open Sub Window')
self.button.setStyleSheet('font-size:40px')
self.button.clicked.connect(self.sub_show)
def sub_show(self):
self.hide()
self.sub_window = SubWindow()
# connect signal to show again when button2 is pressed
self.sub_window.button2.clicked.connect(self.show)
self.sub_window.show()
class SubWindow(QtWidgets.QWidget):
def __init__(self):
super(SubWindow, self).__init__()
self.resize(400, 300)
self.button2 = QtWidgets.QPushButton(self)
self.button2.setGeometry(0, 0, 400, 300)
self.button2.setText('Back to Main window')
self.button2.setStyleSheet('font-size:40px')
self.button2.clicked.connect(self.close)
if __name__ == "__main__" :
app = QtWidgets.QApplication([])
mw = MainWindow()
mw.show()
sys.exit(app.exec())

cannot be associated with QComboBox

button of class Main don't connect with class Qcombobox of Signals
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtWidgets import *
import sys
from PyQt5 import QtGui
class Signals(QWidget):
asignal = pyqtSignal(str)
def __init__(self):
super(Signals, self).__init__()
self.setGeometry(300, 250, 400, 300)
self.ii()
self.show()
def ii(self):
vbox = QVBoxLayout()
self.combo = QComboBox()
self.combo.addItem("Python")
self.combo.addItem("Java")
self.combo.addItem("C++")
self.combo.addItem("C#")
self.combo.addItem("Ruby")
self.buttom = QPushButton("Click")
self.buttom.clicked.connect(self.windown2)
vbox.addWidget(self.combo)
vbox.addWidget(self.buttom)
self.setLayout(vbox)
def do_something(self):
self.asignal.emit(self.combo.currentText())
def windown2(self):
self.ggpp = Main()
self.ggpp.show()
class Main(QWidget):
def __init__(self):
super(Main, self).__init__()
self.setGeometry(500,150, 600, 300)
vbox1 = QVBoxLayout()
self.buttom1 = QPushButton("Click")
self.buttom1.clicked.connect(self.coso1)
vbox1.addWidget(self.buttom1)
self.setLayout(vbox1)
def coso1(self):
s = Signals()
s.asignal.connect(lambda sig: print("self.combo.currentText()>>>>>" + sig))
s.do_something()
if __name__ == '__main__':
app = QApplication(sys.argv)
nals = Signals()
nals.show()
sys.exit(app.exec())
What you see happens because you're not using the existing instance of Signals, but you're creating a new one each time the button is clicked.
In your case, you could add a reference to the instance as an argument when you create the new window, so that you can correctly connect to its signal.
class Signals(QWidget):
# ...
def windown2(self):
self.ggpp = Main(self)
self.ggpp.show()
class Main(QWidget):
def __init__(self, signals):
super(Main, self).__init__()
self.signals = signals
self.signals.asignal.connect(self.coso1)
self.setGeometry(500,150, 600, 300)
vbox1 = QVBoxLayout()
self.buttom1 = QPushButton("Click")
self.buttom1.clicked.connect(self.signals.do_something)
vbox1.addWidget(self.buttom1)
self.setLayout(vbox1)
def coso1(self, sig):
print("self.combo.currentText()>>>>>" + sig)

Pass other functions returned value to QtableView in PYQt5

I am stuck on the last bit of the code to create a small search engine. So far I have been able to let users do some actions as select a folder where the files to search are stored, create an index, search for keyword and then export excerpt of the text around the keyword to a txt file. This is the layout
And this is the code I have used:
from PyQt5 import QtCore, QtGui, QtWidgets, QtWidgets
from PyQt5.QtWidgets import QHeaderView
import os, os.path
import glob
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
import pdftotext
from whoosh import index
from whoosh.fields import Schema, TEXT, ID, STORED
from whoosh.analysis import RegexTokenizer
from whoosh.analysis import StopFilter
from whoosh import scoring
from whoosh.index import open_dir
from whoosh import qparser
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1126, 879)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 30, 100, 30))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(180, 30, 120, 30))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(620, 30, 80, 30))
self.pushButton_3.setObjectName("pushButton_3")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(380, 60, 191, 21))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(40, 90, 50, 21))
self.lineEdit_2.setObjectName("lineEdit_2")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(380, 30, 50, 35))
font = QtGui.QFont()
font.setPointSize(10)
self.label.setFont(font)
self.label.setObjectName("label")
self.label2 = QtWidgets.QLabel(self.centralwidget)
self.label2.setGeometry(QtCore.QRect(40, 70, 150, 16))
font = QtGui.QFont()
font.setPointSize(10)
self.label2.setFont(font)
self.label2.setObjectName("label")
self.tableView = QtWidgets.QTableView(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(0, 120, 1121, 721))
self.tableView.setObjectName("tableView")
self.horizontal_header = self.tableView.horizontalHeader()
self.vertical_header = self.tableView.verticalHeader()
self.horizontal_header.setSectionResizeMode(
QHeaderView.ResizeToContents
)
self.vertical_header.setSectionResizeMode(
QHeaderView.ResizeToContents
)
self.horizontal_header.setStretchLastSection(True)
self.tableView.showGrid()
self.tableView.wordWrap()
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1126, 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)
self.pushButton.clicked.connect(self.open_directory)
self.pushButton_2.clicked.connect(self.createindex)
self.pushButton_3.clicked.connect(self.export)
self.lineEdit.returnPressed.connect(self.search)
def open_directory(self):
self.dialog = QtWidgets.QFileDialog()
self.folder_path = self.dialog.getExistingDirectory(None, "Select Folder")
return self.folder_path
def createindex(self):
os.chdir(self.folder_path)
self.mypdfiles = glob.glob("*.pdf")
#creation of folder for splitted files
MYDIR = ("Splitted")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
# save split downloaded file and save into new folder
for self.file in self.mypdfiles:
self.fname = os.path.splitext(os.path.basename(self.file))[0]
self.pdf = PdfFileReader(self.file)
for self.page in range(self.pdf.getNumPages()):
self.pdfwrite = PdfFileWriter()
self.pdfwrite.addPage(self.pdf.getPage(self.page))
self.outputfilename = '{}_page_{}.pdf'.format(self.fname, self.page+1)
with open(os.path.join("./Splitted", self.outputfilename), 'wb') as out:
self.pdfwrite.write(out)
print('Created: {}'.format(self.outputfilename))
#set working directory
os.chdir(self.folder_path + "/Splitted")
self.spltittedfiles = glob.glob("*.pdf")
MYDIR = ("Txt")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
# Load your PDF
for self.file in self.spltittedfiles:
with open(self.file, "rb") as f:
self.pdf = pdftotext.PDF(f)
#creation of folder for splitted files
# Save all text to a txt file.
with open(os.path.join("./TXT", os.path.splitext(os.path.basename(self.file))[0] + ".txt") , 'w', encoding = 'utf-8') as f:
f.write("\n\n".join(self.pdf))
f.close()
os.chdir(self.folder_path)
MYDIR = ("indexdir")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
self.my_analyzer = RegexTokenizer()| StopFilter(lang = "en")
self.schema = Schema(title=TEXT(stored=True),path=ID(stored=True),
content=TEXT(analyzer = self.my_analyzer),
textdata=TEXT(stored=True))
# set an index writer to add document as per schema
self.ix = index.create_in("indexdir",self.schema)
self.writer = self.ix.writer()
self.filepaths = [os.path.join("./Splitted/Txt",i) for i in os.listdir("./Splitted/Txt")]
for path in self.filepaths:
self.fp = open(path, "r", encoding='utf-8')
self.text = self.fp.read()
self.writer.add_document(title = os.path.splitext(os.path.basename(path))[0] , path=path, content=self.text,textdata=self.text)
self.fp.close()
self.writer.commit()
def search(self):
os.chdir(self.folder_path)
self.ix = open_dir("indexdir")
MYDIR = ("Results")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
self.text = self.lineEdit.text()
self.query_str = self.text
self.query = qparser.QueryParser("textdata", schema = self.ix.schema)
self.q = self.query.parse(self.query_str)
self.topN = self.lineEdit_2.text()
if self.lineEdit_2.text() == "":
self.topN = 1000
else:
self.topN = int(self.lineEdit_2.text())
with self.ix.searcher(weighting=scoring.Frequency) as searcher:
self.results = searcher.search(self.q, terms=True, limit=self.topN)
for self.i in range(self.topN):
print(self.results[self.i]['title'], self.results[self.i]['textdata'])
def export(self):
with self.ix.searcher(weighting=scoring.Frequency) as searcher:
self.results = searcher.search(self.q, terms=True, limit= None)
for self.i in range(self.topN):
with open(os.path.join(self.folder_path, self.text + ".txt"), 'a') as f:
print(self.results[self.i]['title'], self.results[self.i]['textdata'], file=f)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Search Text"))
self.pushButton.setText(_translate("MainWindow", "Select Folder"))
self.pushButton_2.setText(_translate("MainWindow", "Create Database"))
self.pushButton_3.setText(_translate("MainWindow", "Export"))
self.label.setText(_translate("MainWindow", "Search"))
self.label2.setText(_translate("MainWindow", "Top Results"))
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_())
What I want to do now is to show the results also in the table. I have been trying to understand how to "send" the returned value of the search function to the table and how to show it. It should have two columns: File_Page and Content and as many rows as top results selected. Each row should then show the file with hit and the text of interest like this:
So far I have been able to just set to parameter of the table, but not much more.
Is there any mean to let the table how the results without pushing any other button? As I have so far understood, is it possible to trigger the same function from different places of the code but I did not find the opposite, that is to activate two functions with just one signal
I have found lots of examples but none suits the objective. I am still learning how to use Python and I have never used C++.
Use other signal to trigger layoutChanged. i.e. QLineEdit's signal.
Mind me if I understood your question wrong, assuming you want to update search results as soon as you type something in Search field.
In that case, here's neat working example demonstrating immediate searching on 5 entries:
from PySide2.QtWidgets import QWidget, QApplication, QPushButton, QVBoxLayout, QLineEdit
from PySide2.QtCore import QAbstractTableModel, QModelIndex, Qt, QObject
from PySide2.QtWidgets import QTableView
import sys
class Table(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def data(self, index: QModelIndex, role: int = ...):
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def rowCount(self, parent: QModelIndex = ...) -> int:
return len(self._data)
def columnCount(self, parent: QModelIndex = ...) -> int:
return len(self._data[0])
def overWriteData(self, new_list):
self._data = new_list
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.table = QTableView()
self.line = QLineEdit()
self.layout = QVBoxLayout()
self.layout.addWidget(self.table)
self.layout.addWidget(self.line)
self.data = [('stack overflow', 'some_fancy_data'),
('stack overflow', 'some_fancy_data'),
('stack underflow', 'some_fancy_data'),
('Server Fault', 'some_fancy_data'),
('Ask Ubuntu', 'some_fancy_data')]
self.model = Table(self.data)
self.table.setModel(self.model)
self.setLayout(self.layout)
self.line.textChanged.connect(self.update)
def update(self):
filtered = [i for i in self.data if self.line.text() in i[0]]
if filtered:
self.model.overWriteData(filtered)
self.model.layoutChanged.emit()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
I have shifted to Qtable Widget, created a new function (datatable) and called it from setup UI.
This is the new setupUI:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1126, 879)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 30, 100, 30))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(180, 30, 120, 30))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(620, 30, 80, 30))
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(180, 80, 80, 30))
self.pushButton_4.setObjectName("pushButton_4")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(380, 60, 191, 21))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(40, 90, 50, 21))
self.lineEdit_2.setObjectName("lineEdit_2")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(380, 30, 50, 35))
font = QtGui.QFont()
font.setPointSize(10)
self.label.setFont(font)
self.label.setObjectName("label")
self.label2 = QtWidgets.QLabel(self.centralwidget)
self.label2.setGeometry(QtCore.QRect(40, 70, 150, 16))
font = QtGui.QFont()
font.setPointSize(10)
self.label2.setFont(font)
self.label2.setObjectName("label")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(0, 120, 1121, 721))
self.tableWidget.setObjectName("tableWidget")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1126, 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)
self.pushButton.clicked.connect(self.open_directory)
self.pushButton_2.clicked.connect(self.createindex)
self.pushButton_3.clicked.connect(self.export)
self.pushButton_4.clicked.connect(self.OCR)
self.lineEdit.returnPressed.connect(self.search)
self.lineEdit.returnPressed.connect(self.datatable)
And this is the function that takes the data returned from another function within the class.
numrows = len(self.data)
numcols = len(self.data[0])
self.tableWidget.setColumnCount(numcols)
self.tableWidget.setRowCount(numrows)
self.tableWidget.setHorizontalHeaderLabels((list(self.data[0].keys())))
self.tableWidget.resizeColumnsToContents()
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
for row in range(numrows):
for column in range(numcols):
item = (list(self.data[row].values())[column])
self.tableWidget.setItem(row, column, QTableWidgetItem(item)) ```

CheckBox to a variables. PyQt5

How can I link checkbox to the variable under pushbutton?
The checkbox will return either 0 or 1 for the variable F which will affect the calculation output.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 394)
self.spinBox = QtWidgets.QSpinBox(Dialog)
self.spinBox.setGeometry(QtCore.QRect(60, 120, 48, 24))
self.spinBox.setObjectName("spinBox")
self.spinBox.setRange(1, 200)
self.spinBox.setValue(0)
self.checkBox = QtWidgets.QCheckBox(Dialog)
self.checkBox.setGeometry(QtCore.QRect(60, 160, 87, 20))
self.checkBox.setObjectName("checkBox")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(50, 190, 113, 32))
self.pushButton.setObjectName("pushButton")
self.lcdNumber = QtWidgets.QLCDNumber(Dialog)
self.lcdNumber.setGeometry(QtCore.QRect(90, 230, 113, 32))
self.lcdNumber.setObjectName("lcdNumber")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.pushButton.clicked.connect(self.pushButton_handler)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.checkBox.setText(_translate("Dialog", "CheckBox"))
self.pushButton.setText(_translate("Dialog", "PushButton"))
def pushButton_handler(self, state):
A1 = self.spinBox.value()
F= ??? #F to be equal to 0 if check box checked or 1 if
check box unchecked.
i=A1*F
app.processEvents()'
self.lcdNumber.display(i)
QCheckBox::stateChanged(int state)
This signal is emitted whenever the checkbox's state changes, i.e., whenever the user checks or unchecks it.
state contains the checkbox's new Qt::CheckState.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 394)
self.spinBox = QtWidgets.QSpinBox(Dialog)
self.spinBox.setGeometry(QtCore.QRect(60, 120, 48, 24))
self.spinBox.setObjectName("spinBox")
self.spinBox.setRange(1, 200)
self.spinBox.setValue(0)
self.checkBox = QtWidgets.QCheckBox(Dialog)
self.checkBox.setGeometry(QtCore.QRect(60, 160, 87, 20))
self.checkBox.setObjectName("checkBox")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(50, 190, 113, 32))
self.pushButton.setObjectName("pushButton")
self.lcdNumber = QtWidgets.QLCDNumber(Dialog)
self.lcdNumber.setGeometry(QtCore.QRect(90, 230, 113, 32))
self.lcdNumber.setObjectName("lcdNumber")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.pushButton.clicked.connect(self.pushButton_handler)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.checkBox.setText(_translate("Dialog", "CheckBox"))
self.pushButton.setText(_translate("Dialog", "PushButton"))
class Example(QtWidgets.QDialog, Ui_Dialog): # +
def __init__(self):
super(Example, self).__init__()
self.setupUi(self)
self.checkBox.stateChanged.connect(self.selectCheckBox) # +++
self.F = 1 # +
def pushButton_handler(self, state):
A1 = self.spinBox.value()
# F = #??? #F to be equal to 0 if check box checked or 1 if check box unchecked.
i = A1 * self.F
# ? app.processEvents()'
self.lcdNumber.display(i)
def selectCheckBox(self, toggle): # +++
if toggle == QtCore.Qt.Checked:
self.F = 0
else:
self.F = 1
if __name__ == "__main__":
app = QApplication(sys.argv)
default_font = QFont()
default_font.setPointSize(15)
app.setFont(default_font)
w = Example()
w.resize(220, 300)
w.show()
sys.exit(app.exec_())

How to compute a value without clicking a button in pyqt5?

How can I compute the net price (Price * (1 - discount)) automatically whenever I enter data? I can make it work on a button press but I'd like to do it whenever data is entered.
See image below.
Thank you in advance!
At first it seems like you are using QLineEdit for the input. Because you want to input integers, I would recommend using the QSpinBox or QDoubleSpinBox, which are made for the input of integers.
I built up such a GUI like you have with QtCreator and converted it with pyuic5 -x gui.ui -o gui.py on my Raspberry Pi to Python.
You simply need to connect the value change of the SpinBox with a function that gives out the net price. For doing this, see the code below:
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 415)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(30, 40, 201, 81))
font = QtGui.QFont()
font.setPointSize(26)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(30, 140, 201, 81))
font = QtGui.QFont()
font.setPointSize(26)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(30, 260, 201, 81))
font = QtGui.QFont()
font.setPointSize(26)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_netprice = QtWidgets.QLabel(self.centralwidget)
self.label_netprice.setGeometry(QtCore.QRect(260, 282, 421, 41))
self.label_netprice.setStyleSheet("background-color: rgb(255, 255, 255);")
self.label_netprice.setText("")
self.label_netprice.setObjectName("label_netprice")
self.doubleSpinBox_price = QtWidgets.QDoubleSpinBox(self.centralwidget)
self.doubleSpinBox_price.setGeometry(QtCore.QRect(260, 60, 421, 41))
self.doubleSpinBox_price.setObjectName("doubleSpinBox_price")
####################################
# Link to function when value changes
self.doubleSpinBox_price.valueChanged.connect(self.Refresh)
####################################
self.doubleSpinBox_discount = QtWidgets.QDoubleSpinBox(self.centralwidget)
self.doubleSpinBox_discount.setGeometry(QtCore.QRect(260, 160, 421, 41))
self.doubleSpinBox_discount.setObjectName("doubleSpinBox_discount")
####################################
# Link to function when value changes
self.doubleSpinBox_discount.valueChanged.connect(self.Refresh)
####################################
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 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.label.setText(_translate("MainWindow", "Price:"))
self.label_2.setText(_translate("MainWindow", "Discount:"))
self.label_3.setText(_translate("MainWindow", "Net Price:"))
##########################################
# Function for refreshing the output label
def Refresh(self):
price = self.doubleSpinBox_price.value()
discount = self.doubleSpinBox_discount.value()
netprice = price * (1 - discount)
self.label_netprice.setText(str(netprice))
##########################################
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_())
In my code the SpinBoxes are limited at 99 but you can set this to a higher value.
Just a hint: People are more likely to help you, if you give them a short but relatable code example to work with and they don't have to build their own GUI.
I hope this helps. If you find it useful, please mark it as correct.
Best wishes,
RaspiManu