apply clicked on table header in pyqt - python-3.x

this is my caller file which helps me generate ui of table where i can write data.the problem here is i want to sort the data when i click on the header of the table according to that column. i can sort the data easily as i have a backend data(not present in this code as it will not be needed here) but i am unable to apply click function on headers of the table. i want to apply clicked.connect on different table header. thanks in advance :)
from table import *
from PyQt4 import QtGui # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MainWindow(QMainWindow,Ui_MainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
this is my table.py which has ui code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'table.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.tableWidget = QtGui.QTableWidget(self.centralwidget)
self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(3)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 31))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
item = self.tableWidget.verticalHeaderItem(0)
item.setText(_translate("MainWindow", "New Row", None))
item = self.tableWidget.verticalHeaderItem(1)
item.setText(_translate("MainWindow", "New Row", None))
item = self.tableWidget.verticalHeaderItem(2)
item.setText(_translate("MainWindow", "New Row", None))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Name", None))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "class", None))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "marks", None))
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_())

self.connect(self.tableWidget.horizontalHeader(),SIGNAL("sectionClicked(int)"),self.fun)
def fun(self,i):
print("index clicked is"+i)

Related

How to send a signal from a QDialog to a QMainWindow class

I have made a UI which includes a mainwindow and a button that opens a dialog window. I want to send the current text changed signal from a line edit in the dialog window to the Mainwindow class as a variable. An example of the code I am making is below:
from PyQt5 import QtCore, QtGui, QtWidgets
from selenium import webdriver
import time
import threading
from bs4 import BeautifulSoup as soup
import requests
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(388, 179)
self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
self.lineEdit_2.setGeometry(QtCore.QRect(100, 100, 271, 21))
font = QtGui.QFont()
font.setFamily("Yu Gothic")
self.lineEdit_2.setFont(font)
self.lineEdit_2.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);")
self.lineEdit_2.setObjectName("lineEdit_2")
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
# self.pushButton.pressed.connect(self.textEdit.clear)
# self.pushButton.pressed.connect(self.sejd)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.keyworddict = {}
self.count = {}
MainWindow.setObjectName("MainWindow")
MainWindow.resize(803, 538)
MainWindow.setMinimumSize(QtCore.QSize(0, 0))
MainWindow.setMaximumSize(QtCore.QSize(10000, 10000))
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.pushButton = QtWidgets.QPushButton(self.centralWidget)
self.pushButton.setGeometry(QtCore.QRect(180, 210, 75, 23))
font = QtGui.QFont()
font.setFamily("Yu Gothic")
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralWidget)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pushButton.pressed.connect(self.on_Button_clicked)
def on_Button_clicked(self):
dialog = QtWidgets.QDialog()
dialog.ui = Ui_Dialog()
dialog.ui.setupUi(dialog)
dialog.setWindowTitle("Login")
dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
dialog.exec_()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.setWindowTitle("ui")
w.show()
sys.exit(app.exec_())
All help appreciated. I would preferably like an example using the code above.
There are at least two simple ways to do this. You can either connect a signal when the dialog is created, or just retrieve the text after the dialog closes:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
...
def dialogTextChanged(self, text):
print(text)
def on_Button_clicked(self):
dialog = QtWidgets.QDialog()
dialog.ui = Ui_Dialog()
dialog.ui.setupUi(dialog)
# connect signal to slot
dialog.ui.lineEdit_2.textChanged.connect(self.dialogTextChanged)
dialog.setWindowTitle("Login")
# this is not needed
# dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
dialog.exec_()
# or retrieve text after dialog closes
print(dialog.ui.lineEdit_2.text())
dialog.deleteLater()
If this is a login dialog, you should probably have an accept button which is connected to the dialog's accept() slot. Then you can check the exit status of the dialog like this:
if dialog.exec_() == QtWidgets.QDialog.Accepted:
text = dialog.ui.lineEdit_2.text()
# do sothing with text ...
dialog.deleteLater()

Copy/Save PyQt5 Listbox items in a text file python

