def new_room_dialog(self, db): ui = Ui_Room() new_rm = QDialog() ui.setupUi(new_rm) model = QSqlTableModel(new_rm, db) #Threading thrd = QThreadPool().globalInstance() hlist = ['Reserv. ID','Customer ID','Room #','From','To','Discount','Extension','Net Total'] worker = TableWorker(update_table("CurrentReservation", hlist, ui.tableView, db, model, where=f"RmNumber={ui.lineEdit.text()}")) #We pass a function for the worker to execute thrd.tryStart(worker) #Setup Signals and other UI elements ui.lineEdit.setFocus() # TODO find a better signal than textChanged because it sucks bad ui.lineEdit.textChanged.connect(lambda: update_table_onEnter(new_rm, hlist, ui, db, thrd, model)) ui.pushButton_3.clicked.connect(lambda: thrd.tryStart(TableWorker(add_DB(ui, new_rm, db, "Room", [ui.lineEdit.text(),ui.comboBox.currentText(),ui.spinBox.value(),0], "?, ?, ?, ?", [ui.lineEdit,ui.spinBox])))) ui.pushButton_2.clicked.connect(lambda: thrd.tryStart(TableWorker(edit_DB(ui, new_rm, db, "Room", [ui.lineEdit.text(),ui.comboBox.currentText(),ui.spinBox.value(),ui.lineEdit.text()], "Number = ?, Type = ?, Price = ?", "Number", [ui.lineEdit,ui.spinBox])))) ui.pushButton.clicked.connect(lambda: thrd.tryStart(TableWorker(del_DB(ui, new_rm, db, "Room", "Number = ?", [ui.lineEdit.text()], [ui.lineEdit,ui.spinBox])))) new_rm.setWindowTitle('Create, edit, or delete a Room') new_rm.exec()
def new_customer_dialog(self, db): ui = Ui_Customer() new_cust = QDialog() ui.setupUi(new_cust) model = QSqlTableModel(new_cust, db) #Setup Threading thrd = QThreadPool().globalInstance() hlist = ['Customer ID','Name','Phone #','Date of Birth','# Reservations'] worker = TableWorker(update_table("Customer", hlist, ui.tableView, db, model)) #We pass a function for the worker to execute thrd.tryStart(worker) #? Consider using, instead of QSqlQuery, A QSqlTableModel and insert or delete from it ui.lineEdit_2.textEdited.connect(lambda: update_custTable_onEnter(new_cust, hlist, ui, db, thrd, model)) ui.pushButton_3.clicked.connect(lambda: thrd.tryStart(TableWorker(add_DB(ui, new_cust, db, "Customer", [ui.lineEdit_2.text(),ui.lineEdit.text(),ui.spinBox.value(),ui.dateEdit.date().toString("yyyy-MM-dd"),ui.comboBox.currentText(),0], "?,?,?,?,?,?", [ui.lineEdit_2,ui.lineEdit,ui.spinBox,ui.dateEdit])))) ui.pushButton_2.clicked.connect(lambda: thrd.tryStart(TableWorker(edit_DB(ui, new_cust, db, "Customer", [ui.lineEdit_2.text(),ui.lineEdit.text(),ui.spinBox.value(),ui.dateEdit.date().toString("yyyy-MM-dd"),ui.comboBox.currentText(),ui.lineEdit_2.text()], "ID = ?, Name = ?, Phone = ?, DoB = ?, Sex = ?", "ID", [ui.lineEdit_2,ui.lineEdit,ui.spinBox,ui.dateEdit])))) ui.pushButton.clicked.connect(lambda: thrd.tryStart(TableWorker(del_DB(ui, new_cust, db, "Customer", "ID = ?", [ui.lineEdit_2.text()], [ui.lineEdit_2,ui.lineEdit,ui.spinBox,ui.dateEdit])))) ui.lineEdit_2.setText("CTMR" + str(randrange(100, 999, 10))) new_cust.setWindowTitle('Create, edit, or delete a Customer') new_cust.exec()
def new_res_dialog(self, db, mainui, model): ui = Ui_Reservation() new_res = QDialog() ui.setupUi(new_res) thrd = QThreadPool().globalInstance() worker = TableWorker(collect_data(ui, db)) thrd.tryStart(worker) ui.pushButton.clicked.connect(lambda: new_reservation(ui, new_res, db, ui.checkBox.isChecked(), thrd, mainui, model)) ui.lineEdit.setText("RES" + str(randrange(100, 999, 10))) ui.dateEdit.setDate(ui.dateEdit.date().currentDate()) ui.dateEdit_2.setDate(ui.dateEdit.date().currentDate()) ui.checkBox.stateChanged.connect(ui.spinBox.setEnabled) new_res.setWindowTitle('Create, edit, or delete a Reservation') new_res.exec()
def run(self): # 2. Implement run() ui = Ui_MainWindow() window = QMainWindow() version = self.build_settings['version'] ui.setupUi(window) window.setWindowTitle("HotelManagementSystem v" + version) #Setup Charts for isolated UI editing ui.chartView = QtChart.QChartView(window) ui.chartView_2 = QtChart.QChartView(window) ui.gridLayout_3 = QtWidgets.QGridLayout(ui.groupBox_2) ui.gridLayout_3.addWidget(ui.chartView, 0, 0, 1, 1) ui.gridLayout_4 = QtWidgets.QGridLayout(ui.groupBox_3) ui.gridLayout_4.addWidget(ui.chartView_2, 0, 0, 1, 1) window.showMaximized() #Database connection, instead of sqlite3 db = QSqlDatabase('QSQLITE') db.setDatabaseName(self.get_resource('hotel.db')) model = QSqlTableModel(self.app, db) #Threading thrd = QThreadPool().globalInstance() thrd.setExpiryTimeout(5) hlist = ['Reserv. ID','Customer ID','Room #','From','To','Discount','Extension','Net Total'] worker = TableWorker(update_table("CurrentReservation", hlist, ui.current_res, db, model)) #We pass a function for the worker to execute thrd.tryStart(worker) #Setup Signals ui.newRes.triggered.connect(lambda: self.new_res_dialog(db, ui, model)) ui.newRoom.triggered.connect(lambda: self.new_room_dialog(db)) ui.newService.triggered.connect(lambda: self.new_srv_dialog(db)) ui.newCustomer.triggered.connect(lambda: self.new_customer_dialog(db)) ui.cancelRes.triggered.connect(lambda: self.new_cancel_dialog(window, db, ui.current_res.currentIndex(), thrd, model, hlist, ui.current_res)) #TODO Add new dialog for adding/deleting services to a current Reservation ui.current_res.doubleClicked.connect(lambda: self.new_addservice_dialog(window, db, ui.current_res.currentIndex(), thrd)) return self.app.exec_() # 3. End run() with this line
def new_srv_dialog(self, db): #Setup UI ui = Ui_Service() new_srv = QDialog() ui.setupUi(new_srv) model = QSqlTableModel(new_srv, db) #Setup Threading thrd = QThreadPool().globalInstance() worker = TableWorker(update_table("Service", ['Service ID','Name','Price'], ui.tableView, db, model)) #We pass a function for the worker to execute thrd.tryStart(worker) #Setup Signals and other UI elements ui.pushButton.clicked.connect(lambda: thrd.tryStart(TableWorker(add_DB(ui, new_srv, db, "Service", [ui.lineEdit_2.text(),ui.lineEdit.text(),ui.doubleSpinBox.value()], "?,?,?", [ui.lineEdit_2,ui.lineEdit,ui.doubleSpinBox])))) ui.pushButton_2.clicked.connect(lambda: thrd.tryStart(TableWorker(edit_DB(ui, new_srv, db, "Service", [ui.lineEdit_2.text(),ui.lineEdit.text(),ui.doubleSpinBox.value(),ui.lineEdit_2.text()], "ID = ?, Name = ?, Price = ?", "ID", [ui.lineEdit_2,ui.lineEdit,ui.doubleSpinBox])))) ui.pushButton_3.clicked.connect(lambda: thrd.tryStart(TableWorker(del_DB(ui, new_srv, db, "Service", "ID = ?", [ui.lineEdit_2.text()], [ui.lineEdit_2,ui.lineEdit,ui.doubleSpinBox])))) #When an item in the tableView is selected update lineEdit and lineEdit_2 for better workflow #You can just repeat the connect() method and it wouldn't override the previous one ui.tableView.clicked.connect(lambda index: ui.lineEdit_2.setText(index.siblingAtColumn(0).data())) ui.tableView.clicked.connect(lambda index: ui.lineEdit.setText(index.siblingAtColumn(1).data())) ui.tableView.clicked.connect(lambda index: ui.doubleSpinBox.setValue(index.siblingAtColumn(2).data())) ui.lineEdit_2.setText("SRVC" + str(randrange(100, 999, 10))) #execute new_srv.setWindowTitle('Create, edit, or delete a Service') new_srv.exec()
class WaveformGraphWidget(QWaveformGraph, Ui_waveformGraph): newBkgSignal = pyqtSignal() def __init__(self, parent=None): """ Notes: Needs a newDataSignal to be defined from the parent using self.connect_attr """ super(WaveformGraphWidget, self).__init__( parent=parent ) # passing parent here is important so that widget is properly displayed in parent widget. self.setupUi(self) try: self.threadpool = self.parent().threadpool except AttributeError: self.threadpool = QThreadPool(maxThreadCount=4) print('Threadpool with {} threads started.'.format( self.threadpool.maxThreadCount())) # epics PV setup self.pv = PV(config.DEFAULT_CHANNEL) self.channelEdit.setText(config.DEFAULT_CHANNEL) self.channelEdit.returnPressed.connect(self.change_pv) # graph (using remote lead to problems with QObjects (cant be pickled)) self.wfPlot = pg.PlotWidget() self.pgLayout.addWidget(self.wfPlot) self.wfCurve = utils.initialize_line_plot(self.wfPlot, color=config.COLORS[0]) self.wfFit = utils.initialize_line_plot(self.wfPlot, color=config.COLORS[1]) # self.view = pg.widgets.RemoteGraphicsView.RemoteGraphicsView() # self.wfPlot = self.view.pg.PlotItem() # self.pgLayout.addWidget(self.view) self.lr = pg.LinearRegionItem([0, 100]) self.lr.setZValue(-10) self.wfPlot.addItem(self.lr) self.lr.sigRegionChangeFinished.connect(self.get_roi) # background function self.new_bkg() self.bkgEdit.returnPressed.connect(self.new_bkg) return def connect_attr(self, name, attr): setattr(self, name, attr) return @pyqtSlot() def change_pv(self): self.pv = PV(self.channelEdit.text()) return @pyqtSlot() def get_roi(self): self.roi = np.round(self.lr.getRegion()).astype(int) return self.roi @pyqtSlot() def get_data(self): self.worker = GetWfWorker(self.pv, bkg_fun=self.bkg_fun, signal=self.newDataSignal) self.threadpool.tryStart( self.worker ) # skip (no queuing) if no thread available (if rate is too high) # self.worker.signals.signal.connect(self.display_data) return @pyqtSlot(dict) def display_data_fit(self, data_dict): data = data_dict['data'] fit = data_dict['fit'] # print(data.shape) self.wfCurve.setData(data[0], data[1]) # self.wfPlot.plot(data[0],data[1], clear=True) if fit is not None: self.wfFit.setData(fit[0], fit[1]) return @pyqtSlot() def new_bkg(self): bkg_idx = int(self.bkgEdit.text()) if (bkg_idx <= 0) or (bkg_idx is None): self.bkg_fun = lambda wf: 0 print('Background subtraction removed.') else: self.bkg_fun = lambda wf: utils.background(wf, bkg_idx=bkg_idx) print('Background subtraction updated.') self.newBkgSignal.emit() return
class svd_interface(pydm.Display): displaySignal = pyqtSignal(dict) def __init__(self, parent=None, args=None, macros=None): self.threadpool = QThreadPool( maxThreadCount=12) # should be before super.__init__. Why? print('Threadpool with {} threads.'.format( self.threadpool.maxThreadCount())) super(svd_interface, self).__init__(parent=parent, args=args, macros=macros) # for l in self.__dir__(): # if 'waveform' in l: # print(l) self._ana_count = 0 # Signals for workers (multitreading) self.newDataSignal = WorkerSignal_ndarray() self.newFitSignal = WorkerSignal_dict() # connect stuff together self.waveformGraph.connect_attr('newDataSignal', self.newDataSignal) self.regressorWidget.connect_attr('graph', self.waveformGraph) # Setup the analysis timer self.timer = QTimer(interval=int(1 / config.RATE * 1000)) # timer in ms self.timer.timeout.connect(self.waveformGraph.get_data) self.timer.start() # Processing self.newDataSignal.signal.connect(self.fit_data) self.newFitSignal.signal.connect(self.trigger_display) # Stripcharts self.stripchartsView.make_stripcharts(2, useRemote=False) self.stripcharts = Svd_stripchart(stripchartsView=self.stripchartsView) self.regressorWidget.newRegressorSignal.connect( self.stripcharts.make_ravgs) self.newFitSignal.signal.connect(self.stripcharts.update_ravgs) # self.timer.timeout.connect(self.stripchartsView.update_test) # Update display self.displaySignal.connect(self.waveformGraph.display_data_fit) self.displaySignal.connect(self.stripcharts.update_stripchartsView) return def ui_filename(self): return 'main.ui' def ui_filepath(self): return path.join(path.dirname(path.realpath(__file__)), self.ui_filename()) @pyqtSlot(np.ndarray) def fit_data(self, data): self.worker = FitWfWorker(data=data, roi=self.waveformGraph.get_roi(), regressor=self.regressorWidget.regressor, signal=self.newFitSignal) self.threadpool.tryStart(self.worker) return @pyqtSlot(dict) def trigger_display(self, data_dict): if self._ana_count < config.DISPLAY_RATE_RATIO: self._ana_count += 1 else: self._ana_count = 0 self.displaySignal.emit(data_dict) # def make_stripchart(self, n=0, ts_len=100, alpha=None, n_pulse=1): # self.stripcharts = Svd_stripchart( # n=n, ts_len=ts_len, alpha=alpha, n_pulse=n_pulse, stripchartsView=self.stripchartsView) # return def print_time(self): time = QDateTime.currentDateTime() print(time.toString('yyyy-MM-dd hh:mm:ss dddd')) return # if __name__ == '__main__': # app = QApplication(sys.argv) # thisapp = svd_interface() # thisapp.show() # sys.exit(app.exec_())
class MainWindow(QMainWindow): """ You can use @pyqtSlot(int) syntax (with parameters), or you can pass this, but it make code more readable. Вы можете использовать синтаксис объявления слотов @pyqtSlot(int) с указанием типа передаваемых значений, или опустить его вовсе, однако это делает код нагляднее и позволяет быстро понять, что слот, а что - функция. """ def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self._counter = 0 self.init_ui() self._threadpool = QThreadPool() #self._threadpool = QtCore.QThreadPool.globalInstance() #self._threadpool.setMaxThreadCount(2) print("Multithreading with maximum {} threads" .format(self._threadpool.maxThreadCount())) self._timer = QTimer() self._timer.setInterval(1000) self._timer.timeout.connect(self.recurring_timer) self._timer.start() def init_ui(self): layout = QVBoxLayout() self._label = QLabel("Start") b = QPushButton("Start QRunnable") b.pressed.connect(self.start_new_runnable) layout.addWidget(self._label) layout.addWidget(b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) @pyqtSlot(int) def thread_progress_fn(self, n): print("{}% done".format(n)) @pyqtSlot(object) def thread_print_output(self, s): print('Result: {}'.format(s)) @pyqtSlot() def thread_complete(self): print("QRunnable worker COMPLETE!") @pyqtSlot(tuple) def thread_error(self, err): QMessageBox.warning(self, "Warning!", err[1], QMessageBox.Ok) print('Error {}\n{}'.format(err[1], err[2])) @pyqtSlot() def start_new_runnable(self): # Pass the function to execute worker = Worker(1, debug=True) # Any other args, kwargs are passed to the run function worker.signals.result.connect(self.thread_print_output) worker.signals.finished.connect(self.thread_complete) worker.signals.progress.connect(self.thread_progress_fn) worker.signals.error.connect(self.thread_error) worker.setAutoDelete(True) # Execute (tryStart() better than start() ) if self._threadpool.tryStart(worker) is False: print("Can't create worker!") QMessageBox.warning(self, "Warning!", "Can't create worker!", QMessageBox.Ok) @pyqtSlot() def recurring_timer(self): self._counter += 1 self._label.setText("Counter: {}".format(self._counter)) print('Active thread count: {}'.format(self._threadpool.activeThreadCount())) def closeEvent(self, event): """Main window closed, override PyQt5 widget function""" print('Try to exit, active thread count: {}'.format(self._threadpool.activeThreadCount())) reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self._threadpool.waitForDone() self._timer.stop() event.accept() else: event.ignore()