I am working on some app. I wanted to create a toolbar that after having been clicked will open Settings window. However I don't know how to do it exactly. The way it is now is that i have a Toolbar icon connected to ShowSettings function. This function creates a new instance of settings each time I click on the icon ( i know it shouldn't create new instances each time but only one in the beginning and then work on it. I don't know how to do it though) and then show the settings window associated with this instance. However in this way the settings window only flashes for a second and then disappears. I don't know what's wrong hope you can help me out :)
import sys
import time
from PyQt4 import QtCore, QtGui
from ui import Ui_MainWindow
from ui import Ui_SettingsWindow
#Aplikacja obslugujaca bramki LF
#zamiana pliku .ui na kod pythona
#pyuic4 untitled.ui -o output.py
class timerThread(QtCore.QThread):
timeElapsed = QtCore.pyqtSignal(float)
def __init__(self, parent=None):
super(timerThread, self).__init__(parent)
self.timeStart = None
def start(self, timeStart):
self.timeStart = timeStart
return super(timerThread, self).start()
def run(self):
while self.parent().isRunning():
self.timeElapsed.emit(time.time() - self.timeStart)
time.sleep(0.1)
class myThread(QtCore.QThread):
timeElapsed = QtCore.pyqtSignal(float)
def __init__(self, parent=None):
super(myThread, self).__init__(parent)
self.timerThread = timerThread(self)
self.timerThread.timeElapsed.connect(self.timeElapsed.emit)
def run(self):
self.timerThread.start(time.time())
iterations = 10000000000
while iterations:
print "Running {0}".format(self.__class__.__name__)
iterations -= 1
time.sleep(10)
class SettingsWindow(QtGui.QMainWindow):
#Constructor:
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui_settigns = Ui_SettingsWindow()
self.ui_settigns.setupUi(self)
class MainWindow(QtGui.QMainWindow):
#Constructor:
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.myThread = myThread(self)
self.myThread.timeElapsed.connect(self.on_myThread_timeElapsed)
self.myThread.finished.connect(self.on_myThread_finished)
#Nie wiem jak przerzucic to do pliku UI bez errorow
#Toolbar
settingsAction = QtGui.QAction(QtGui.QIcon('tools.jpg'), 'Ustawienia', self)
settingsAction.setShortcut('Ctrl+U')
settingsAction.triggered.connect(self.ShowSettings)
self.toolbar = self.addToolBar('Settings')
self.toolbar.addAction(settingsAction)
def UpdateList(self):
contest_name = self.ui.comboBox.currentText()
#jakis try-catch tutaj sie przyda gdyby nie plik nie istnial
#zczytuje z pliku liste robotow
with open('database\%s.txt' % contest_name) as f:
robots_list = f.read().splitlines()
self.ui.listWidget.clear()
self.ui.listWidget.addItems(robots_list)
def Search(self):
text = self.ui.lineEdit.text()
self.ui.lineEdit.clear()
item = self.ui.listWidget.findItems(text, QtCore.Qt.MatchExactly)
#jakiegos try-catcha trzeba tutaj walnac
self.ui.listWidget.setItemSelected(item[0], True)
def ShowSettings(self):
settings = SettingsWindow() #creates settings instance
settings.show()
#QtCore.pyqtSlot()
def on_button_clicked(self):
self.myThread.start()
#QtCore.pyqtSlot(int)
def on_myThread_timeElapsed(self, seconds):
self.ui.lcdNumber.display(seconds)
#QtCore.pyqtSlot()
def on_myThread_finished(self):
self.myThread.terminate()
print "Done"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
settings = SettingsWindow()
myapp.show()
settings.show()
sys.exit(app.exec_())
And Here is the UI file
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Fri Apr 24 08:04:20 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_SettingsWindow(object):
def setupUi(self, SettingsWindow):
SettingsWindow.setObjectName(_fromUtf8("Ustawienia"))
SettingsWindow.resize(686, 556)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(686, 556)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.groupBox = QtGui.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 341, 491))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.pushButton = QtGui.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(10, 460, 231, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.label = QtGui.QLabel(self.groupBox)
self.label.setGeometry(QtCore.QRect(10, 80, 90, 16))
self.label.setObjectName(_fromUtf8("label"))
self.lineEdit = QtGui.QLineEdit(self.groupBox)
self.lineEdit.setGeometry(QtCore.QRect(130, 77, 191, 20))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.listWidget = QtGui.QListWidget(self.groupBox)
self.listWidget.setGeometry(QtCore.QRect(10, 110, 321, 341))
self.listWidget.setObjectName(_fromUtf8("listWidget"))
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
self.label_2 = QtGui.QLabel(self.groupBox)
self.label_2.setGeometry(QtCore.QRect(10, 50, 111, 16))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.comboBox = QtGui.QComboBox(self.groupBox)
self.comboBox.setGeometry(QtCore.QRect(130, 50, 191, 22))
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.comboBox.addItem(_fromUtf8(""))
self.comboBox.addItem(_fromUtf8(""))
self.comboBox.addItem(_fromUtf8(""))
self.comboBox.addItem(_fromUtf8(""))
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
self.groupBox_2.setGeometry(QtCore.QRect(360, 10, 311, 491))
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.lcdNumber = QtGui.QLCDNumber(self.groupBox_2)
self.lcdNumber.setGeometry(QtCore.QRect(10, 20, 281, 151))
self.lcdNumber.setSmallDecimalPoint(True)
self.lcdNumber.setObjectName(_fromUtf8("lcdNumber"))
self.pushButton_2 = QtGui.QPushButton(self.groupBox_2)
self.pushButton_2.setGeometry(QtCore.QRect(20, 340, 75, 23))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.pushButton_3 = QtGui.QPushButton(self.groupBox_2)
self.pushButton_3.setGeometry(QtCore.QRect(200, 340, 75, 23))
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.lineEdit.clear)
QtCore.QObject.connect(self.lineEdit, QtCore.SIGNAL("returnPressed()"), MainWindow.Search) #connected to Search method in class MainWindow
QtCore.QObject.connect(self.comboBox, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), MainWindow.UpdateList)
QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.on_button_clicked)
QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.on_myThread_finished)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "LF Timer", None))
self.groupBox.setTitle(_translate("MainWindow", "Wybierz robota", None))
self.pushButton.setText(_translate("MainWindow", "Uruchom AplikacjÄ™ Pomiaru Czasu", None))
self.label.setText(_translate("MainWindow", "Wyszukaj robota:", None))
self.lineEdit.setText(_translate("MainWindow", "cos tam", None))
__sortingEnabled = self.listWidget.isSortingEnabled()
self.listWidget.setSortingEnabled(False)
item = self.listWidget.item(0)
item.setText(_translate("MainWindow", "Robot 1", None))
item = self.listWidget.item(1)
item.setText(_translate("MainWindow", "Robot 2", None))
item = self.listWidget.item(2)
item.setText(_translate("MainWindow", "Robot 3", None))
self.listWidget.setSortingEnabled(__sortingEnabled)
self.label_2.setText(_translate("MainWindow", "Wybierz Konkurencje:", None))
self.comboBox.setItemText(0, _translate("MainWindow", "", None))
self.comboBox.setItemText(1, _translate("MainWindow", "LF", None))
self.comboBox.setItemText(2, _translate("MainWindow", "TURBO LF", None))
self.comboBox.setItemText(3, _translate("MainWindow", "LEGO LF", None))
self.groupBox_2.setTitle(_translate("MainWindow", "Pomiar Czasu", None))
self.pushButton_2.setText(_translate("MainWindow", "Start", None))
self.pushButton_3.setText(_translate("MainWindow", "Stop", None))
The instance of the settings window is local to the MainWindow.ShowSettings method. As such, it is quickly garbage collected because nothing keeps a reference to the window.
You can fix this in two ways. The first is to specify a parent of the settings window when it is instantiated. The second is to store it as an instance attribute of MainWindow (eg self.settings = ...).
Thank you three_pineapples for your help. I used the second way that you have described. It works like a dream :) Here's the code if anyone needs it.
import sys
import time
from PyQt4 import QtCore, QtGui
from ui import Ui_MainWindow
from ui import Ui_SettingsWindow
#Aplikacja obslugujaca bramki LF
#zamiana pliku .ui na kod pythona
#pyuic4 untitled.ui -o output.py
#py to exe
#python setup.py py2exe --includes sip
class timerThread(QtCore.QThread):
timeElapsed = QtCore.pyqtSignal(float)
def __init__(self, parent=None):
super(timerThread, self).__init__(parent)
self.timeStart = None
def start(self, timeStart):
self.timeStart = timeStart
return super(timerThread, self).start()
def run(self):
while self.parent().isRunning():
self.timeElapsed.emit(time.time() - self.timeStart)
time.sleep(0.1)
class myThread(QtCore.QThread):
timeElapsed = QtCore.pyqtSignal(float)
def __init__(self, parent=None):
super(myThread, self).__init__(parent)
self.timerThread = timerThread(self)
self.timerThread.timeElapsed.connect(self.timeElapsed.emit)
def run(self):
self.timerThread.start(time.time())
iterations = 10000000000
while iterations:
print "Running {0}".format(self.__class__.__name__)
iterations -= 1
time.sleep(10)
class SettingsWindow(QtGui.QMainWindow):
#Constructor:
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui_settigns = Ui_SettingsWindow()
self.ui_settigns.setupUi(self)
class MainWindow(QtGui.QMainWindow):
#Constructor:
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.settings = SettingsWindow()# Creates and stores SettingsWindow instance, MainWindow manages SettingsWindow
self.myThread = myThread(self)
self.myThread.timeElapsed.connect(self.on_myThread_timeElapsed)
self.myThread.finished.connect(self.on_myThread_finished)
#Nie wiem jak przerzucic to do pliku UI bez errorow
#Toolbar
settingsAction = QtGui.QAction(QtGui.QIcon('tools.jpg'), 'Ustawienia', self)
settingsAction.setShortcut('Ctrl+U')
settingsAction.triggered.connect(self.ShowSettings)
self.toolbar = self.addToolBar('Settings')
self.toolbar.addAction(settingsAction)
def UpdateList(self):
contest_name = self.ui.comboBox.currentText()
#jakis try-catch tutaj sie przyda gdyby nie plik nie istnial
#zczytuje z pliku liste robotow
with open('database\%s.txt' % contest_name) as f:
robots_list = f.read().splitlines()
self.ui.listWidget.clear()
self.ui.listWidget.addItems(robots_list)
def Search(self):
text = self.ui.lineEdit.text()
self.ui.lineEdit.clear()
item = self.ui.listWidget.findItems(text, QtCore.Qt.MatchExactly)
#jakiegos try-catcha trzeba tutaj walnac
self.ui.listWidget.setItemSelected(item[0], True)
def ShowSettings(self):
self.settings.show()
#QtCore.pyqtSlot()
def on_button_clicked(self):
self.myThread.start()
#QtCore.pyqtSlot(int)
def on_myThread_timeElapsed(self, seconds):
self.ui.lcdNumber.display(seconds)
#QtCore.pyqtSlot()
def on_myThread_finished(self):
self.myThread.terminate()
print "Done"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())
Related
I created a custom dialog that contains a QLineEdit. When certain criteria matches on the main screen, the dialog opens up and allows the user to enter input. Upon returning the the main screen, that input needs to be grabbed and used.
In QtDesigner, I created I dialog (with the Ok and Cancel buttons already on it) and added a QLineEdit with an object name of lineEdit.
also I'm using three .py file one is main_app which is importing other two files mainwindow file and dialog file (converted from .ui file)
following is the method I'm using to open dialog in my main_app file.
def open_dialog(self):
Dialog = QtWidgets.QDialog()
ui = sub_search.Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
resp = Dialog.exec_()
if resp == QtWidgets.QDialog.Accepted:
print("Accepted!") #this place will be used to do something more once I have
#userinupt from dialog box
till this end code is working fine I'm not sure how to return and use user input
following is the code I'm trying to return input of lineEdit from dialog box
def get_text_from(self):
if self.lineEdit.text() != "" and self.buttonBox.accepted():
swc = self.lineEdit.text()
return swc
elif self.lineEdit.text() == "" and self.buttonBox.accepted():
warning_message(title="Warning!", message="please provide swc clli,thanks!")
else:
pass
following are the complete code where I want to put more filter based on user input
main_app.py
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMessageBox
import pandas as pd
from pyqt_master_data import search, sub_search
pd.set_option('display.max_rows', None, 'display.max_columns', None)
master_data = pd.read_excel('Master_data.xlsx', 'Shares')
class SearchTool(search.Ui_main, QtWidgets.QMainWindow):
def __init__(self):
super(SearchTool, self).__init__()
self.setupUi(self)
self.push()
def master_data_search(self):
if self.lineEdit.text() != "":
day = self.lineEdit.text().strip()
if day.upper() in "TUESDAY":
self.open_dialog()
else:
day_df = master_data[(master_data.Day.str.contains(day,
case=False, na=False))]
model = PandasModel(day_df)
self.tableView.setModel(model)
def push(self):
self.pushButton.clicked.connect(self.master_data_search)
def open_dialog(self):
Dialog = QtWidgets.QDialog()
ui = sub_search.Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
resp = Dialog.exec_()
if resp == QtWidgets.QDialog.Accepted:
print("Accepted!")
sub_search.Ui_Dialog.get_text_from() #do something here
else:
print('rejected')
def warning_message(title="Warning!", message="Please provide input,
thanks!"):
QMessageBox.information(None, title, message)
class PandasModel(QtCore.QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe
"""
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return str(self._data.values[index.row()][index.column()])
return None
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role ==
QtCore.Qt.DisplayRole:
return self._data.columns[col]
return None
if __name__ == "__main__":
app = QtWidgets.QApplication([])
qt_app = SearchTool()
qt_app.show()
app.exec_()
search.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_main(object):
def setupUi(self, main):
main.setObjectName("main")
main.resize(855, 886)
main.setMouseTracking(True)
main.setTabletTracking(True)
self.centralwidget = QtWidgets.QWidget(main)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setFrameShape(QtWidgets.QFrame.Box)
self.frame.setFrameShadow(QtWidgets.QFrame.Plain)
self.frame.setObjectName("frame")
self.verticalLayout = QtWidgets.QVBoxLayout(self.frame)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(self.frame)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.lineEdit = QtWidgets.QLineEdit(self.frame)
self.lineEdit.setClearButtonEnabled(True)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.pushButton = QtWidgets.QPushButton(self.frame)
font = QtGui.QFont()
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
self.verticalLayout_2.addWidget(self.frame)
self.frame_2 = QtWidgets.QFrame(self.centralwidget)
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_2)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.frame_3 = QtWidgets.QFrame(self.frame_2)
self.frame_3.setMouseTracking(True)
self.frame_3.setTabletTracking(True)
self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_3.setObjectName("frame_3")
self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_3)
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.tableView = QtWidgets.QTableView(self.frame_3)
self.tableView.setMouseTracking(True)
self.tableView.setTabletTracking(True)
self.tableView.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.tableView.setFrameShadow(QtWidgets.QFrame.Plain)
self.tableView.setDragEnabled(True)
self.tableView.setDefaultDropAction(QtCore.Qt.CopyAction)
self.tableView.setSortingEnabled(True)
self.tableView.setObjectName("tableView")
self.verticalLayout_4.addWidget(self.tableView)
self.verticalLayout_3.addWidget(self.frame_3)
self.verticalLayout_2.addWidget(self.frame_2)
main.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(main)
self.menubar.setGeometry(QtCore.QRect(0, 0, 855, 26))
self.menubar.setObjectName("menubar")
main.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(main)
self.statusbar.setObjectName("statusbar")
main.setStatusBar(self.statusbar)
self.retranslateUi(main)
QtCore.QMetaObject.connectSlotsByName(main)
def retranslateUi(self, main):
_translate = QtCore.QCoreApplication.translate
main.setWindowTitle(_translate("main", "MainWindow"))
self.label.setText(_translate("main", "DATA"))
self.lineEdit.setPlaceholderText(_translate("main", "day"))
self.pushButton.setText(_translate("main", "SEARCH"))
sub_search.py
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMessageBox
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(478, 170)
Dialog.setMaximumSize(QtCore.QSize(560, 170))
self.verticalLayout_2 = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.frame = QtWidgets.QFrame(Dialog)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.verticalLayout = QtWidgets.QVBoxLayout(self.frame)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(self.frame)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.lineEdit = QtWidgets.QLineEdit(self.frame)
self.lineEdit.setObjectName("lineEdit")
self.verticalLayout.addWidget(self.lineEdit)
self.verticalLayout_2.addWidget(self.frame)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setCenterButtons(True)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_2.addWidget(self.buttonBox)
self.retranslateUi(Dialog)
self.buttonBox.accepted.connect(Dialog.accept)
self.buttonBox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def get_text_from(self):
if self.lineEdit.text() != "" and self.buttonBox.accepted():
swc = self.lineEdit.text()
return swc
elif self.lineEdit.text() == "" and self.buttonBox.accepted():
warning_message(title="Warning!", message="please provide swc clli,thanks!")
else:
pass
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "TextLabel"))
self.buttonBox.accepted.connect(self.get_text_from)
def warning_message(title="Warning!", message="Please provide input,
thanks!"):
QMessageBox.information(None, title, message)
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_())
my Questions are how do capture lineEdit value and use in my main_app file.
I realize I've still got lots to learn so if someone could point in the right direction that would be awesome. I got decent start but I'm not sure how to finish this..
thanks in advance!
You could try something like this:
class SearchTool(search.Ui_main, QtWidgets.QMainWindow):
def __init__(self):
super(SearchTool, self).__init__()
self.setupUi(self)
self.push()
def master_data_search(self):
if self.lineEdit.text() != "":
day = self.lineEdit.text().strip()
if day.upper() in "TUESDAY":
result = self.open_dialog()
if result is not None:
print(f'the search result was {result}')
else:
print('the search was canceled')
else:
print('do something else')
def push(self):
self.pushButton.clicked.connect(self.master_data_search)
def open_dialog(self):
print('open dialog')
Dialog = QtWidgets.QDialog(self)
ui = sub_search.Ui_Dialog()
ui.setupUi(Dialog)
#Dialog.show()
resp = Dialog.exec_()
if resp == QtWidgets.QDialog.Accepted:
print("Accepted!")
# retrieve text from line edit in dialog and return it
return ui.lineEdit.text()
else:
print('rejected')
return None
I am trying pass a string from First window to Second window using signal. I want the string to be shown after pressing the push button on the Second window. However, I am getting the following error:"TypeError: decorated slot has no signature compatible with clicked(bool)"
I am using Qt-designer to create First and Second window.
Below is the main code:
class First(QDialog):
signal = pyqtSignal(str)
def __init__(self, parent = None):
super(First, self).__init__(parent)
self.ui = Ui_First()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.Send)
self.show()
def Send(self):
UserInput = self.ui.lineEdit.text()
foo = Second()
self.signal.connect(foo.Receive)
self.signal.emit(str(UserInput))
self.ui = Second()
class Second(QDialog):
def __init__(self, parent = None):
super(Second, self).__init__(parent)
self.ui = Ui_Second()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.Receive)
self.show()
#pyqtSlot(str)
def Receive(self, strA):
self.ui.label.setText(strA)
Here is the First.py:
class Ui_First(object):
def setupUi(self, First):
First.setObjectName("First")
First.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(First)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(First)
self.lineEdit.setGeometry(QtCore.QRect(40, 40, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(First)
QtCore.QMetaObject.connectSlotsByName(First)
def retranslateUi(self, First):
_translate = QtCore.QCoreApplication.translate
First.setWindowTitle(_translate("First", "First"))
self.pushButton.setText(_translate("First", "Send to Second"))
Here is the Second.py:
class Ui_Second(object):
def setupUi(self, Second):
Second.setObjectName("Second")
Second.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(Second)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(Second)
self.label.setGeometry(QtCore.QRect(60, 40, 55, 16))
self.label.setObjectName("label")
self.retranslateUi(Second)
QtCore.QMetaObject.connectSlotsByName(Second)
def retranslateUi(self, Second):
_translate = QtCore.QCoreApplication.translate
Second.setWindowTitle(_translate("Second", "Second"))
self.pushButton.setText(_translate("Second", "Show Input"))
self.label.setText(_translate("Second", "TextLabel"))
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Ui_First(object):
def setupUi(self, First):
First.setObjectName("First")
First.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(First)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(First)
self.lineEdit.setGeometry(QtCore.QRect(40, 40, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(First)
QtCore.QMetaObject.connectSlotsByName(First)
def retranslateUi(self, First):
_translate = QtCore.QCoreApplication.translate
First.setWindowTitle(_translate("First", "First"))
self.pushButton.setText(_translate("First", "Send to Second"))
class Ui_Second(object):
def setupUi(self, Second):
Second.setObjectName("Second")
Second.resize(195, 134)
self.pushButton = QtWidgets.QPushButton(Second)
self.pushButton.setGeometry(QtCore.QRect(40, 80, 111, 28))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(Second)
self.label.setGeometry(QtCore.QRect(60, 40, 55, 16))
self.label.setObjectName("label")
self.retranslateUi(Second)
QtCore.QMetaObject.connectSlotsByName(Second)
def retranslateUi(self, Second):
_translate = QtCore.QCoreApplication.translate
Second.setWindowTitle(_translate("Second", "Second"))
self.pushButton.setText(_translate("Second", "Show Input"))
self.label.setText(_translate("Second", "TextLabel"))
class First(QDialog):
signal = pyqtSignal(str)
def __init__(self, parent = None):
super(First, self).__init__(parent)
self.ui = Ui_First()
self.ui.setupUi(self)
self.ui.lineEdit.setFocus() # +
self.ui.pushButton.clicked.connect(self.Send)
self.show()
def Send(self):
UserInput = self.ui.lineEdit.text()
foo = Second(self) # + self.
self.signal.emit(str(UserInput))
# self.signal.connect(foo.Receive)
# self.ui = Second()
class Second(QDialog):
def __init__(self, parent = None):
super(Second, self).__init__(parent)
self.ui = Ui_Second()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.close) # - (self.Receive)
parent.signal.connect(self.Receive) # +++
self.show()
#pyqtSlot(str)
def Receive(self, strA):
self.ui.label.setText(strA)
self.ui.label.adjustSize() # +
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = First()
gui.show()
sys.exit(app.exec_())
I designed a window with QtDesigner and added a scrollarea and a layout in it, but the scroll area doesn't scroll, it shows the scroll bar but It cant be scrolled at all.
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 StartQT4(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(767, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(230, 300, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.lineEdit = QtGui.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(80, 330, 371, 71))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 767, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(130, 70, 301, 191))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setMinimumSize(QtCore.QSize(100, 100))
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 299, 189))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(100, 100))
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.horizontalLayoutWidget = QtGui.QWidget(self.scrollAreaWidgetContents)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(-1, -1, 301, 191))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout = QtGui.QVBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
p= QtGui.QPalette()
p.setColor(QtGui.QPalette.Background, QtCore.Qt.white)
self.scrollArea.setAutoFillBackground(True)
self.scrollArea.setPalette(p)
self.retranslateUi(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "send", None))
I want to add labels and this is how I do it
from main_ui import *
import sys
global height
height=10
def send():
global height
label=QtGui.QLabel(myapp.ui.horizontalLayoutWidget)
label.setGeometry(QtCore.QRect(10, height, 46, 13))
height=height+label.height()
label.setText(myapp.ui.lineEdit.text())
label.show()
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
QtCore.QObject.connect(myapp.ui.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), send)
myapp.setCentralWidget(myapp.ui.centralwidget)
QtCore.QMetaObject.connectSlotsByName(myapp)
sys.exit(app.exec_())
Sir, your code is a bit messed.
Here is a small example, see if it works. There is no secret. :D
it's in PyQt5. You just gotta change your imports to PyQt4.
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QScrollArea
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget
class WSlideBar(QWidget):
"""WSlideBar is a personalized slide bar."""
w_container = None
v_layout_container = None
v_scroll_area = None
v_layout_preview = None
def __init__(self):
"""Init UI."""
super(WSlideBar, self).__init__()
self.init_ui()
def init_ui(self):
"""Init all ui object requirements."""
self.setFixedSize(100,500)
self.setStyleSheet("""
background: gray;
""")
# Container Widget
self.w_container = QWidget()
self.w_container.setFixedWidth(100)
# Layout of Container Widget
self.v_layout_container = QVBoxLayout()
self.v_layout_container.setSpacing(100)
aux = QWidget()
aux.setFixedSize(10,10)
aux.setStyleSheet("""background: red;""")
aux2 = QWidget()
aux2.setFixedSize(20, 20)
aux2.setStyleSheet("""background: blue;""")
aux3 = QWidget()
aux3.setFixedSize(15, 15)
aux3.setStyleSheet("""background: yellow;""")
aux4 = QWidget()
aux4.setFixedSize(50,50)
aux4.setStyleSheet("""background: rgb(0,255,0,30%);""")
aux5 = QWidget()
aux5.setFixedSize(40, 40)
aux5.setStyleSheet("""background: green;""")
aux6 = QWidget()
aux6.setFixedSize(40, 40)
aux6.setStyleSheet("""background: green;""")
self.v_layout_container.addWidget(aux)
self.v_layout_container.addWidget(aux2)
self.v_layout_container.addWidget(aux3)
self.v_layout_container.addWidget(aux4)
self.v_layout_container.addWidget(aux5)
self.v_layout_container.addWidget(aux6)
self.w_container.setLayout(self.v_layout_container)
self.v_scroll_area = QScrollArea(self)
self.v_scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.v_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.v_scroll_area.setWidget(self.w_container)
# Scroll Area Layer add
self.v_layout_preview = QVBoxLayout()
self.setLayout(self.v_layout_preview)
self.v_layout_preview.addWidget(self.v_scroll_area)
def run():
app = QApplication(sys.argv)
GUI = WSlideBar()
GUI.show()
sys.exit(app.exec_())
run()
OBS: You will just have to change for QPushButtons, QLabels,... instead of small QWidgets and whatever you need.
I'm trying to connect a push-button on my main window to open a new widget when I click it. But each time I run the program I get this error:
AttributeError: 'dataAcquisition' object has no attribute 'gpioButton'
I will be grateful if someone can help.
Here's my code:
from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow
from gpiodialog import Ui_GPIODialog
import sys
class gpioDialog(QtGui.QDialog, Ui_GPIODialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
flags = QtCore.Qt.Drawer | QtCore.Qt.WindowStaysOnTopHint
self.setWidowFlags(flags)
self.ui = Ui_GPIODialog
self.ui.setupUi(self)
self.gpioOKButton.clicked.connect(self.acceptOKButtonClicked)
def acceptOKButtonClicked(self):
self.close()
class dataAcquisition(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.gpioButton.clicked.connect(self.gpioButton_clicked)
self.popGPIO = gpioDialog()
def gpioButton_clicked(self):
self.popGPIO.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
MainWindow = dataAcquisition()
MainWindow.show()
sys.exit(app.exec_())
mainwindow.py code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Tue Oct 18 02:57:57 2016
# by: PyQt4 UI code generator 4.11.2
#
# 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(700, 600)
MainWindow.setMinimumSize(QtCore.QSize(700, 600))
MainWindow.setMaximumSize(QtCore.QSize(700, 600))
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gpioButton = QtGui.QToolButton(self.centralwidget)
self.gpioButton.setGeometry(QtCore.QRect(20, 80, 181, 61))
self.gpioButton.setObjectName(_fromUtf8("gpioButton"))
self.procButton = QtGui.QPushButton(self.centralwidget)
self.procButton.setGeometry(QtCore.QRect(20, 180, 181, 61))
self.procButton.setObjectName(_fromUtf8("procButton"))
self.startButton = QtGui.QPushButton(self.centralwidget)
self.startButton.setEnabled(True)
self.startButton.setGeometry(QtCore.QRect(20, 360, 131, 51))
self.startButton.setObjectName(_fromUtf8("startButton"))
self.stopButton = QtGui.QPushButton(self.centralwidget)
self.stopButton.setGeometry(QtCore.QRect(190, 360, 131, 51))
self.stopButton.setObjectName(_fromUtf8("stopButton"))
self.plotButton = QtGui.QPushButton(self.centralwidget)
self.plotButton.setGeometry(QtCore.QRect(20, 460, 181, 61))
self.plotButton.setObjectName(_fromUtf8("plotButton"))
self.columnView = QtGui.QColumnView(self.centralwidget)
self.columnView.setGeometry(QtCore.QRect(340, 50, 341, 251))
self.columnView.setObjectName(_fromUtf8("columnView"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(280, 20, 221, 21))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.saveButton = QtGui.QPushButton(self.centralwidget)
self.saveButton.setEnabled(True)
self.saveButton.setGeometry(QtCore.QRect(410, 420, 211, 31))
self.saveButton.setObjectName(_fromUtf8("saveButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 700, 27))
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.gpioButton.setText(_translate("MainWindow", "GPIO Number of inputs", None))
self.procButton.setText(_translate("MainWindow", "Processing", None))
self.startButton.setText(_translate("MainWindow", "Start Acquiring", None))
self.stopButton.setText(_translate("MainWindow", "Stop Acquiring", None))
self.plotButton.setText(_translate("MainWindow", "Start Live Plot", None))
self.label_2.setText(_translate("MainWindow", "Data Acquisition System", None))
self.saveButton.setText(_translate("MainWindow", "Save this session\'s data", 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_())
gpiodialog.py code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gpiodialog.ui'
#
# Created: Tue Oct 18 03:11:51 2016
# by: PyQt4 UI code generator 4.11.2
#
# 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_GPIODialog(object):
def setupUi(self, GPIODialog):
GPIODialog.setObjectName(_fromUtf8("GPIODialog"))
GPIODialog.resize(400, 300)
self.gpioOKButton = QtGui.QPushButton(GPIODialog)
self.gpioOKButton.setGeometry(QtCore.QRect(170, 240, 101, 31))
self.gpioOKButton.setObjectName(_fromUtf8("gpioOKButton"))
self.label = QtGui.QLabel(GPIODialog)
self.label.setGeometry(QtCore.QRect(90, 20, 191, 21))
font = QtGui.QFont()
font.setPointSize(13)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.retranslateUi(GPIODialog)
QtCore.QMetaObject.connectSlotsByName(GPIODialog)
def retranslateUi(self, GPIODialog):
GPIODialog.setWindowTitle(_translate("GPIODialog", "Dialog", None))
self.gpioOKButton.setText(_translate("GPIODialog", "OK", None))
self.label.setText(_translate("GPIODialog", "Choose GPIO input bins", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
GPIODialog = QtGui.QDialog()
ui = Ui_GPIODialog()
ui.setupUi(GPIODialog)
GPIODialog.show()
sys.exit(app.exec_())
You created a separate namespace for the ui, so you would need to access the button like this:
self.ui.gpioButton.clicked.connect(self.gpioButton_clicked)
However, if you'd prefer to have all the widgets as attributes of the window, do this:
class gpioDialog(QtGui.QDialog, Ui_GPIODialog):
def __init__(self, parent=None):
super(gpioDialog, self).__init__(parent)
flags = QtCore.Qt.Drawer | QtCore.Qt.WindowStaysOnTopHint
self.setWindowFlags(flags)
self.setupUi(self)
self.gpioOKButton.clicked.connect(self.acceptOKButtonClicked)
class dataAcquisition(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(dataAcquisition, self).__init__(parent)
self.setupUi(self)
self.gpioButton.clicked.connect(self.gpioButton_clicked)
self.popGPIO = gpioDialog()
I need your help with my app. I undecorated python gui and now i need to create clicable label.
run.py
from PyQt4 import QtCore, QtGui
import sys
import untitled
class ExampleApp(QtGui.QMainWindow, untitled.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
def closeapp():
sys.exit(0);
untitled.py:
# -*- 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_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.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 110, 85, 30))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(220, 100, 58, 14))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(220, 140, 58, 14))
self.label_2.setObjectName(_fromUtf8("label_2"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
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.pushButton.setText(_translate("MainWindow", "open", None))
self.label.setText(_translate("MainWindow", "close", None))
self.label_2.setText(_translate("MainWindow", "view", None))
Now I need to add action to label and label_2. How to make the label to perform closeapp()?
Add a function to Ui_MainWindow class (untitled.py)
def click(self,eve):
print "clicked"
Then add attribute to label object
self.label.mousePressEvent = self.click
another option is just modify run.py file like following
class ExampleApp(QtGui.QMainWindow, untitled.Ui_MainWindow):
def click(self,eve):
print "clicked"
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.label.mousePressEvent = self.click
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
QLabel inherits QWidget. QWidget` has an event handler mousePressEvent
so as E-ebola virus mentioned
add
self.label.mousePressEvent = self.click
and define
def click(self,event):
#do something
or
subclass QLabel
class customLabel(QLabel):
def __init__(self):
QLabel.__init__(self)
def self.mousePressEvent(self,event):
self.emit(SIGNAL("closeapp"))
emit a SIGNAL when label is pressed, i would implement it as
self.label = customLabel()
self.connect(self.label,SIGNAL('closeapp'),self.close)