Select a text in PYQT to copy - python

I designed a windows desktop app with QT Designer and PYQT5. The problem is that, I can not select any item, text on main window, or on qtablewidget to paste it manually somewhere else. It will make things easier for users not for me. `
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(260, 160, 256, 192))
self.tableWidget.setRowCount(3)
self.tableWidget.setColumnCount(2)
self.tableWidget.setObjectName("tableWidget")
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(1, 0, item)
self.input_gunduz = QtWidgets.QLineEdit(self.centralwidget)
self.input_gunduz.setGeometry(QtCore.QRect(370, 70, 71, 20))
self.input_gunduz.setObjectName("input_gunduz")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(220, 70, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
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"))
__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
item = self.tableWidget.item(1, 0)
item.setText(_translate("MainWindow", "trial"))
self.tableWidget.setSortingEnabled(__sortingEnabled)
self.label_5.setText(_translate("MainWindow", "Gündüz (kWhr):"))
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_())
`
The code is as seen above. Please help me make the main window selectable

Copying of text does not work in the same way for every widget, because each widget type uses even radically different way to show or interact with text.
If you want to copy the text of a QLabel, you have to make it selectable (by using label.setTextInteractionFlags(Qt.TextSelectableByMouse)).
But if you want to copy the text from QTableWidget, things are very different, since a table allows interaction with their items that prevent a simple text selection.
Obviously, the most simple method would be to start editing the item (assuming it's editable) and select its text, but if you want other ways to do that, it depends on how you want to be able to copy the text.
A possibility is to use the ctrl+c keyboard shortcut. To do so, we need to install an event filter on the table widget:
from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# install an event filter on the table widget, so that we can filter all
# its event, including keyboard presses
self.tableWidget.installEventFilter(self)
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.KeyPress and event == QtGui.QKeySequence.Copy:
# check if an index is currently selected and it has text
text = self.tableWidget.currentIndex().data()
if text:
# copy that text to the clipboard
QtWidgets.QApplication.clipboard().setText(text)
return super().eventFilter(source, event)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Note that in the example above I used the multiple inheritance method explained in the documentation about using Designer with ui files. You should never edit the files created by pyuic.
It's also possible to set a menu for the table widget and copy the text from there:
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
# ...
# use the custom context menu policy for the table widget, so that we can
# connect the menu request to a slot
self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.tableWidget.customContextMenuRequested.connect(self.showTableMenu)
def showTableMenu(self, pos):
# get the text of the index at the mouse cursor (if any)
text = self.tableWidget.indexAt(pos).data()
menu = QtWidgets.QMenu()
copyAction = menu.addAction('Copy')
if not text:
copyAction.setEnabled(False)
# show the menu
res = menu.exec_(QtGui.QCursor.pos())
if res == copyAction:
# if the menu has been triggered by the action, copy to the clipboard
QtWidgets.QApplication.clipboard().setText(text)

Related

PyQt5 QPushButton

I want to make Pushbutton show me the text like this
1 You clicked
2 PushButton
not in the same line.
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
Class Ui_MainWindow (object):
def setupUi(self, MainWindow):
MainWindow.resize(506, 312)
self.centralwidget = QtWidgets.QWidget(MainWindow)
# adding pushbutton
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(200, 150, 93, 28))
# adding signal and slot
self.pushButton.clicked.connect(self.changelabeltext)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(140, 90, 221, 20))
# keeping the text of label empty before button get clicked
self.label.setText("")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Push Button"))
def changelabeltext(self):
# changing the text of label after button get clicked
self.label.setText("You clicked PushButton")
# Hiding pushbutton from the main window
# after button get clicked.
self.pushButton.hide()
If __name__ == "__main__":
app = QtWidgets.QApplication (sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
if I understand you correctly, you want the text to be displayed as follows:
You clicked
PushButton
To achieve this, try placing a newline character in between the words like this:
"You clicked \nPushButton"
Alternatively, if this does not display correctly, try adding a new label with the second half of the text to it, or increase the size of the rectangle in which you placed the text.
Although you technically only asked how to place "You clicked" below "Pushbutton" (which can be done by putting a newline in the string "You clicked \nPushButton"), when you do this you will run into another fundamental problem with your code, mainly that you are positioning widgets by drawing them inside a QRect with a static position.
This will produce problems when you change the text or window size, since you will have to manually change the coordinates of the QRect to place then in the correct position.
I took the liberty of rewriting your setupUi to use layouts (which I recommend you research) instead of QRect's. Hope this helps, it should be a drop in replacement:
def setupUi(self, MainWindow):
MainWindow.resize(506, 312)
self.mainWidget = QtWidgets.QWidget(MainWindow)
self.pushButton = QtWidgets.QPushButton()
self.pushButton.clicked.connect(self.changelabeltext)
self.label = QtWidgets.QLabel()
self.label.setText("")
self.hbox = QtWidgets.QHBoxLayout()
self.hbox.addWidget(self.pushButton)
self.hbox.addWidget(self.label)
self.vbox = QtWidgets.QVBoxLayout()
self.vbox.addLayout(self.hbox)
self.hbox.setAlignment(QtCore.Qt.AlignCenter)
self.vbox.setAlignment(QtCore.Qt.AlignCenter)
self.mainWidget.setLayout(self.vbox)
MainWindow.setCentralWidget(self.mainWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)

How avoid change tab in QTabWidget | PyQt5

I'm trying to implement a tab with the name "+" in which if I click on it opens a ApplicationModal window for configurate the content in that tab. I want to avoid the change of tab when i click in it until press "Accept" in the ApplicationModal window. How can I block this change? I don't know if I explain me.
This it's de code
tabs.py for the MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(628, 504)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(36, 34, 541, 396))
self.tabWidget.setObjectName("tabWidget")
self.tab1 = QtWidgets.QWidget()
self.tab1.setObjectName("tab1")
self.tabWidget.addTab(self.tab1, "")
self.tab2 = QtWidgets.QWidget()
self.tab2.setObjectName("tab2")
self.tabWidget.addTab(self.tab2, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 628, 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)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab1), _translate("MainWindow", "Tab 1"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab2), _translate("MainWindow", "+"))
win0.py for the ApplicationModal window
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Win0(object):
def setupUi(self, Win0):
Win0.setObjectName("Win0")
Win0.setWindowModality(QtCore.Qt.ApplicationModal)
Win0.resize(255, 203)
self.centralwidget = QtWidgets.QWidget(Win0)
self.centralwidget.setObjectName("centralwidget")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(17, 9, 154, 22))
self.comboBox.setObjectName("comboBox")
self.accpet_button = QtWidgets.QPushButton(self.centralwidget)
self.accpet_button.setGeometry(QtCore.QRect(43, 130, 75, 23))
self.accpet_button.setObjectName("accpet_button")
self.cancel_button = QtWidgets.QPushButton(self.centralwidget)
self.cancel_button.setGeometry(QtCore.QRect(135, 131, 75, 23))
self.cancel_button.setObjectName("cancel_button")
Win0.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(Win0)
self.menubar.setGeometry(QtCore.QRect(0, 0, 255, 21))
self.menubar.setObjectName("menubar")
Win0.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(Win0)
self.statusbar.setObjectName("statusbar")
Win0.setStatusBar(self.statusbar)
self.retranslateUi(Win0)
QtCore.QMetaObject.connectSlotsByName(Win0)
def retranslateUi(self, Win0):
_translate = QtCore.QCoreApplication.translate
Win0.setWindowTitle(_translate("Win0", "New Window"))
self.accpet_button.setText(_translate("Win0", "Accept"))
self.cancel_button.setText(_translate("Win0", "Cancel"))
And the main.py for develop the functionality
from tabs import Ui_MainWindow
from win0 import Ui_Win0
from PyQt5 import QtCore, QtGui, QtWidgets
class Win0(Ui_Win0):
win0 = None
def __init__(self, win):
self.win0 = win
super().__init__()
self.setupUi(self.win0)
class Main(Ui_MainWindow):
win0 = None
win1 = None
def __init__(self, win):
self.win = win
super().__init__()
self.setupUi(self.win)
self.tabWidget.tabBarClicked.connect(self.tabClick)
def tabClick(self, event):
if event == 1:
print("New tab")
self.win1 = QtWidgets.QMainWindow()
new_window = Win0(self.win1)
self.win1.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Main(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
If you want a window that blocks the others until it's closed, you're looking for a modal dialog.
A modal window creates a mode that disables the main window but keeps it visible, with the modal window as a child window in front of it. Users must interact with the modal window before they can return to the parent application. This avoids interrupting the workflow on the main window.
[From the wikipedia article about modal windows]
It is relatively easy to achieve that in Qt, by using a QDialog.
Designer already provides two basic templates with basic Ok/Cancel buttons when you create a new form, so create a new dialog with buttons on right or bottom (this will automatically connect the button box with the dialog's accept/reject slots), add the combobox, save and convert the file with pyuic (in the following example, I exported the file as dialog.py and used the default Ui_Dialog).
Then the implementation is very easy. The important thing is to add the parent argument to the QDialog instance: this ensures that the dialog uses the parent as a reference for the "window modality", so that that parent is blocked until the dialog is closed by accepting or rejecting it (rejection is usually done by clicking on a RejectRole button like Cancel or by closing the dialog in any way, including pressing Esc).
Do note that I changed your approach by using multiple inheritance in order to make things easier (see the guidelines on using Designer about this approach, which is usually the better and most suggested method when using pyuic generated files).
from tabs import Ui_MainWindow
from dialog import Ui_Dialog
from PyQt5 import QtCore, QtGui, QtWidgets
class SelectDialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
class Main(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.tabWidget.tabBarClicked.connect(self.tabClick)
def tabClick(self, tab):
if tab == 1:
dialog = SelectDialog(self)
if dialog.exec_():
print(dialog.comboBox.currentIndex())
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = Main()
mainWindow.show()
sys.exit(app.exec_())

Very basic pyqt5 dialog app quits with exit code -1073740791

I tried to design a very basic GUI app that shows the entered height on a dialog, but after I press the ‘OK’ button on the main window, the whole program crashes and the process finishes with this exit code:
Process finished with exit code -1073740791 (0xC0000409)
Here’s the full code for the app, the UI files are below:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.uic import *
class My_Dialog(QDialog):
def __init__(self):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
self.mid_label.setText(My_Window.mid_label_nexttext)
class My_Window(QMainWindow):
def __init__(self):
super(My_Window, self).__init__()
loadUi("mainwindow.ui", self)
self.mid_label_nexttext = None
self.height_selecter_spinbox.textChanged.connect(lambda x: self.spin_changed(x))
self.pushButton.clicked.connect(self.onMyPushButtonClick)
def onMyPushButtonClick(self):
dlg = My_Dialog()
if dlg.exec_():
print("Success!")
else:
print("Cancel!")
def spin_changed(self, s):
self.mid_label_nexttext = s
self.update()
def main():
app = QApplication(sys.argv)
window = My_Window()
window.show()
app.exec_()
if __name__ == "__main__":
main()
The main window’s UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(513, 171)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(310, 80, 75, 23))
self.pushButton.setObjectName("pushButton")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(90, 40, 209, 29))
self.layoutWidget.setObjectName("layoutWidget")
self.layout = QtWidgets.QHBoxLayout(self.layoutWidget)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setObjectName("layout")
self.label_firstpart = QtWidgets.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_firstpart.setFont(font)
self.label_firstpart.setObjectName("label_firstpart")
self.layout.addWidget(self.label_firstpart)
self.height_selecter_spinbox = QtWidgets.QSpinBox(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(13)
self.height_selecter_spinbox.setFont(font)
self.height_selecter_spinbox.setMinimum(100)
self.height_selecter_spinbox.setMaximum(250)
self.height_selecter_spinbox.setProperty("value", 175)
self.height_selecter_spinbox.setObjectName("height_selecter_spinbox")
self.layout.addWidget(self.height_selecter_spinbox)
self.label_lastpart = QtWidgets.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_lastpart.setFont(font)
self.label_lastpart.setObjectName("label_lastpart")
self.layout.addWidget(self.label_lastpart)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 513, 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.pushButton.setText(_translate("MainWindow", "OK"))
self.label_firstpart.setText(_translate("MainWindow", "My height is "))
self.label_lastpart.setText(_translate("MainWindow", "cm."))
The dialog’s UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dialog.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.dialog_buttonbox = QtWidgets.QDialogButtonBox(Dialog)
self.dialog_buttonbox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.dialog_buttonbox.setOrientation(QtCore.Qt.Horizontal)
self.dialog_buttonbox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.dialog_buttonbox.setObjectName("dialog_buttonbox")
self.widget = QtWidgets.QWidget(Dialog)
self.widget.setGeometry(QtCore.QRect(80, 90, 151, 41))
self.widget.setObjectName("widget")
self.dialog_layout = QtWidgets.QHBoxLayout(self.widget)
self.dialog_layout.setContentsMargins(0, 0, 0, 0)
self.dialog_layout.setObjectName("dialog_layout")
self.left_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.left_label.setFont(font)
self.left_label.setObjectName("left_label")
self.dialog_layout.addWidget(self.left_label)
self.mid_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.mid_label.setFont(font)
self.mid_label.setObjectName("mid_label")
self.dialog_layout.addWidget(self.mid_label)
self.right_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.right_label.setFont(font)
self.right_label.setObjectName("right_label")
self.dialog_layout.addWidget(self.right_label)
self.retranslateUi(Dialog)
self.dialog_buttonbox.accepted.connect(Dialog.accept)
self.dialog_buttonbox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.left_label.setText(_translate("Dialog", "You are"))
self.mid_label.setText(_translate("Dialog", "100"))
self.right_label.setText(_translate("Dialog", "cm tall."))
I would appreciate some help on fixing this error, and on why it occured.
You are trying to access an attribute that does not exist:
self.mid_label.setText(My_Window.mid_label_nexttext)
My_Window is a class, while mid_label_nexttext was assigned to the instance of that class (self is always the reference to the current instance).
If you want to set the text for that label from a "parent" window, you either add an extra argument to the __init__ that allows to get the text, or you set it from the main window.
Use the text as init argument
class My_Dialog(QDialog):
def __init__(self, text):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
# ensure that "text" is a valid string, you can't use setText(None)
if text:
self.mid_label.setText(text)
class My_Window(QMainWindow):
# ...
def onMyPushButtonClick(self):
dlg = My_Dialog(self.mid_label_nexttext)
# ...
Set the text from the parent
class My_Dialog(QDialog):
def __init__(self):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
# NO setText() here!!!
class My_Window(QMainWindow):
# ...
def onMyPushButtonClick(self):
dlg = My_Dialog()
if self.mid_label_nexttext:
dlg.mid_label.setText(self.mid_label_nexttext)
# ...
Note that the first method is usually better, mostly for modularity reasons: let's say that you create that dialog from different classes in different situations, whenever you need to change the object name of the label (or the whole interface structure) you can easily change its reference in the dialog subclass, otherwise you'll need to change every reference in your code.
Note: the call to self.update() is useless; if you want to update the label on the dialog whenever the spinbox value is changed, you need to directly access the label (like in the last example) or use signals. Also, you don't need to use lambda if you're using the same argument parameter, just connect to the function.

How to work with multiple windows in PyQt5? Passing Values through multiple windows and Calling Modules in Other Modules

I have created a GUI with PyQt5. I have total three windows. first window has one push button (**btn_OpenSecondWIndow**) which opens a second window. second window has one push button (**btn_OpenCalendar**) which opens third (Calendar) window. user picks a date from there and select a button (**btn_selecteddate**) on third window, I want to display that selection in the label (label_Date) in the second window.
Snippet to get the flow
Now I'm at this point where the first window works just fine and the second window opens BUT pushbuttons doesn't work.
The button in the second window does nothing when the window is opened from the first one but when the class "SecondWindow" is called by its own and not from the first window, it works.
here is the code:
from PyQt5 import QtWidgets
from FirstWindow import Ui_FirstWindow
from SecondWindow import Ui_SecondWindow
from Calendar import Ui_CalendarWindow
class Calendar(QtWidgets.QMainWindow, Ui_CalendarWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
class FirstWindow(QtWidgets.QMainWindow, Ui_FirstWindow):
def __init__(self):
super(FirstWindow,self).__init__()
self.setupUi(self)
self.btn_OpenSecondWIndow.clicked.connect(self.open_SecondWindow)
def open_SecondWindow(self):
self.window = QtWidgets.QMainWindow()
self.ui = SecondWindow()
self.ui.setupUi(self.window)
self.window.show()
self.setEnabled(False)
self.window.setEnabled(True)
class SecondWindow(QtWidgets.QMainWindow, Ui_SecondWindow):
def __init__(self):
super(SecondWindow, self).__init__()
self.setupUi(self)
self.btn_OpenCalendar.clicked.connect(self.Open_Calendar)
def Open_Calendar(self):
self.window = Calendar()
self.window.setupUi(self.window)
self.window.show()
self.window.btn_Selecteddate.clicked.connect(self.PickedDate)
def PickedDate(self):
self.selecteddate = self.window.CalendarBox.selectedDate()
self.label_Date.setText(self.selecteddate.toString('MMM')+'-'+self.selecteddate.toString('yyyy'))
self.window.hide()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = FirstWindow()
window.show()
sys.exit(app.exec_())
Reference Ui Class codes are as below:
First Window:
from PyQt5 import QtCore, QtWidgets
class Ui_FirstWindow(object):
def setupUi(self, FirstWindow):
FirstWindow.setObjectName("FirstWindow")
FirstWindow.resize(380, 195)
self.centralwidget = QtWidgets.QWidget(FirstWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_OpenSecondWIndow = QtWidgets.QPushButton(self.centralwidget)
self.btn_OpenSecondWIndow.setGeometry(QtCore.QRect(80, 60, 221, 61))
self.btn_OpenSecondWIndow.setObjectName("btn_OpenSecondWIndow")
FirstWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(FirstWindow)
self.statusbar.setObjectName("statusbar")
FirstWindow.setStatusBar(self.statusbar)
self.retranslateUi(FirstWindow)
QtCore.QMetaObject.connectSlotsByName(FirstWindow)
def retranslateUi(self, FirstWindow):
_translate = QtCore.QCoreApplication.translate
FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
self.btn_OpenSecondWIndow.setText(_translate("FirstWindow", "Open Second Window"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
FirstWindow = QtWidgets.QMainWindow()
ui = Ui_FirstWindow()
ui.setupUi(FirstWindow)
FirstWindow.show()
sys.exit(app.exec_())
Second WIndow:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SecondWindow(object):
def setupUi(self, SecondWindow):
SecondWindow.setObjectName("SecondWindow")
SecondWindow.resize(654, 242)
self.centralwidget = QtWidgets.QWidget(SecondWindow)
self.centralwidget.setObjectName("centralwidget")
self.label_Date = QtWidgets.QLabel(self.centralwidget)
self.label_Date.setGeometry(QtCore.QRect(330, 60, 281, 131))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.label_Date.setFont(font)
self.label_Date.setLayoutDirection(QtCore.Qt.LeftToRight)
self.label_Date.setObjectName("label_Date")
self.btn_OpenCalendar = QtWidgets.QPushButton(self.centralwidget)
self.btn_OpenCalendar.setGeometry(QtCore.QRect(80, 90, 191, 61))
self.btn_OpenCalendar.setObjectName("btn_OpenCalendar")
SecondWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(SecondWindow)
self.statusbar.setObjectName("statusbar")
SecondWindow.setStatusBar(self.statusbar)
self.retranslateUi(SecondWindow)
QtCore.QMetaObject.connectSlotsByName(SecondWindow)
def retranslateUi(self, SecondWindow):
_translate = QtCore.QCoreApplication.translate
SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
self.label_Date.setText(_translate("SecondWindow", "Date"))
self.btn_OpenCalendar.setText(_translate("SecondWindow", "Open Calendar"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
SecondWindow = QtWidgets.QMainWindow()
ui = Ui_SecondWindow()
ui.setupUi(SecondWindow)
SecondWindow.show()
sys.exit(app.exec_())
Third (Calendar) Window:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CalendarWindow(object):
def setupUi(self, CalendarWindow):
CalendarWindow.setObjectName("CalendarWindow")
CalendarWindow.resize(512, 458)
self.centralwidget = QtWidgets.QWidget(CalendarWindow)
self.centralwidget.setObjectName("centralwidget")
self.CalendarBox = QtWidgets.QCalendarWidget(self.centralwidget)
self.CalendarBox.setGeometry(QtCore.QRect(20, 20, 464, 289))
self.CalendarBox.setObjectName("CalendarBox")
self.btn_Selecteddate = QtWidgets.QPushButton(self.centralwidget)
self.btn_Selecteddate.setGeometry(QtCore.QRect(160, 330, 181, 60))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.btn_Selecteddate.setFont(font)
self.btn_Selecteddate.setObjectName("btn_Selecteddate")
CalendarWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(CalendarWindow)
self.statusbar.setObjectName("statusbar")
CalendarWindow.setStatusBar(self.statusbar)
self.retranslateUi(CalendarWindow)
QtCore.QMetaObject.connectSlotsByName(CalendarWindow)
def retranslateUi(self, CalendarWindow):
_translate = QtCore.QCoreApplication.translate
CalendarWindow.setWindowTitle(_translate("CalendarWindow", "MainWindow"))
self.btn_Selecteddate.setText(_translate("CalendarWindow", "Select"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
CalendarWindow = QtWidgets.QMainWindow()
ui = Ui_CalendarWindow()
ui.setupUi(CalendarWindow)
CalendarWindow.show()
sys.exit(app.exec_())
Thanks in Advance. :)
In FirstWindow.open_SecondWindow you don't need to create a separate QMainWindow object for the second window. SecondWindow() already returns a QMainWindow object with the proper UI set up and a slot connected to btn_OpenCalendar for opening the calendar window. Therefore it is sufficient to do something like:
def open_SecondWindow(self):
self.window = SecondWindow()
self.window.show()
self.setEnabled(False)
self.window.setEnabled(True)

PyQt5 Designer with Custom Slots

I'm still trying to figure out PyQt and running into another issue that I've been beating my head over for the last several hours. When I use pyuic5 to convert the .ui file into the .py file, part of the output (in the class Ui_MainWindow) connects signals to slots:
self.browseButton.clicked.connect(MainWindow.browseSlot)
self.importButton.clicked.connect(MainWindow.importSlot)
self.lineEdit.returnPressed.connect(MainWindow.returnPressedSlot)
This is called from the main function:
def main():
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = MainWindowUI()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Above this, in the same file, I have the following code:
class MainWindowUI(Ui_MainWindow):
def __init__(self):
super().__init__()
self.model = Model()
def setupUi(self, mainWindow):
super().setupUi(mainWindow)
def debugPrint(self, msg):
self.textEdit.append(msg)
def refreshAll(self):
self.lineEdit.setText(self.model.getFileName())
self.textEdit.setText(self.model.getFileContents())
def returnPressedSlot(self):
self.debugPrint('Return key pressed')
def importSlot(self):
self.debugPrint('Import button pressed')
def browseSlot(self):
self.debugPrint('Browse button pressed')
The exact error I'm getting is this:
AttributeError: 'QMainWindow' object has no attribute 'browseSlot'
This actually makes perfect sense, because there's no reason QtWidgets.QMainWindow() should know anything about the custom slots I defined in the MainWindowUI class. So it makes sense that it doesn't work, but I'm confused about what I should be doing differently. This is how every tutorial I've seen sets it up, so clearly I have a fundamental misunderstanding somewhere. Any help in clarifying this issue would be appreciated!
Many thanks in advance.
Edited to add the full code of my Ui_MainWindow class:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(798, 593)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.verticalLayout = QtWidgets.QVBoxLayout(self.tab)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.frame_2 = QtWidgets.QFrame(self.tab)
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.debugTextBrowser = QtWidgets.QTextBrowser(self.frame_2)
self.debugTextBrowser.setGeometry(QtCore.QRect(10, 10, 351, 461))
self.debugTextBrowser.setObjectName("debugTextBrowser")
self.horizontalLayout_2.addWidget(self.frame_2)
self.frame = QtWidgets.QFrame(self.tab)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.browseButton = QtWidgets.QPushButton(self.frame)
self.browseButton.setGeometry(QtCore.QRect(80, 30, 51, 20))
self.browseButton.setObjectName("browseButton")
self.lineEdit = QtWidgets.QLineEdit(self.frame)
self.lineEdit.setGeometry(QtCore.QRect(80, 10, 281, 20))
self.lineEdit.setObjectName("lineEdit")
self.importButton = QtWidgets.QPushButton(self.frame)
self.importButton.setGeometry(QtCore.QRect(310, 30, 51, 20))
self.importButton.setObjectName("importButton")
self.textEdit = QtWidgets.QTextEdit(self.frame)
self.textEdit.setGeometry(QtCore.QRect(80, 130, 281, 81))
self.textEdit.setObjectName("textEdit")
self.horizontalLayout_2.addWidget(self.frame)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.setupProgressBar = QtWidgets.QProgressBar(self.tab)
self.setupProgressBar.setProperty("value", 0)
self.setupProgressBar.setTextVisible(False)
self.setupProgressBar.setInvertedAppearance(False)
self.setupProgressBar.setTextDirection(QtWidgets.QProgressBar.TopToBottom)
self.setupProgressBar.setObjectName("setupProgressBar")
self.verticalLayout.addWidget(self.setupProgressBar)
self.tabWidget.addTab(self.tab, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.tabWidget.addTab(self.tab_2, "")
self.tab_3 = QtWidgets.QWidget()
self.tab_3.setObjectName("tab_3")
self.tabWidget.addTab(self.tab_3, "")
self.tab_4 = QtWidgets.QWidget()
self.tab_4.setObjectName("tab_4")
self.tabWidget.addTab(self.tab_4, "")
self.tab_5 = QtWidgets.QWidget()
self.tab_5.setObjectName("tab_5")
self.tabWidget.addTab(self.tab_5, "")
self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 798, 18))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
self.browseButton.clicked.connect(MainWindow.browseSlot)
self.importButton.clicked.connect(MainWindow.importSlot)
self.lineEdit.returnPressed.connect(MainWindow.returnPressedSlot)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.browseButton.setText(_translate("MainWindow", "Browse"))
self.importButton.setText(_translate("MainWindow", "Import"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Setup"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Production Forecast"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Production Forecast"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "Page"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("MainWindow", "Page"))
PyQt recommends in your docs that you should inherit from the appropriate widget, in this case QMainWindow, and use Ui_MainWindow as an interface, it is also recommended that you use the decorator #QtCore.pyqtSlot() since you save resources and avoid having problems with overloaded signals.
class MainWindowUI(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.model = Model()
def setupUi(self, mainWindow):
super().setupUi(mainWindow)
def debugPrint(self, msg):
self.textEdit.append(msg)
def refreshAll(self):
self.lineEdit.setText(self.model.getFileName())
self.textEdit.setText(self.model.getFileContents())
#QtCore.pyqtSlot()
def returnPressedSlot(self):
self.debugPrint('Return key pressed')
#QtCore.pyqtSlot()
def importSlot(self):
self.debugPrint('Import button pressed')
#QtCore.pyqtSlot()
def browseSlot(self):
self.debugPrint('Browse button pressed')
def main():
app = QtWidgets.QApplication(sys.argv)
w = MainWindowUI()
w.show()
sys.exit(app.exec_())
if __name__ == '__main__': main()
The PyQt 5 Designer generates files with .ui extension. The file contains xml code which can be converted to Python code with the pyuic5 command. The pyuic5 command produces a file with .py extension.
But each time the pyuic5 command is run, it overwrites any changes made to the Python file. To prevent this we need to copy the "main" code in the generated Python file to a separate file and then use this file as our main program file. In this file we can import the Python class generated by the pyuic5 command. We can also add our custom slots in this file
This practice of separating Qt Desginer code from custom code is good Qt programming practice. It has been suggested in Section 3 of the video ebook: "Python GUI Programming Recipes using PyQt5".

Categories