How to access QLineEdit in QDialog? - python

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

Related

Drag and drop files to QTableWidget

I'm trying to drag and drop files into a table-widget, but the path will not appear when I drop the files. When I test by using print() the path appears, but the path will not appear in the table. I am not sure why this is happening, I would greatly appreciate some help.
Main code:
import os
import shutil
import sys
import pandas as pd
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import *
from vituix_converter_UI import (Ui_MainWindow)
def no_file_selected():
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setWindowIcon(QtGui.QIcon("D:/Python Projects/HATS SAMS Conversion/Icon/Vituix_Converter_Icon_R1.ico"))
msg.setText("No File Was Selected!")
msg.setWindowTitle("Warning!")
retval = msg.exec_()
def process_completed():
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setWindowIcon(QtGui.QIcon("D:/Python Projects/HATS SAMS Conversion/Icon/Vituix_Converter_Icon_R1.ico"))
msg.setText("Files are converted.")
msg.setWindowTitle("Completed!")
retval = msg.exec_()
class MyMainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.setupUi(self)
self.pushButton_hats.clicked.connect(self.hats_conversion)
self.pushButton_sams.clicked.connect(self.sams_conversion)
self.tableWidget.setAcceptDrops(True)
self.tableWidget.viewport().installEventFilter(self)
types = ['text/uri-list']
types.extend(self.tableWidget.mimeTypes())
self.tableWidget.mimeTypes = lambda: types
self.tableWidget.setRowCount(0)
self.tableWidget.dropEvent(self.eventFilter())
def hats_conversion(self):
hats_file = QtWidgets.QFileDialog.getOpenFileName(self, "Select HATS File", "", 'txt (*.txt)')[0]
if hats_file == '':
no_file_selected()
else:
hats_data = pd.read_csv(hats_file, sep="\t", skiprows=3, header=None, on_bad_lines='skip')
txt_name = []
for i in range(1, 148, 2):
txt_name.append(hats_data.loc[0, i])
hats_data = hats_data.drop([0, 1])
hats_data = hats_data.reset_index(drop=True)
# Select folder to save data output
save_folder = QtWidgets.QFileDialog.getExistingDirectory(self, "Select HATS Save Folder")
# iteration variable for lists in following for loop
i = 1
# iterate over all text names, allocate corresponding data, and then save as txt
for j in range(0, len(txt_name)):
test_df_1 = hats_data[0].values.tolist()
test_df_2 = hats_data[i].values.tolist()
test_df_3 = hats_data[i + 1].values.tolist()
export_df = pd.DataFrame(
{'0': test_df_1,
'1': test_df_2,
'2': test_df_3
})
save_file = save_folder + '/' + txt_name[j] + '.txt'
export_df.to_csv(save_file, sep='\t', index=False, na_rep='NaN', header=False)
i = i + 2
process_completed()
def sams_conversion(self):
sams_file = QtWidgets.QFileDialog.getExistingDirectory(self, "Select SAMS Folder")
if sams_file == '':
no_file_selected()
else:
output_folder = QtWidgets.QFileDialog.getExistingDirectory(self, "Select/Create Save Folder")
if output_folder == '':
no_file_selected()
else:
file_names = []
for x in os.listdir(sams_file):
if x.endswith(".txt"):
file_names.append(x)
for i in range(len(file_names)):
newPath = shutil.copy(os.path.join(sams_file, file_names[i]), output_folder)
sams_data = pd.read_csv(newPath, sep="\t", skiprows=5, header=None, on_bad_lines='skip')
sams_data.to_csv(newPath, sep='\t', index=False, na_rep='NaN', header=False)
process_completed()
def eventFilter(self, source, event):
if event.mimeData().hasUrls():
for url in event.mimeData().urls():
self.addFile(url.toLocalFile())
return True
return super().eventFilter(source, event)
def addFile(self, filepath):
row = self.tableWidget.rowCount()
self.tableWidget.insertRow(row)
item = QtWidgets.QTableWidgetItem(filepath)
self.tableWidget.setItem(row, 0, item)
self.tableWidget.resizeColumnToContents(0)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon("D:/Python Projects/HATS SAMS Conversion/Icon/Vituix_Converter_Icon_R1.ico"))
win = MyMainWindow()
win.show()
sys.exit(app.exec_())
UI code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'vituix converter.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# 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(400, 500)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(400, 500))
MainWindow.setMaximumSize(QtCore.QSize(400, 500))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("Icon/Vituix_Converter_Icon_R1.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
self.tableWidget.setSizePolicy(sizePolicy)
self.tableWidget.setMinimumSize(QtCore.QSize(0, 350))
self.tableWidget.setDragEnabled(False)
self.tableWidget.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)
self.tableWidget.setDefaultDropAction(QtCore.Qt.LinkAction)
self.tableWidget.setAlternatingRowColors(True)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.verticalLayout.addWidget(self.tableWidget, 0, QtCore.Qt.AlignVCenter)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.gridLayout.setVerticalSpacing(6)
self.gridLayout.setObjectName("gridLayout")
self.pushButton_hats = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_hats.setMinimumSize(QtCore.QSize(0, 55))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.pushButton_hats.setFont(font)
self.pushButton_hats.setObjectName("pushButton_hats")
self.gridLayout.addWidget(self.pushButton_hats, 0, 0, 1, 1)
self.pushButton_sams = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_sams.setMinimumSize(QtCore.QSize(0, 55))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.pushButton_sams.setFont(font)
self.pushButton_sams.setObjectName("pushButton_sams")
self.gridLayout.addWidget(self.pushButton_sams, 0, 1, 1, 1, QtCore.Qt.AlignVCenter)
self.verticalLayout.addLayout(self.gridLayout)
MainWindow.setCentralWidget(self.centralwidget)
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", "Vituix Converter"))
self.pushButton_hats.setText(_translate("MainWindow", "Vituix HATS"))
self.pushButton_sams.setText(_translate("MainWindow", "Vituix SAMS"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
In order to do this using an event-filter, you need to handle the drag-enter, drag-move and drag-drop events, and accept the events when the mime-data contains urls. The following changes to your example should work as expected:
class MyMainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
...
self.tableWidget.setAcceptDrops(True)
self.tableWidget.viewport().installEventFilter(self)
self.tableWidget.setRowCount(0)
self.tableWidget.setColumnCount(1)
def eventFilter(self, source, event):
if (source is self.tableWidget.viewport() and
(event.type() == QtCore.QEvent.DragEnter or
event.type() == QtCore.QEvent.DragMove or
event.type() == QtCore.QEvent.Drop) and
event.mimeData().hasUrls()):
if event.type() == QtCore.QEvent.Drop:
for url in event.mimeData().urls():
if url.isLocalFile():
self.addFile(url.path())
event.accept()
return True
return super().eventFilter(source, event)
The table has no columns: setItemData() will be ignored if no valid row and column are given:
def addFile(self, filepath):
if not self.tableWidget.columnCount():
self.tableWidget.setColumnCount(1)
# ...
Note that you must always check the event type in an event filter before accessing the event functions, otherwise you'll get an error or even a crash:
def eventFilter(self, source, event):
if event.type() == event.Drop and event.mimeData().hasUrls():
for url in event.mimeData().urls():
self.addFile(url.toLocalFile())
return True
return super().eventFilter(source, event)
Also, remove the following line, which is completely wrong:
self.tableWidget.dropEvent(self.eventFilter())

How to autorefresh pyqt5 table when the data is updated

I want to add one functionality in my application when update is done then data in pyqt5 table should automatically refreshed with the new data in search results. But when I click the buttom, there is nothing happened.
# -*- coding: utf-8 -*-
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import logging
import logging.config
import time
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QIcon('images/icon.png'))
Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
#表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0,0,QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0,1,QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0,2,QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0,3, QTableWidgetItem("温度值"))
self.tableWidget.setItem(0,4, QTableWidgetItem("电流值"))
self.tableWidget.setItem(0,5, QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0,0).setFont(font)
self.tableWidget.item(0,1).setFont(font)
self.tableWidget.item(0,2).setFont(font)
self.tableWidget.item(0,3).setFont(font)
self.tableWidget.item(0,4).setFont(font)
self.tableWidget.item(0,5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.slotStart)
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
def slotStart(self):
#开始按钮不可点击,线程开始
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData()
self.update_data_thread.update_data.connect(self.set_btn)
self.update_data_thread.start()
def set_btn(self):
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):#使用qt自己本身的线程
update_data=QtCore.pyqtSignal()#因为这个信号槽要继承于Qobject,不然会发生没有emit,connect函数的报错,括号里面填写的是发射的数据类型
#print(".............")
def __init__(self):
super().__init__()
def run(self):
cnt = 0
while True:
cnt += 1
self.tableWidget.setItem(2,2,QTableWidgetItem(cnt))
self.update_data.emit() # 发射信号
time.sleep(1)
if __name__ == '__main__':
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Control_system()
ui.setupUi(MainWindow) # 将ui实例绘制到窗口实例上​
desktop = QtWidgets.QApplication.desktop()
x = (desktop.width() - MainWindow.width()) // 2
y = (desktop.height() - MainWindow.height()) // 2
MainWindow.move(x,y)
MainWindow.show()
sys.exit(app.exec())#exec_()方法的作用是“进入程序的主循环直到exit()被调
You cannot and should not modify the GUI directly from another thread, in your case QTableWidget and QTableWidgetItem are part of the GUI so the code: self.tableWidget.setItem(2, 2, QTableWidgetItem(cnt)) is incorrect. What should be done is to send the information to the main thread through elements that are thread-safe such as signals, QEvents, etc.
On the other hand PyQt recommends not modifying the class it generates but creating a widget and using the generated class as an interface(1).
Considering the above the solution is:
import sys
import time
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QtGui.QIcon("images/icon.png"))
Control_system.setStyleSheet(
"QMainWindow{border-image:url(images/background.jpg)}"
)
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
# 表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0, 2, QtWidgets.QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0, 3, QtWidgets.QTableWidgetItem("温度值"))
self.tableWidget.setItem(0, 4, QtWidgets.QTableWidgetItem("电流值"))
self.tableWidget.setItem(0, 5, QtWidgets.QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0, 0).setFont(font)
self.tableWidget.item(0, 1).setFont(font)
self.tableWidget.item(0, 2).setFont(font)
self.tableWidget.item(0, 3).setFont(font)
self.tableWidget.item(0, 4).setFont(font)
self.tableWidget.item(0, 5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
#QtCore.pyqtSlot()
def slotStart(self):
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData(self)
self.update_data_thread.dataChanged.connect(self.onDataChanged)
self.update_data_thread.start()
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while True:
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
if __name__ == "__main__":
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
w = Control_system()
w.show()
sys.exit(app.exec_())
Update:
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
self.pushButton_2.clicked.connect(self.slotStop)
#QtCore.pyqtSlot()
def slotStart(self):
# ...
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
#QtCore.pyqtSlot()
def slotStop(self):
self.update_data_thread.requestInterruption()
self.update_data_thread.quit()
self.update_data_thread.wait()
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while not self.isInterruptionRequested(): # <---
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
(1) Using the Generated Code

How to Find Words and Go to Line in QScintilla Editor?

I would like to create a function for searching for words and highlight them in Qscintilla editor and another function to go to specific line in the editor.
I know these functions works in QPlainTextEdit but since I am learning Qscintilla and most of the documents are written in C++, it's difficult for me to understand and the methods are quite different in Scintilla.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *
#from PyQt5.QtCore import *
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.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.textEdit = QsciScintilla(self.centralwidget)
self.textEdit.setObjectName("textEdit")
self.gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuSearch = QtWidgets.QMenu(self.menubar)
self.menuSearch.setObjectName("menuSearch")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen = QtWidgets.QAction(MainWindow)
self.actionOpen.setObjectName("actionOpen")
self.actionSave = QtWidgets.QAction(MainWindow)
self.actionSave.setObjectName("actionSave")
self.actionExit = QtWidgets.QAction(MainWindow)
self.actionExit.setObjectName("actionExit")
self.actionFind = QtWidgets.QAction(MainWindow)
self.actionFind.setObjectName("actionFind")
self.actionWord_Count = QtWidgets.QAction(MainWindow)
self.actionWord_Count.setObjectName("actionWord_Count")
self.actionNew = QtWidgets.QAction(MainWindow)
self.actionNew.setObjectName("actionNew")
self.menuFile.addAction(self.actionNew)
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionSave)
self.menuFile.addAction(self.actionExit)
self.menuSearch.addAction(self.actionFind)
self.menuSearch.addAction(self.actionWord_Count)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuSearch.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuSearch.setTitle(_translate("MainWindow", "Search"))
self.actionOpen.setText(_translate("MainWindow", "Open"))
self.actionOpen.setShortcut(_translate("MainWindow", "Ctrl+O"))
self.actionSave.setText(_translate("MainWindow", "Save"))
self.actionSave.setShortcut(_translate("MainWindow", "Ctrl+S"))
self.actionExit.setText(_translate("MainWindow", "Exit"))
self.actionExit.setShortcut(_translate("MainWindow", "Ctrl+Q"))
self.actionFind.setText(_translate("MainWindow", "Find"))
self.actionFind.setShortcut(_translate("MainWindow", "Ctrl+F"))
self.actionWord_Count.setText(_translate("MainWindow", "Go to Line"))
self.actionNew.setText(_translate("MainWindow", "New"))
self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N"))
class Ui_Dock_Find(object):
def setupUi(self, Dock_Find):
Dock_Find.setObjectName("Dock_Find")
Dock_Find.resize(320, 65)
Dock_Find.setMinimumSize(QtCore.QSize(320, 65))
font = QtGui.QFont()
font.setPointSize(10)
Dock_Find.setFont(font)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("Ok.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dock_Find.setWindowIcon(icon)
self.dockWidgetContents = QtWidgets.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.serachLabel = QtWidgets.QLabel(self.dockWidgetContents)
self.serachLabel.setGeometry(QtCore.QRect(10, 10, 71, 16))
self.serachLabel.setObjectName("serachLabel")
self.findLine = QtWidgets.QLineEdit(self.dockWidgetContents)
self.findLine.setGeometry(QtCore.QRect(80, 10, 151, 20))
self.findLine.setObjectName("findLine")
self.findButton = QtWidgets.QPushButton(self.dockWidgetContents)
self.findButton.setGeometry(QtCore.QRect(240, 10, 75, 23))
self.findButton.setObjectName("findButton")
Dock_Find.setWidget(self.dockWidgetContents)
self.retranslateUi(Dock_Find)
QtCore.QMetaObject.connectSlotsByName(Dock_Find)
def retranslateUi(self, Dock_Find):
_translate = QtCore.QCoreApplication.translate
Dock_Find.setWindowTitle(_translate("Dock_Find", "Find"))
self.serachLabel.setText(_translate("Dock_Find", "Search For:"))
self.findButton.setText(_translate("Dock_Find", "Find"))
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
#Defining Menu Actions
self.actionNew.triggered.connect(self.newFile)
self.actionOpen.triggered.connect(self.openFile)
#self.actionSave.triggered.connect(self.saveFile)
#self.actionExit.triggered.connect(self.exitFile)
self.actionFind.triggered.connect(self.findWord)
self.actionWord_Count.triggered.connect(self.gotoLine)
self.showMaximized()
def newFile(self):
self.textEdit.clear()
def openFile(self):
filename = QFileDialog.getOpenFileName(self, 'Open File', ".","(*.txt *.py *.log *.csv)")
if filename[0]:
#wordcounts = Counter()
with open(filename[0], 'rt') as fp:
for line in fp:
#wordcounts.update(line.split())
data = fp.read()
self.textEdit.setText(data)
def saveFile(self):
filename = QFileDialog.getSaveFileName(self, 'Save File', ".", "(*.txt)")
if filename[0]:
f = open(filename[0], 'wt')
with f:
text = self.textEdit.toPlainText()
f.write(text)
QMessageBox.about(self, "Save File", "File Saved Successfully")
def exitFile(self):
choice = QMessageBox.question(self, 'Close', "Do you want to close?", QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
self.saveFile()
self.close()
else:
pass
def findWord(self):
self.dock = Dock_Find()
self.addDockWidget(Qt.TopDockWidgetArea, self.dock)
self.dock.show()
def handleFind():
word = self.dock.findLine.text()
if self.textEdit.SCI_FINDTEXT(self.textEdit.SCFIND_WHOLEWORD(), word):
self.textEdit.SCFIND_WHOLEWORD(word)
else:
self.textEdit.SCFIND_WHOLEWORD(word)
return
self.dock.findButton.clicked.connect(handleFind)
def gotoLine(self):
window = GoTo()
window.show()
def handleGoTo():
ln = int(window.findText.text())
"""messenger = self.textEdit.SendScintilla()
messenger(self.textEdit.SCI_SETTARGETSTART, 0)
messenger(self.textEdit.SCI_SETTARGETEND, len(self.textEdit))
pos = messenger(self.textEdit.SCI_SEARCHINTARGET, len("ln"), "ln")
print(pos)"""
linecursor = self.textEdit.wordAtLineIndex(ln, self.textEdit.getCursorPosition()[1])
print(linecursor)
self.textEdit.SCI_GOTOPOS(window.findText.text())
window.hide()
window.findButton.clicked.connect(handleGoTo)
class Dock_Find(QtWidgets.QDockWidget, Ui_Dock_Find):
def __init__(self, parent=None):
super(Dock_Find, self).__init__(parent)
self.setupUi(self)
self.findLine.setPlaceholderText("Type Here")
class GoTo(QDialog):
def __init__(self):
super(GoTo, self).__init__()
self.initUI()
self.setWindowTitle("GoTo")
icon = QIcon()
icon.addPixmap(QPixmap(":/image/graphy_100px.png"), QIcon.Normal, QIcon.Off)
self.setWindowIcon(icon)
def initUI(self):
self.lb1 = QLabel("Go To Line:", self)
self.lb1.setStyleSheet("font-size: 15px")
self.lb1.move(10, 10)
self.findText = QLineEdit(self)
self.findText.move(10, 40)
self.findText.resize(200, 20)
self.findText.setPlaceholderText('Type the line number')
self.findText.setClearButtonEnabled(True)
self.findText.setInputMask("9999999999") #For allowing up to number digit only as input
self.findButton = QPushButton('GO', self)
self.findButton.move(220, 40)
if __name__ == '__main__':
app = QApplication(sys.argv)
QApplication.setStyle(QStyleFactory.create('Fusion'))
myGUI = MainWindow()
sys.exit(app.exec_())
I don't understand how to implement these two functions and I have been trying, but no positive result for finding the word. However for second function, I can print the word which starts with the line number but I want to highlight that word with line number when the function go to line is searched.

TAB key is not working in my code in PYQT5 and Python

What I need from the program is, once I press the TAB from the keyboard, should move to the next field and execute specific function.
The function in the first field is 'ID'(digits) is taken from the user as input. Then, after I press the TAB should extract specific digits, these digits are the 'Birth-date'.
By the 'push-button' is working fine. However, by the tab key is not working and through errors. Please see the code and the image.
I am using PYQT5 and Python 3.7.
Form image
See the for image in this link:
The code
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.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(282, 130, 181, 41))
self.lineEdit.setObjectName("lineEdit")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(216, 140, 51, 20))
self.Handel_Buttons()
self.keyPressEvent()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "ID"))
self.label_2.setText(_translate("MainWindow", "D.O.B"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
def Handel_Buttons(self):
self.pushButton.clicked.connect(self.ID)
def keyPressEvent(self):
print('HI')
if QtCore.Qt.Key_Tab:
self.ID()
def ID(self):
number = self.lineEdit.text()
#number = '279121100762'
#print(int(number[5]))
digit = int(number[5])
digit1 = int(number[6])
digit2 = int(number[3])
digit3 = int(number[4])
digit4 = int(number[1])
digit5 = int(number[2])
#self.textBrowser.append(str[digit,digit1])
self.textBrowser.append ('%d%d/%d%d/19%d%d' % (digit, digit1,digit2,digit3,digit4,digit5))
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_())
Many thanks,
The code you provide can not be executed so I take the time to create it from scratch. The basic idea is to intercept the events of the QLineEdit through an eventFilter:
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.id_le = QtWidgets.QLineEdit("279121100762")
self.id_le.installEventFilter(self)
self.dob_le = QtWidgets.QLineEdit()
btn = QtWidgets.QPushButton(
text="Press me",
clicked=self.conversion
)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QFormLayout(central_widget)
lay.addRow("ID", self.id_le)
lay.addRow("D.O.B", self.dob_le)
lay.addRow(btn)
def eventFilter(self, obj, event):
if self.id_le == obj and event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Tab:
QtCore.QTimer.singleShot(0, self.conversion)
return super(MainWindow, self).eventFilter(obj, event)
def conversion(self):
id_value = self.id_le.text()
if len(id_value) > 7:
text = id_value[1:7]
dt = QtCore.QDateTime.fromString(text, "yyddMM")
if dt.isValid():
self.dob_le.setText(dt.toString("dd/MM/yyyy"))
return
print("Invalid conversion")
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

How to switch between two windows in python using PyQt

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

Categories

Resources