After several clicks of Add button, it adds items to the listbox. I wish to save all the items from the listbox to a textfile with the save button.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.listView = QtWidgets.QListWidget(Dialog)
self.listView.setGeometry(QtCore.QRect(120, 40, 256, 192))
self.listView.setObjectName("listView")
self.AddButton = QtWidgets.QPushButton(Dialog)
self.AddButton.setGeometry(QtCore.QRect(20, 80, 75, 41))
self.AddButton.setObjectName("AddButton")
self.SaveButton = QtWidgets.QPushButton(Dialog)
self.SaveButton.setGeometry(QtCore.QRect(20, 140, 75, 41))
self.SaveButton.setObjectName("SaveButton")
self.AddButton.clicked.connect(self.ADD)
self.SaveButton.clicked.connect(self.SAVE)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.AddButton.setText(_translate("Dialog", "Add to List"))
self.SaveButton.setText(_translate("Dialog", "Save"))
def ADD(self):
self.listView.addItem("SAMPLE STRING")
def SAVE(self):
s = open('textfile.txt','a')
for items in self.listView():
s.write(item)
s.close()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
but the code under the def SAVE(self): doesn't work.
self.listView is an object and not callable by self.listView(). I suppose you want to save the items's text. You can get it and all other data of the items from the listViews model:
def SAVE(self):
with open('textfile.txt','a') as s:
for i in range(self.listView.model().rowCount()):
text = self.listView.model().data(self.listView.model().index(i))
# print(i, text)
s.write(text)
or ask for the text() of the items:
def SAVE(self):
with open('textfile.txt','a') as s:
for i in range(self.listView.model().rowCount()):
text = self.listView.item(i).text()
# print(i, text)
s.write(text)

PYQT4 not able to write into excelwriter

