How to trigger text in a widget using PyQt - pyqt4

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.

Related

Python PyQt5 Terminal Command execution problem on a button click

I'm trying to create an application, that can execute an embedded Terminal command when ever the button is clicked. The actual problem occurs when i click the button and nothing happens.
I have two scripts one has a terminal widget and the other has the main GUI. Any Help, would be highly appreciated.
That's first Script
import sys
from PyQt5 import QtCore, QtWidgets
class EmbTerminal(QtWidgets.QWidget):
def __init__(self, parent=None):
super(EmbTerminal, self).__init__(parent)
self._process = []
self.start_process('urxvt',['-embed', str(int(self.winId())),"-e","tmux"])
def start_process(self,prog,options):
child = QtCore.QProcess(self)
self._process.append(child)
child.start(prog,options)
def run_command(self, command = "ls" ):
program = "tmux"
options = []
options.extend(["send-keys"])
options.extend([command])
options.extend(["Enter"])
self.start_process(program, options)
That's Second Script
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(745, 496)
self.tabWidget = QtWidgets.QTabWidget(Dialog)
self.tabWidget.setGeometry(QtCore.QRect(100, 190, 561, 261))
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.tabWidget.addTab(EmbTerminal(), "Terminal")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.tabWidget.addTab(self.tab_2, "")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(280, 70, 211, 71))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.pushButton.clicked.connect(lambda: EmbTerminal.run_command(EmbTerminal(), "ls"))
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Dialog", "Tab 1"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Dialog", "Tab 2"))
self.pushButton.setText(_translate("Dialog", "ls"))
from terminal5 import EmbTerminal
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_())
You should consider the following:
You should not modify the code generated by Qt Designer (unless you understand its logic)
Do not implement the logic in the class generated by Qt Designer, it is advisable to create a new class that inherits from the appropriate widget and use the other class to fill it.
In your case the problem is that the EmbTerminal() object in lambda: EmbTerminal.run_command(EmbTerminal(), "ls") only exists while the lambda is running, but the lambda runs for a very short time causing the command not to be sent causing the error.
Considering the above, the solution is:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(745, 496)
self.tabWidget = QtWidgets.QTabWidget(Dialog)
self.tabWidget.setGeometry(QtCore.QRect(100, 190, 561, 261))
self.tabWidget.setObjectName("tabWidget")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(280, 70, 211, 71))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.pushButton.setText(_translate("Dialog", "ls"))
from terminal5 import EmbTerminal
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.terminal = EmbTerminal()
self.tabWidget.addTab(self.terminal, "Terminal")
self.pushButton.clicked.connect(self.on_clicked)
#QtCore.pyqtSlot()
def on_clicked(self):
self.terminal.run_command("ls")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
On the other hand if you are only going to send commands then it is not necessary to store the QProcess, instead use QProcess: startDetached and make run_command a classmethod:
class EmbTerminal(QtWidgets.QWidget):
# ...
#staticmethod
def run_command(command = "ls" ):
program = "tmux"
options = []
options.extend(["send-keys"])
options.extend([command])
options.extend(["Enter"])
QtCore.QProcess.startDetached(program, options)

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()

apply clicked on table header in pyqt

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)

pyqt keypress event in lineedit

i have created a untitled ui where exists one lineedit.
now i want to get the value of whatever i type in lineedit immediately
i figured out it could be done using keypressevent but i exactly didn't understand how to use it in lineedit now
from untitled 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_Dialog):
def event(self, event):
if type(event) == QtGui.QKeyEvent:
print (event.key())
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
#here i want to get what is keypressed in my lineEdit
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
this is my untitled.py code that i have imported
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.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_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(662, 207)
self.lineEdit = QtGui.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(50, 30, 113, 27))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
If you want to get the whole text in the line-edit as it is entered, you can use the textEdited signal. However, if you just want to get the current key that was pressed, you can use an event-filter.
Here is how to use both of these approaches:
class MainWindow(QMainWindow, Ui_Dialog):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.lineEdit.installEventFilter(self)
self.lineEdit.textEdited.connect(self.showCurrentText)
def eventFilter(self, source, event):
if (event.type() == QEvent.KeyPress and
source is self.lineEdit):
print('key press:', (event.key(), event.text()))
return super(MainWindow, self).eventFilter(source, event)
def showCurrentText(self, text):
print('current-text:', text)

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.

Resources