class AddDecrementWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # Creating and setting the components and their characteristics size = QSize(400, 250) self.setFixedSize(size) self.main_layout = QVBoxLayout() title: str = centralize_text("Добавить расход продукта") self.title = QLabel(title, parent=self) self.data_layout = QHBoxLayout() self.quantity_layout = QVBoxLayout() self.quantity_title = QLabel("Кол-во:", parent=self) self.quantity_value = QDoubleSpinBox(parent=self) self.quantity_value.setSingleStep(1.0) self.quantity_value.setRange(0.0, 1000000.0) self.quantity_value.setDecimals(3) self.quantity_checker = QCheckBox("На 1 ребёнка", parent=self) self.date_layout = QVBoxLayout() self.date_title = QLabel("Выберите дату:", parent=self) self.today_radio = QRadioButton("Сегодня", parent=self) self.today_radio.setChecked(True) self.today_radio.clicked.connect(self.disable_date_edit) self.otherday_radio = QRadioButton("Другой день", parent=self) self.otherday_radio.clicked.connect(self.enable_date_edit) self.otherday_edit = QDateEdit(date=date.today(), parent=self) self.otherday_edit.setDisabled(True) self.button = QPushButton("Добавить &расход", parent=self) # Locating the components in the widget self.setLayout(self.main_layout) self.main_layout.addWidget(self.title) self.main_layout.addLayout(self.data_layout) self.data_layout.addLayout(self.quantity_layout) self.quantity_layout.addWidget(self.quantity_title) self.quantity_layout.addWidget(self.quantity_value) self.quantity_layout.addWidget(self.quantity_checker) self.data_layout.addLayout(self.date_layout) self.date_layout.addWidget(self.date_title) self.date_layout.addWidget(self.today_radio) self.date_layout.addWidget(self.otherday_radio) self.date_layout.addWidget(self.otherday_edit) self.main_layout.addWidget(self.button) def enable_date_edit(self): # The user would choose another date self.otherday_edit.setEnabled(True) def disable_date_edit(self): # The user chose today self.otherday_edit.setDate(date.today()) self.otherday_edit.setDisabled(True)
class MainWindow(PageWindow): def __init__(self, dir): super().__init__() self.storage = firebase.screening() try: self.ser = serial.Serial(port='COM3', baudrate=115200, bytesize=8, parity='N', stopbits=1) except Exception as ex: message = template.format(type(ex).__name__, ex.args) print(message) self.dirname = dir self.seperator_vertical = QVSeperationLine() self.seperator_horizontal = QHSeperationLine() self.initUI() self.setWindowTitle("MainWindow") self.overlay = Overlay(self.centralWidget()) self.available_cameras = QCameraInfo.availableCameras() if not self.available_cameras: pass #quit self.select_camera(0) def initUI(self): self.homeUI() def homeUI(self): self.preview_widget = QWidget() self.footer_widget = QWidget() self.grid_widget = QWidget() self.graph_widget = QWidget() self.home = True self.viewfinder = QCameraViewfinder() self.viewfinder.show() self.setCentralWidget(self.viewfinder) self.cap = None # -capture <-> +cap self.horizontalLayout = QHBoxLayout() self.horizontalLayout2 = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.verticalLayout = QVBoxLayout() self.chartLayout = QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.image_label = QLabel() self.image_label.setText("") self.image_label.setObjectName("image_label") self.image_label.setStyleSheet("QLabel { margin-right:4px; }") self.temp = QLabel() self.temp.setText("TEMPERATURE : ") self.temp.setObjectName("temp") self.temp.setFont(QFont("Gadugi", 15, weight=QFont.Bold)) #self.temp.setAlignment(QtCore.Qt.AlignCenter) self.temp_reading = QLabel() self.temp_reading.setText("READING...") self.temp_reading.setObjectName("temp_reading") self.temp_reading.setFont(QFont("Gadugi", 15, weight=QFont.Bold)) #self.temp_reading.setAlignment(QtCore.Qt.AlignCenter) self.temp2 = QLabel() self.temp2.setText("ROOM READING : ") self.temp2.setFont(QFont("Gadugi", 15, weight=QFont.Bold)) self.temp2.setObjectName("temp2") #self.temp2.setAlignment(QtCore.Qt.AlignCenter) self.temp2_reading = QLabel() self.temp2_reading.setText("READING...") self.temp2_reading.setFont(QFont("Gadugi", 15, weight=QFont.Bold)) #self.temp2_reading.setAlignment(QtCore.Qt.AlignCenter) self.temp2_reading.setObjectName("temp2_reading") self.image_label.setScaledContents(True) self.matplotlibWidget = MatplotlibWidget(self) self.threadSample = ThreadSample(self) self.threadSample.newSample.connect(self.on_threadSample_newSample) self.threadSample.finished.connect(self.on_threadSample_finished) self.gridLayout = QGridLayout(self) self.gridLayout.addWidget(self.temp, 0, 0, 1, 1) self.gridLayout.addWidget(self.temp_reading, 0, 1, 1, 3) self.gridLayout.addWidget(self.temp2, 2, 0, 1, 1) self.gridLayout.addWidget(self.temp2_reading, 2, 1, 1, 3) self.clock(self.gridLayout, 3, 0, 3, 3) self.grid_widget.setLayout(self.gridLayout) self.grid_widget.setMinimumHeight(250) self.grid_widget.setMaximumHeight(250) self.grid_widget.setMinimumWidth(600) self.grid_widget.setMaximumWidth(600) self.horizontalLayout.addWidget(self.image_label) #self.horizontalLayout.addWidget(self.seperator_vertical) self.horizontalLayout.addWidget(self.graph_widget) self.preview_widget.setLayout(self.horizontalLayout) self.preview_widget.setMinimumHeight(200) self.preview_widget.setMaximumHeight(200) self.preview_widget.setMinimumWidth(600) self.preview_widget.setMaximumWidth(600) # self.chartLayout.addWidget(self.matplotlibWidget) # self.graph_widget.setLayout(self.chartLayout) self.graph_widget.setMinimumHeight(250) self.graph_widget.setMaximumHeight(250) self.graph_widget.setMinimumWidth(250) self.graph_widget.setMaximumWidth(250) self.horizontalLayout2.addWidget(self.grid_widget) # self.horizontalLayout2.addWidget(self.seperator_vertical) #self.horizontalLayout2.addWidget(self.clock) #self.clock(self.horizontalLayout2) self.footer_widget.setLayout(self.horizontalLayout2) self.footer_widget.setMinimumHeight(250) self.footer_widget.setMaximumHeight(250) self.footer_widget.setMinimumWidth(600) self.footer_widget.setMaximumWidth(600) self.verticalLayout.addWidget(self.preview_widget) self.verticalLayout.addWidget(self.seperator_horizontal) self.verticalLayout.addWidget(self.footer_widget) #self.verticalLayout.addWidget(self.image_label2) self.timer = QTimer(self, interval=5) self.timer.timeout.connect(self.update_frame) self._image_counter = 0 centralWidget = QWidget(self) self.setCentralWidget(centralWidget) self.centralWidget().setLayout(self.verticalLayout) self.start_webcam() self.update_frame() # self.setCentralWidget(self.scroll) self.setGeometry(300, 300, 400, 700) thread = Thread(target=self.read_temp) thread.daemon = True thread.start() def select_camera(self, i): self.camera = QCamera(self.available_cameras[i]) self.camera.setViewfinder(self.viewfinder) self.camera.setCaptureMode(QCamera.CaptureStillImage) self.camera.error.connect( lambda: self.alert(self.camera.errorString())) self.camera.start() self.capture = QCameraImageCapture(self.camera) self.capture.error.connect(lambda i, e, s: self.alert(s)) self.capture.imageCaptured.connect(lambda d, i: self.statusmessage( "Image %04d captured" % self.save_seq)) self.current_camera_name = self.available_cameras[i].description() self.save_seq = 0 def read_temp(self): temp = [] while True: self.ser.write(b'0x55,0xAA,5,1,4') response = self.ser.readline() print(str(response)) if 'body' in str(response): temp.append(str(response)) #print("temp-"+str(response)) #print(temp) elif 'Vbat' in str(response): if len(temp) != 0: temp[1] = temp[1].replace('b\'T body =', '') temp[1] = temp[1].replace("\\r\\n'", '') temp[0] = temp[0].replace('b\'T body =', '') temp[0] = temp[0].replace("compensate\\r\\n'", '') self.findFaces('-'.join(temp)) self.update_label(temp[0], temp[1], '12') temp = [] time.sleep(1) # start = time.clock() # while True: # if True: # if True: # temp.append(str(random.randint(0,100))) # temp.append(str(random.randint(0,100))) # self.overlay.show() # self.findFaces('-'.join(temp)) # self.update_label(temp[0],temp[1],'12') # self.overlay.hide() # print("Done-"+ ' '.join(temp)) # temp = [] # time.sleep(1) def statusmessage(self, msg): self.statusBar().showMessage(msg) def update_label(self, temp1, temp2, time): print(temp1) temp2 = self.getTemp(str(temp2)) temp1 = self.getTemp(str(temp1)) if temp2 >= 36.1 and temp2 <= 37.2: pal = self.temp_reading.palette() pal.setColor(QPalette.WindowText, QColor("green")) self.temp_reading.setPalette(pal) else: pal = self.temp_reading.palette() pal.setColor(QPalette.WindowText, QColor("red")) self.temp_reading.setPalette(pal) # if temp2>=36.1 and temp2<=37.2: # pal = self.temp_reading.palette() # pal.setColor(QPalette.WindowText, QColor("black")) # self.temp2_reading.setPalette(pal) # else: # pal = self.temp_reading.palette() # pal.setColor(QPalette.WindowText, QColor("black")) # self.temp2_reading.setPalette(pal) self.temp_reading.setText(str(temp2) + " °C") self.temp2_reading.setText(str(temp1) + " °C") #self.temp2_reading.setColor(QPalette.WindowText, QtGui.QColor("red")) def getTemp(self, inp): temp = re.findall(r"[-+]?\d*\.\d+|\d+", inp) temp = ''.join(temp) if temp == '': return 0 else: return float(temp) def filter(self, text): text = text.replace('bTbody', 'body') text = text.replace('\'', '') text = text.replace('\\r\n\'b\'Tbody', '-') text = text.replace('\\r', '') text = text.replace('\r', '') text = text.replace('\\xa8', '') text = text.replace('\\xa1\\xe6', '') text = text.replace('\\n', '-') text = text.replace(' ', '') text = text.replace(', ', ',') text = text.replace('=', '_') text = text.replace(',', '-') return text def alert(self, s): """ Handle errors coming from QCamera dn QCameraImageCapture by displaying alerts. """ err = QErrorMessage(self) err.showMessage(s) @QtCore.pyqtSlot() def start_webcam(self): if self.cap is None: self.cap = cv2.VideoCapture(0) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) self.timer.start() def start_cam(self): self.cap.open(0) def stop_webcam(self): self.cap.release() def closeEvent(self, event): print("closing PyQtTest") self.cap.close() @QtCore.pyqtSlot() def update_frame(self): if self.cap.isOpened(): ret, image = self.cap.read() #self.face_detect(image,file_name) simage = cv2.flip(image, 1) self.displayImage(image, True) def findFaces(self, file_name): face_detect = True while face_detect: if self.cap.isOpened(): ret, frame = self.cap.read() face_locations = fl(frame) print("I found {} face(s) in this photograph.".format( len(face_locations))) #self.statusmessage("I found {} face(s) in this photograph.".format(len(face_locations))) for face_location in face_locations: face_detect = False # Print the location of each face in this image top, right, bottom, left = face_location print( "A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}" .format(top, left, bottom, right)) # ts = time.time() # You can access the actual face itself like this: face_image = frame[top - 100:bottom + 100, left - 100:right + 100] ts = datetime.now().strftime('%Y_%m_%d-%H_%M_%S') cv2.imwrite( os.path.abspath( os.path.join(self.dirname, (ts + '-' + file_name + '.jpg'))), face_image) self.storage.upload(self.dirname, (ts + '-' + file_name + '.jpg')) def face_detect(self, file_name): face_locations = [] face_encodings = [] face_names = [] process_this_frame = True i = 0 face_detect = True # Resize frame of video to 1/4 size for faster face recognition processing while face_detect: ret, frame = self.cap.read() #self.face_detect(image,file_name) #simage = cv2.flip(image, 1) small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Only process every other frame of video to save time if process_this_frame: # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations( rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: # See if the face is a match for the known face(s) face_detect = False name = "Unknown" cv2.imwrite( os.path.abspath( os.path.join( self.dirname, (datetime.today().strftime('%Y-%m-%d') + '-' + file_name + '-' + str(++i) + '.png'))), frame) #self.storage.upload(self.dirname,(datetime.today().strftime('%Y-%m-%d')+'-'+file_name+'-'+str(i)+'.png')) i = i + 1 print("I see someone named {}!".format(name)) # # If a match was found in known_face_encodings, just use the first one. # if True in matches: # first_match_index = matches.index(True) # name = known_face_names[first_match_index] # Or instead, use the known face with the smallest distance to the new face process_this_frame = not process_this_frame @QtCore.pyqtSlot() def capture_image(self): if self.cap.isOpened(): flag, frame = self.cap.read() timestamp = time.strftime("%d-%b-%Y-%H_%M_%S") self.save_seq += 1 path = self.dirname # if flag: QtWidgets.QApplication.beep() name = "my_image.jpg" cv2.imwrite( os.path.join( self.dirname, "%s-%04d-%s.jpg" % (self.current_camera_name, self.save_seq, timestamp)), frame) self.alert('Image Store Successfully.') self._image_counter += 1 def displayImage(self, img, window=True): qformat = QImage.Format_Indexed8 if len(img.shape) == 3: if img.shape[2] == 4: qformat = QImage.Format_RGBA8888 else: qformat = QImage.Format_RGB888 outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat) outImage = outImage.rgbSwapped() if window: self.image_label.setStyleSheet(""" QLabel { height:300px !important; } """) self.image_label.setPixmap(QPixmap.fromImage(outImage)) def clock(self, layout, row, col, row_span, col_span): self.verticalLayoutClock = QVBoxLayout(self) self.dateEdit = QDateEdit(self) self.dateEdit.setDisplayFormat("MMM dd yyyy") self.dateEdit.setDisabled(True) self.verticalLayoutClock.addWidget(self.dateEdit) self.timeEdit = QTimeEdit(self) self.timeEdit.setDisplayFormat("hh:mm:ss AP") self.timeEdit.setDisabled(True) self.verticalLayoutClock.addWidget(self.timeEdit) self.updateTime() self.timer = QTimer(self) self.timer.timeout.connect(self.updateTime) self.timer.start(1000) layout.addLayout(self.verticalLayoutClock, row, col, row_span, col_span) @QtCore.pyqtSlot(list) def on_threadSample_newSample(self, sample): self.matplotlibWidget.axis.plot(sample) self.matplotlibWidget.canvas.draw() @QtCore.pyqtSlot() def on_threadSample_finished(self): self.samples += 1 if self.samples <= 2: self.threadSample.start() @QtCore.pyqtSlot() def on_pushButtonPlot_clicked(self): self.samples = 0 self.matplotlibWidget.axis.clear() self.threadSample.start() def updateTime(self): current = QtCore.QDateTime.currentDateTime() self.dateEdit.setDate(current.date()) self.timeEdit.setTime(current.time())
class MainWindow(PageWindow): def __init__(self): super().__init__() #self.ser = serial.Serial(port='COM3', baudrate=115200, bytesize=8, parity='N', stopbits=1) self.seperator_vertical = QVSeperationLine() self.seperator_horizontal = QHSeperationLine() self.initUI() self.setWindowTitle("MainWindow") def initUI(self): self.homeUI() def homeUI(self): self.preview_widget = QWidget() self.footer_widget = QWidget() self.home = True self.viewfinder = QCameraViewfinder() self.viewfinder.show() self.setCentralWidget(self.viewfinder) self.cap = None # -capture <-> +cap self.horizontalLayout = QHBoxLayout() self.horizontalLayout2 = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.verticalLayout = QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.image_label = QLabel() self.image_label.setText("") self.image_label.setObjectName("image_label") self.temp = QLabel() self.temp.setText("Temperature:") self.temp.setObjectName("temp") self.temp_reading = QLabel() self.temp_reading.setText("temp_reading") self.temp_reading.setObjectName("temp_reading") self.temp2 = QLabel() self.temp2.setText("Temperature 2:") self.temp2.setObjectName("temp2") self.temp2_reading = QLabel() self.temp2_reading.setText("Temperature2 Reading") self.temp2_reading.setObjectName("temp2_reading") self.image_label.setScaledContents(True) self.matplotlibWidget = MatplotlibWidget(self) self.threadSample = ThreadSample(self) self.threadSample.newSample.connect(self.on_threadSample_newSample) self.threadSample.finished.connect(self.on_threadSample_finished) self.gridLayout = QGridLayout(self) self.gridLayout.addWidget(self.temp, 0, 0) self.gridLayout.addWidget(self.temp_reading, 0, 1) self.gridLayout.addWidget(self.temp2, 1, 0) self.gridLayout.addWidget(self.temp2_reading, 1, 1) self.horizontalLayout.addWidget(self.image_label) self.horizontalLayout.addWidget(self.seperator_vertical) self.horizontalLayout.addLayout(self.gridLayout) self.preview_widget.setLayout(self.horizontalLayout) self.preview_widget.setMinimumHeight(200) self.preview_widget.setMaximumHeight(200) self.preview_widget.setMinimumWidth(600) self.preview_widget.setMaximumWidth(600) self.horizontalLayout2.addWidget(self.matplotlibWidget) self.horizontalLayout2.addWidget(self.seperator_vertical) #self.horizontalLayout2.addWidget(self.clock) self.clock(self.horizontalLayout2) self.footer_widget.setLayout(self.horizontalLayout2) self.footer_widget.setMinimumHeight(250) self.footer_widget.setMaximumHeight(250) self.footer_widget.setMinimumWidth(600) self.footer_widget.setMaximumWidth(600) self.verticalLayout.addWidget(self.preview_widget) self.verticalLayout.addWidget(self.seperator_horizontal) self.verticalLayout.addWidget(self.footer_widget) #self.verticalLayout.addWidget(self.image_label2) self.timer = QTimer(self, interval=5) self.timer.timeout.connect(self.update_frame) self._image_counter = 0 centralWidget = QWidget(self) self.setCentralWidget(centralWidget) self.centralWidget().setLayout(self.verticalLayout) # self.setCentralWidget(self.scroll) self.setGeometry(300, 300, 400, 700) def read_temp(self): temp = [] while True: self.ser.write(b'0x55,0xAA,5,1,4') response = self.ser.readline() #print(str(response)) if 'body' in str(response): temp.append(str(response)) #print("temp-"+str(response)) #print(temp) elif 'Vbat' in str(response): if len(temp) != 0: print("Done-" + ' '.join(temp)) self.start_webcam() self.update_frame(self.filter(''.join(temp))) temp = [] def filter(self, text): text = text.replace('bTbody', 'body') text = text.replace('\'', '') text = text.replace('\\r\n\'b\'Tbody', '-') text = text.replace('\\r', '') text = text.replace('\r', '') text = text.replace('\\xa8', '') text = text.replace('\\xa1\\xe6', '') text = text.replace('\\n', '-') text = text.replace(' ', '') text = text.replace(', ', ',') text = text.replace('=', '_') text = text.replace(',', '-') return text @QtCore.pyqtSlot() def start_webcam(self): if self.cap is None: self.cap = cv2.VideoCapture(0) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) self.timer.start() def closeEvent(self, event): print("closing PyQtTest") self.cap.close() @QtCore.pyqtSlot() def update_frame(self, file_name): ret, image = self.cap.read() self.face_detect(image, file_name) simage = cv2.flip(image, 1) self.displayImage(image, True) def face_detect(self, image, file_name): frame = image face_locations = [] face_encodings = [] face_names = [] process_this_frame = True i = 0 face_detect = True # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] self.dirname = 'd:' # Only process every other frame of video to save time if process_this_frame: # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: # See if the face is a match for the known face(s) face_detect = False name = "Unknown" cv2.imwrite( os.path.abspath( os.path.join( self.dirname, (datetime.today().strftime('%Y-%m-%d') + '-' + file_name + '-' + str(++i) + '.png'))), frame) #self.storage.upload(self.dirname,(datetime.today().strftime('%Y-%m-%d')+'-'+file_name+'-'+str(i)+'.png')) i = i + 1 print("I see someone named {}!".format(name)) # # If a match was found in known_face_encodings, just use the first one. # if True in matches: # first_match_index = matches.index(True) # name = known_face_names[first_match_index] # Or instead, use the known face with the smallest distance to the new face process_this_frame = not process_this_frame @staticmethod @QtCore.pyqtSlot() def capture_image(self): flag, frame = self.cap.read() timestamp = time.strftime("%d-%b-%Y-%H_%M_%S") self.save_seq += 1 path = self.save_path # if flag: QtWidgets.QApplication.beep() name = "my_image.jpg" cv2.imwrite( os.path.join( self.save_path, "%s-%04d-%s.jpg" % (self.current_camera_name, self.save_seq, timestamp)), frame) self._image_counter += 1 def displayImage(self, img, window=True): qformat = QImage.Format_Indexed8 if len(img.shape) == 3: if img.shape[2] == 4: qformat = QImage.Format_RGBA8888 else: qformat = QImage.Format_RGB888 outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat) outImage = outImage.rgbSwapped() if window: self.image_label.setStyleSheet(""" QLabel { height:300px !important; } """) self.image_label.setPixmap(QPixmap.fromImage(outImage)) def clock(self, layout): self.verticalLayoutClock = QVBoxLayout(self) self.dateEdit = QDateEdit(self) self.dateEdit.setDisplayFormat("MMM dd yyyy") self.dateEdit.setDisabled(True) self.verticalLayoutClock.addWidget(self.dateEdit) self.timeEdit = QTimeEdit(self) self.timeEdit.setDisplayFormat("hh:mm:ss AP") self.timeEdit.setDisabled(True) self.verticalLayoutClock.addWidget(self.timeEdit) self.updateTime() self.timer = QTimer(self) self.timer.timeout.connect(self.updateTime) self.timer.start(1000) layout.addLayout(self.verticalLayoutClock) @QtCore.pyqtSlot(list) def on_threadSample_newSample(self, sample): self.matplotlibWidget.axis.plot(sample) self.matplotlibWidget.canvas.draw() @QtCore.pyqtSlot() def on_threadSample_finished(self): self.samples += 1 if self.samples <= 2: self.threadSample.start() @QtCore.pyqtSlot() def on_pushButtonPlot_clicked(self): self.samples = 0 self.matplotlibWidget.axis.clear() self.threadSample.start() def updateTime(self): current = QtCore.QDateTime.currentDateTime() self.dateEdit.setDate(current.date()) self.timeEdit.setTime(current.time())
class AddIncrementWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # Creating and setting the components and their characteristics size = QSize(400, 370) self.setFixedSize(size) self.main_layout = QVBoxLayout() title: str = centralize_text("Добавление прихода продукта:") self.title = QLabel(title, parent=self) self.data_layout = QHBoxLayout() self.price_quantity_layout = QVBoxLayout() self.price_title = QLabel("Цена:", parent=self) self.price_value = QSpinBox() self.price_value.setValue(0) self.price_value.setRange(0, 1000000) self.price_value.setSingleStep(1000) self.quantity_title = QLabel("Кол-во:", parent=self) self.quantity_value = QDoubleSpinBox(parent=self) self.quantity_value.setSingleStep(1.0) self.quantity_value.setRange(0.0, 1000000.0) self.quantity_value.setDecimals(3) self.agreement_title = QLabel("Информация о доверенности:", parent=self) self.agreement_info = QPlainTextEdit(parent=self) self.date_layout = QVBoxLayout() self.date_title = QLabel("Выберите дату:", parent=self) self.today_radio = QRadioButton("Сегодня", parent=self) self.today_radio.setChecked(True) self.today_radio.clicked.connect(self.disable_date_edit) self.otherday_radio = QRadioButton("Другой день", parent=self) self.otherday_radio.clicked.connect(self.enable_date_edit) self.otherday_edit = QDateEdit(date=date.today(), parent=self) self.otherday_edit.setDisabled(True) self.invoice_title = QLabel("Информация о счёт-фактуре:", parent=self) self.invoice_info = QPlainTextEdit(parent=self) self.button = QPushButton("Добавить &приход", parent=self) # Locating the components in the widget self.setLayout(self.main_layout) self.main_layout.addWidget(self.title) self.main_layout.addLayout(self.data_layout) self.data_layout.addLayout(self.price_quantity_layout) self.price_quantity_layout.addWidget(self.price_title) self.price_quantity_layout.addWidget(self.price_value) self.price_quantity_layout.addWidget(self.quantity_title) self.price_quantity_layout.addWidget(self.quantity_value) self.price_quantity_layout.addWidget(self.agreement_title) self.price_quantity_layout.addWidget(self.agreement_info) self.data_layout.addLayout(self.date_layout) self.date_layout.addWidget(self.date_title) self.date_layout.addWidget(self.today_radio) self.date_layout.addWidget(self.otherday_radio) self.date_layout.addWidget(self.otherday_edit) self.date_layout.addWidget(self.invoice_title) self.date_layout.addWidget(self.invoice_info) self.main_layout.addWidget(self.button) def enable_date_edit(self): # The user would choose another date self.otherday_edit.setEnabled(True) def disable_date_edit(self): # The user chose today self.otherday_edit.setDate(date.today()) self.otherday_edit.setDisabled(True)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.lastyear = int(time.strftime('%Y', time.localtime(time.time()))) - 1 self.in_parameters = {u'datetime': str(self.lastyear) + u'年', u'target_area': u'绍兴市', u'density_cell': u'10', u'density_class': 10, u'day_cell': u'15', u'day_class': 10, u'out_type': u'tiff'} self.setupUi() def setupUi(self): self.setObjectName("MainWindow") self.setFixedSize(1040, 915) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) icon = QIcon() icon.addPixmap(QPixmap('./resource/weather-thunder.png'),QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.centralwidget = QWidget(self) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth()) self.centralwidget.setSizePolicy(sizePolicy) self.centralwidget.setObjectName("centralwidget") self.layoutWidget = QWidget(self.centralwidget) self.layoutWidget.setGeometry(QRect(32, 10, 979, 851)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_5 =QVBoxLayout(self.layoutWidget) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName("verticalLayout_5") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.datetime_label = QLabel(self.layoutWidget) self.datetime_label.setObjectName("datetime_label") self.horizontalLayout.addWidget(self.datetime_label) self.datetime = QDateEdit(self.layoutWidget) self.datetime.setDateTime(QDateTime(QDate(self.lastyear, 1, 1), QTime(0, 0, 0))) self.datetime.setObjectName("datetime") self.horizontalLayout.addWidget(self.datetime) spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem1) self.target_area_label = QLabel(self.layoutWidget) self.target_area_label.setObjectName("target_area_label") self.horizontalLayout.addWidget(self.target_area_label) self.target_area = QComboBox(self.layoutWidget) self.target_area.setObjectName("target_area") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.target_area.addItem("") self.horizontalLayout.addWidget(self.target_area) spacerItem2 = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem2) self.verticalLayout_5.addLayout(self.horizontalLayout) self.tabWidget = QTabWidget(self.layoutWidget) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) self.tabWidget.setSizePolicy(sizePolicy) self.tabWidget.setObjectName("tabWidget") self.density_tab = QWidget() self.density_tab.setObjectName("density_tab") self.verticalLayout_3 =QVBoxLayout(self.density_tab) self.verticalLayout_3.setObjectName("verticalLayout_3") self.verticalLayout_2 =QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout_2 = QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.density_cell_label = QLabel(self.density_tab) self.density_cell_label.setObjectName("density_cell_label") self.horizontalLayout_2.addWidget(self.density_cell_label) self.density_cell = QSpinBox(self.density_tab) self.density_cell.setProperty("value", 10) self.density_cell.setObjectName("density_cell") self.horizontalLayout_2.addWidget(self.density_cell) spacerItem3 = QSpacerItem(40, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem3) self.density_class_label = QLabel(self.density_tab) self.density_class_label.setObjectName("density_class_label") self.horizontalLayout_2.addWidget(self.density_class_label) self.density_class = QSpinBox(self.density_tab) self.density_class.setProperty("value", 10) self.density_class.setObjectName("density_class") self.horizontalLayout_2.addWidget(self.density_class) spacerItem4 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem4) self.density_mxd = QPushButton(self.density_tab) self.density_mxd.setObjectName("density_mxd") self.horizontalLayout_2.addWidget(self.density_mxd) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.density_view = QGraphicsView(self.density_tab) self.density_view.setObjectName("density_view") self.verticalLayout_2.addWidget(self.density_view) self.verticalLayout_3.addLayout(self.verticalLayout_2) self.tabWidget.addTab(self.density_tab, "") self.day_tab = QWidget() self.day_tab.setObjectName("day_tab") self.verticalLayout_4 =QVBoxLayout(self.day_tab) self.verticalLayout_4.setObjectName("verticalLayout_4") self.verticalLayout =QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout_3 =QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.day_cell_label = QLabel(self.day_tab) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.day_cell_label.sizePolicy().hasHeightForWidth()) self.day_cell_label.setSizePolicy(sizePolicy) self.day_cell_label.setObjectName("day_cell_label") self.horizontalLayout_3.addWidget(self.day_cell_label) self.day_cell = QSpinBox(self.day_tab) self.day_cell.setProperty("value", 15) self.day_cell.setObjectName("day_cell") self.horizontalLayout_3.addWidget(self.day_cell) spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem5) self.day_class_label = QLabel(self.day_tab) self.day_class_label.setObjectName("day_class_label") self.horizontalLayout_3.addWidget(self.day_class_label) self.day_class = QSpinBox(self.day_tab) self.day_class.setProperty("value", 10) self.day_class.setObjectName("day_class") self.horizontalLayout_3.addWidget(self.day_class) spacerItem6 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem6) self.day_mxd = QPushButton(self.day_tab) self.day_mxd.setObjectName("day_mxd") self.horizontalLayout_3.addWidget(self.day_mxd) self.verticalLayout.addLayout(self.horizontalLayout_3) self.day_view = QGraphicsView(self.day_tab) self.day_view.setObjectName("day_view") self.verticalLayout.addWidget(self.day_view) self.verticalLayout_4.addLayout(self.verticalLayout) self.tabWidget.addTab(self.day_tab, "") self.verticalLayout_5.addWidget(self.tabWidget) self.horizontalLayout_4 =QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.progressBar = QProgressBar(self.layoutWidget) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth()) self.progressBar.setSizePolicy(sizePolicy) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName("progressBar") self.horizontalLayout_4.addWidget(self.progressBar) self.execute_button = QPushButton(self.layoutWidget) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.execute_button.sizePolicy().hasHeightForWidth()) self.execute_button.setSizePolicy(sizePolicy) self.execute_button.setObjectName("execute_button") self.horizontalLayout_4.addWidget(self.execute_button) self.verticalLayout_5.addLayout(self.horizontalLayout_4) self.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 1040, 26)) self.menubar.setObjectName("menubar") self.file_menu = QMenu(self.menubar) self.file_menu.setObjectName("file_menu") self.help_menu = QMenu(self.menubar) self.help_menu.setObjectName("help_menu") self.setMenuBar(self.menubar) self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.action_add_data = QAction(self) self.action_add_data.setObjectName("action_add_data") self.action_help = QAction(self) self.action_help.setObjectName("action_help") self.action_about = QAction(self) self.action_about.setObjectName("action_about") self.action_save_pic = QAction(self) self.action_save_pic.setObjectName("action_save_pic") self.file_menu.addAction(self.action_add_data) self.file_menu.addAction(self.action_save_pic) self.help_menu.addAction(self.action_help) self.help_menu.addAction(self.action_about) self.menubar.addAction(self.file_menu.menuAction()) self.menubar.addAction(self.help_menu.menuAction()) self.retranslateUi() self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(self) self.center() self.show() self.target_area.activated[str].connect(self.updateTargetArea) self.datetime.dateChanged.connect(self.updateDatetime) self.density_cell.valueChanged.connect(self.updateDensityCell) self.density_class.valueChanged.connect(self.updateDensityClass) self.day_cell.valueChanged.connect(self.updateDayCell) self.day_class.valueChanged.connect(self.updateDayClass) self.action_add_data.triggered.connect(self.addData) self.action_save_pic.triggered.connect(self.savePic) self.action_about.triggered.connect(self.showAbout) self.action_help.triggered.connect(self.showHelp) self.execute_button.clicked.connect(self.execute) self.density_mxd.clicked.connect(self.openMxdDensity) self.day_mxd.clicked.connect(self.openMxdDay) self.density_mxd.setDisabled(True) self.day_mxd.setDisabled(True) self.action_save_pic.setDisabled(True) def execute(self): dir = u"E:/Documents/工作/雷电公报/闪电定位原始文本数据/" + self.in_parameters[u'datetime'] if os.path.exists(dir): datafiles = os.listdir(dir) datafiles = map(lambda x:os.path.join(dir,x),datafiles) self.in_parameters[u'origin_data_path'] = datafiles if not self.in_parameters.has_key(u'origin_data_path'): message = u"请加载%s的数据" % self.in_parameters[u'datetime'] msgBox = QMessageBox() msgBox.setText(message) msgBox.setIcon(QMessageBox.Information) icon = QIcon() icon.addPixmap(QPixmap('./resource/weather-thunder.png'), QIcon.Normal, QIcon.Off) msgBox.setWindowIcon(icon) msgBox.setWindowTitle(" ") msgBox.exec_() return self.execute_button.setDisabled(True) self.execute_button.setText(u'正在制图中……') self.progressBar.setMaximum(0) self.progressBar.setMinimum(0) self.action_add_data.setDisabled(True) self.target_area.setDisabled(True) self.datetime.setDisabled(True) self.density_cell.setDisabled(True) self.density_class.setDisabled(True) self.day_cell.setDisabled(True) self.day_class.setDisabled(True) # for outfile in self.in_parameters[u'origin_data_path']: # infile = # try: # with open(infile, 'w+') as in_f: # for line in in_f: # line = line.replace(u":",":") # in_f.write(line) # except Exception,inst: # print infile self.process_thread = WorkThread() self.process_thread.trigger.connect(self.finished) self.process_thread.beginRun(self.in_parameters) def finished(self): #绘制闪电密度图 ##清除上一次的QGraphicsView对象,防止其记录上一次图片结果,影响显示效果 self.density_view.setAttribute(Qt.WA_DeleteOnClose) self.verticalLayout_2.removeWidget(self.density_view) size = self.density_view.size() self.density_view.close() self.density_view = QGraphicsView(self.density_tab) self.density_view.setObjectName("density_view") self.density_view.resize(size) self.verticalLayout_2.addWidget(self.density_view) densityPic = ''.join([cwd,u'/bulletinTemp/', self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'], self.in_parameters[u'target_area'],u'闪电密度空间分布.tif']) scene = QGraphicsScene() pixmap_density = QPixmap(densityPic) scene.addPixmap(pixmap_density) self.density_view.setScene(scene) scale = float(self.density_view.width()) / pixmap_density.width() self.density_view.scale(scale, scale) #绘制雷暴日图 self.day_view.setAttribute(Qt.WA_DeleteOnClose) self.verticalLayout.removeWidget(self.day_view) size = self.day_view.size() self.day_view.close() self.day_view = QGraphicsView(self.day_tab) self.day_view.setObjectName("day_view") self.day_view.resize(size) self.verticalLayout.addWidget(self.day_view) dayPic = ''.join([cwd,u'/bulletinTemp/', self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'], self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif']) pixmap_day = QPixmap(dayPic) scene = QGraphicsScene() scene.addPixmap(pixmap_day) self.day_view.resize(self.density_view.width(),self.density_view.height()) self.day_view.setScene(scene) scale = float(self.day_view.width()) / pixmap_day.width() self.day_view.scale(scale, scale) #处理进度条和执行按钮状态 self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(100) self.progressBar.setFormat(u'完成!') self.execute_button.setDisabled(False) self.execute_button.setText(u'执行') #改变一些控件的状态 self.action_add_data.setDisabled(False) self.target_area.setDisabled(False) self.datetime.setDisabled(False) self.density_cell.setDisabled(False) self.density_class.setDisabled(False) self.day_cell.setDisabled(False) self.day_class.setDisabled(False) self.density_mxd.setDisabled(False) self.day_mxd.setDisabled(False) self.action_save_pic.setDisabled(False) def addData(self): fnames = QFileDialog.getOpenFileNames(self, u'请选择原始的电闪数据', u'E:/Documents/工作/雷电公报/闪电定位原始文本数据', 'Text files (*.txt);;All(*.*)') self.in_parameters[u'origin_data_path'] = fnames[0] def savePic(self): densityPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/', self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'], self.in_parameters[u'target_area'],u'闪电密度空间分布.tif']) dayPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/', self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'], self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif']) directory = QFileDialog.getExistingDirectory(self,u'请选择图片保存位置', u'E:/Documents/工作/雷电公报', QFileDialog.ShowDirsOnly|QFileDialog.DontResolveSymlinks) dest_density = os.path.join(directory,os.path.basename(densityPic)) dest_day = os.path.join(directory,os.path.basename(dayPic)) if os.path.isfile(dest_day) or os.path.isfile(dest_density): message = u"文件已经存在!" msgBox = QMessageBox() msgBox.setText(message) msgBox.setIcon(QMessageBox.Information) icon = QIcon() icon.addPixmap(QPixmap("./resource/weather-thunder.png"), QIcon.Normal, QIcon.Off) msgBox.setWindowIcon(icon) msgBox.setWindowTitle(" ") msgBox.exec_() return move(dayPic,directory) move(densityPic,directory) def openMxdDay(self): program = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe' src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb']) dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']]) src_file = ''.join([self.in_parameters[u'target_area'] , u"地闪雷暴日空间分布模板.mxd"]) copy(os.path.join(src_dir,src_file),dest_dir) arguments = [os.path.join(dest_dir,src_file)] self.process = QProcess(self) self.process.start(program,arguments) def openMxdDensity(self): program = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe' src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb']) dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']]) src_file = ''.join([self.in_parameters[u'target_area'] ,u"闪电密度空间分布模板.mxd"]) copy(os.path.join(src_dir,src_file),dest_dir) arguments = [os.path.join(dest_dir,src_file)] self.process = QProcess(self) self.process.start(program,arguments) def showAbout(self): self.about = About_Dialog() def showHelp(self): program = u'C:/Windows/hh.exe' arguments = [''.join([cwd,'/help/help.CHM'])] self.process = QProcess(self) self.process.start(program,arguments) def updateTargetArea(self, area): self.in_parameters[u'target_area'] = area def updateDatetime(self, date): self.in_parameters[u'datetime'] = str(date.year()) + u'年' if self.in_parameters.has_key(u'origin_data_path'): self.in_parameters.__delitem__(u'origin_data_path') def updateDensityCell(self, cell): self.in_parameters[u'density_cell'] = str(cell) def updateDensityClass(self, nclass): self.in_parameters[u'density_class'] = nclass def updateDayCell(self, cell): self.in_parameters[u'day_cell'] = str(cell) def updateDayClass(self, nclass): self.in_parameters[u'day_class'] = nclass def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def retranslateUi(self): _translate = QCoreApplication.translate self.setWindowTitle(_translate("MainWindow", "绍兴防雷中心 雷电公报制图")) self.datetime_label.setText(_translate("MainWindow", "年份")) self.datetime.setDisplayFormat(_translate("MainWindow", "yyyy")) self.target_area_label.setText(_translate("MainWindow", "地区")) self.target_area.setItemText(0, _translate("MainWindow", "绍兴市")) self.target_area.setItemText(1, _translate("MainWindow", "柯桥区")) self.target_area.setItemText(2, _translate("MainWindow", "上虞区")) self.target_area.setItemText(3, _translate("MainWindow", "诸暨市")) self.target_area.setItemText(4, _translate("MainWindow", "嵊州市")) self.target_area.setItemText(5, _translate("MainWindow", "新昌县")) self.density_cell_label.setText(_translate("MainWindow", "插值网格大小")) self.density_class_label.setText(_translate("MainWindow", "制图分类数目")) self.density_mxd.setText(_translate("MainWindow", "ArcGIS文档")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.density_tab), _translate("MainWindow", "电闪密度")) self.day_cell_label.setText(_translate("MainWindow", "插值网格大小")) self.day_class_label.setText(_translate("MainWindow", "制图分类数目")) self.day_mxd.setText(_translate("MainWindow", "ArcGIS文档")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.day_tab), _translate("MainWindow", "雷暴日")) self.execute_button.setText(_translate("MainWindow", "执行")) self.file_menu.setTitle(_translate("MainWindow", "文件")) self.help_menu.setTitle(_translate("MainWindow", "帮助")) self.action_add_data.setText(_translate("MainWindow", "加载数据")) self.action_help.setText(_translate("MainWindow", "使用说明")) self.action_about.setText(_translate("MainWindow", "关于")) self.action_save_pic.setText(_translate("MainWindow", "图片另存为"))