I have a gui I created in pyqt4 that has a function to call a module that is supposed to write into an excel sheet using pandas excelwriter. For some reason, it creates the worksheet but does not write anything into it. It just crashes my qui without any errors..when I run it in debug mode, it apparently goes through without any issues. I have been debugging this for the past few days and now point the issue between pyqt and excelwriter.Is there a known issue that pyqt does not like pandas excelwriter?
from PyQt4 import QtCore,QtGui
import sys
from MAIN_GUI import *
if __name__=="__main__":
app = Qt.Gui.QApplication(sys.argv)
class MAIN_GUI(QtGui.QMainWindow):
def __init__self:
super(MAIN_GUI, self.__init__:
self.uiM=Ui_MainWindow
self.uiM.setupUi(self)
self.connect(self.uiM.updateALL_Button,QtCore.SIGNAL('clicked()'),self.updateALLEXCEL)
def updateALLEXCEL(self):
import excel_dummy
main_gui = MAIN_GUI()
main_gui.show()
main_gui.raise_()
sys.exit(app.exec_())
---excel_dummy.py---
import pandas as pd
from pandas import ExcelWriter
def excelify():
with ExcelWriter('/home/Desktop/Excelified/final.xlsx', engine='xlsxwriter') as writer:
workbook=writer.book
worksheet=workbook.add_worksheet()
worksheet.write(2,2,'just write something')
writer.save()
excelify()
---MAIN_GUI.py---
from PyQt4 import QtCore,QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.unicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(320,201)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.updateALL_Button = QtGui.QPushButton(self.centralwidget)
self.updateALL_Button.setGeometry(QtCore.QRect(40,110,161,27))
self.updateALL_Button.setFocusPolicy(QtCore.Qt.NoFocus)
self.updateAll_Button.setObjectName(_fromUtf8("Options_updateALL_Button"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 320, 24))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self,MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.updateALL_Button.setText(_translate("MainWindow", "updateALL", None))
The code below works for me. That is, after I click the updateALL button, it prints this:
file size: 5259 "/tmp/final.xlsx"
and viewing the resulting file shows this:
Note that I had to fix quite a lot of bugs to get your example to work. So make sure you use all the files below when you test it:
main.py:
import sys
from MAIN_GUI import *
from PyQt4 import QtGui, QtCore
if __name__=="__main__":
app = QtGui.QApplication(sys.argv)
class MAIN_GUI(QtGui.QMainWindow):
def __init__(self):
super(MAIN_GUI, self).__init__()
self.uiM = Ui_MainWindow()
self.uiM.setupUi(self)
self.connect(self.uiM.updateALL_Button,QtCore.SIGNAL('clicked()'),self.updateALLEXCEL)
def updateALLEXCEL(self):
try:
import excel_dummy
except:
from traceback import format_exception
msg = ''.join(format_exception(*sys.exc_info()))
mb = QtGui.QMessageBox()
mb.setWindowTitle('Error')
mb.setText('Click Show Details to get the Traceback')
mb.setDetailedText(msg)
mb.exec_()
main_gui = MAIN_GUI()
main_gui.show()
main_gui.raise_()
sys.exit(app.exec_())
excel_dummy.py:
import os, pandas as pd
from pandas import ExcelWriter
def excelify():
path = '/tmp/final.xlsx'
with ExcelWriter(path, engine='xlsxwriter') as writer:
workbook = writer.book
worksheet = workbook.add_worksheet()
worksheet.write(2, 2, 'just write something')
writer.save()
print('file size: %s "%s"' % (os.stat(path).st_size, path))
excelify()
MAIN_GUI.py:
from PyQt4 import QtCore,QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.unicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(320,201)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.updateALL_Button = QtGui.QPushButton(self.centralwidget)
self.updateALL_Button.setGeometry(QtCore.QRect(40,110,161,27))
self.updateALL_Button.setFocusPolicy(QtCore.Qt.NoFocus)
self.updateALL_Button.setObjectName(_fromUtf8("Options_updateALL_Button"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 320, 24))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self,MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.updateALL_Button.setText(_translate("MainWindow", "updateALL", None))
Your writer.save() statement is outside the with ExcelWriter(...) as writer: block. Try running it with the statement inside the block.
with ExcelWriter('/home/Desktop/Excelified/final.xlsx', engine='xlsxwriter') as writer:
workbook=writer.book
worksheet=workbook.add_worksheet()
worksheet.write(2,2,'just write something')
writer.save()

pyQt: how to pass information between windows

I have two windows, both containing one button and one lineEdit. I want to create a "ping - pong" communication between both windows. At first, I write something in the lineEdit of the first window, press the button, and a second window appears.
I want the message written in the lineEdit of the first window to appear to the lineEdit of the second window. (and vice versa).
this is the code for the creation of the First window, derived from Qt Designer:
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(331, 249)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.PushButtonFirst = QtGui.QPushButton(self.centralwidget)
self.PushButtonFirst.setGeometry(QtCore.QRect(140, 180, 131, 27))
self.PushButtonFirst.setObjectName(_fromUtf8("PushButtonFirst"))
self.lineEditFirst = QtGui.QLineEdit(self.centralwidget)
self.lineEditFirst.setGeometry(QtCore.QRect(130, 50, 113, 27))
self.lineEditFirst.setObjectName(_fromUtf8("lineEditFirst"))
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.actionNew = QtGui.QAction(MainWindow)
self.actionNew.setObjectName(_fromUtf8("actionNew"))
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
self.actionClose = QtGui.QAction(MainWindow)
self.actionClose.setObjectName(_fromUtf8("actionClose"))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.PushButtonFirst.setText(_translate("MainWindow", "PushButtonFirst", None))
self.actionNew.setText(_translate("MainWindow", "New", None))
self.actionOpen.setText(_translate("MainWindow", "Open", None))
self.actionClose.setText(_translate("MainWindow", "Close", None))
this is the code for the creation of the Second window, derived from Qt Designer:
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(329, 260)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.PushButtonSecond = QtGui.QPushButton(self.centralwidget)
self.PushButtonSecond.setGeometry(QtCore.QRect(130, 190, 121, 27))
self.PushButtonSecond.setObjectName(_fromUtf8("PushButtonSecond"))
self.lineEditSecond = QtGui.QLineEdit(self.centralwidget)
self.lineEditSecond.setGeometry(QtCore.QRect(120, 80, 113, 27))
self.lineEditSecond.setObjectName(_fromUtf8("lineEditSecond"))
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.PushButtonSecond.setText(_translate("MainWindow", "PushButtonSecond", None))
and this is the main code:
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
import design1, design2
class Second(QtGui.QMainWindow, design2.Ui_MainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.setupUi(self)
class First(QtGui.QMainWindow, design1.Ui_MainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setupUi(self)
self.PushButtonFirst.clicked.connect(self.on_PushButtonFirst_clicked)
self.dialog = Second(self)
def on_PushButtonFirst_clicked(self):
self.my_text_First = self.lineEditFirst.text()
pass_text(self)
self.dialog.show()
def pass_text(obj):
obj.lineEditSecond.setText('OK')
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I receive this message:
'First' object has no attribute 'lineEditSecond'
which is quite logical, since pass_text() is a function of the First class. Anyway, I can't think any workaround.
Any thought would be appreciated.
You pretty much got it working. When I get an attribute error and can't figure it out, I use print type(object) and print dir(object) as a first-line of debugging to double check that the object is what I think it is, and to inspect all of its attributes.
The problem is you were not passing the second dialog whose text you wanted to set. I fixed this, and made a few other minor changes to your First class:
class First(QtGui.QMainWindow, design1.Ui_MainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setupUi(self)
self.PushButtonFirst.clicked.connect(self.on_PushButtonFirst_clicked)
self.partnerDialog = Second(self)
def on_PushButtonFirst_clicked(self):
self.partnerDialog.lineEditSecond.setText(self.lineEditFirst.text())
self.partnerDialog.show()
class Second(QtGui.QMainWindow, design2.Ui_MainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.setupUi(self)
self.PushButtonSecond.clicked.connect(self.on_PushButtonSecond_clicked)
self.partnerDialog = parent #otherwise, recursion
def on_PushButtonSecond_clicked(self):
self.partnerDialog.lineEditFirst.setText(self.lineEditSecond.text())
self.partnerDialog.show()
I have tightened it up to keep things more encapsulated and easier for debugging/thinking/posting here.

How to trigger text in a widget using PyQt

This may look like a long question but it is actually really short, I've just decided to copy all the working code here.
I have a main window and a Tip of the Day widget.
I generated both the UI using the PyQt Designer.
I can open the Tip of the Day widget from the main window menu but I'm not able to make the buttons work:
I'd like to replace some text in the Tip of the Day widget when the previous and the next buttons are clicked.
I have the following main window called MainWindow.py:
from PyQt4 import QtCore, QtGui
from MainWindowUi import Ui_MainWindow
from FormUi import Ui_Form
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# Main window user interface elements
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# Main window signal/slot connections
self.setupConnections()
#QtCore.pyqtSlot()
def showTipDialog(self):
'''Trig dialog Tip'''
form = QtGui.QDialog()
form.ui = Ui_Form()
form.ui.setupUi(form)
form.exec_()
def setupConnections(self):
'''Signal and Slot Support'''
self.connect(self.ui.actionTip_of_the_Day, QtCore.SIGNAL('triggered()'), self.showTipDialog)
I have the following main.py:
import sys
from PyQt4 import QtGui
from MainWindow import MainWindow
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
I have the following main window UI called MainWindowUi.py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created: Thu May 21 20:26:31 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuHelp = QtGui.QMenu(self.menubar)
self.menuHelp.setObjectName(_fromUtf8("menuHelp"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.actionTip_of_the_Day = QtGui.QAction(MainWindow)
self.actionTip_of_the_Day.setObjectName(_fromUtf8("actionTip_of_the_Day"))
self.menuHelp.addAction(self.actionTip_of_the_Day)
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.menuHelp.setTitle(_translate("MainWindow", "Help", None))
self.actionTip_of_the_Day.setText(_translate("MainWindow", "Tip of the Day", None))
I have the following widget form UI FormUi.py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Form.ui'
#
# Created: Thu May 21 23:57:41 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(418, 249)
self.verticalLayout = QtGui.QVBoxLayout(Form)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.lineEdit = QtGui.QLineEdit(Form)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.verticalLayout.addWidget(self.lineEdit)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.pushButton_previous = QtGui.QPushButton(Form)
self.pushButton_previous.setObjectName(_fromUtf8("pushButton_previous"))
self.horizontalLayout.addWidget(self.pushButton_previous)
self.pushButton_next = QtGui.QPushButton(Form)
self.pushButton_next.setObjectName(_fromUtf8("pushButton_next"))
self.horizontalLayout.addWidget(self.pushButton_next)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.lineEdit.setText(_translate("Form", "Here a tip I'd like to replace by pressing the buttons below.", None))
self.pushButton_previous.setText(_translate("Form", "Previous Tip", None))
self.pushButton_next.setText(_translate("Form", "Next Tip", None))
Please run main.py in order to open the main window and click Help > Tip of the Day to open the widget.
Thanks for the attention.
You have a MainWindow class (which you instantiate from the main() function) which you have written to instantiate your Ui_MainWindow class (thus creating the GUI) and link a button to a method which pops up the dialog.
Now just apply the same logic to the dialog. Instead of creating a QDialog() directly in showTipDialog, instead instantiate a subclass QDialog. Write the subclass in a similar way to what you've done for MainWindow. Connect the clicked signals from the prev/next pushbuttons to appropriate methods (which you write) that change the contents of the QLineEdit.

Resources