def __init__(self): super(MyUi, self).__init__() self.ui = Ui_Main_Window() self.connection = None self.ui.setup_ui(self) self._init_db() self.ui.stocks_tree.clear() self.ui.search_btn.clicked.connect(lambda: self.search_weibo()) self.ui.stocks_tree.itemClicked.connect(self.onItemClick) current_date = time.strftime("%Y/%m/%d") date_obj = datetime.strptime(current_date, "%Y/%m/%d") past = date_obj - timedelta(days=7) past_time = datetime.strftime(past, "%Y/%m/%d") self.QPastDate = QDate.fromString(past_time, "yyyy/MM/dd") self.QCurDate = QDate.fromString(current_date, "yyyy/MM/dd") self.ui.stocks_tree.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.stocks_tree.customContextMenuRequested.connect(self.openMenu) self.ui.start_date_edit.setDate(self.QPastDate) self.ui.end_date_edit.setDate(self.QCurDate) self.ui.start_date_edit.setCalendarPopup(True) self.ui.end_date_edit.setCalendarPopup(True) self.ui.search_edit_text.setText("6004376285") self.choice = 'Open' file_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "WeiboData/Gui/render.html")) #path to read html file local_url = QUrl.fromLocalFile(file_path) self.ui.webView.load(local_url) self.ui.stock_option_combobox.currentIndexChanged.connect( lambda: self.modifycombo(self.QPastDate, self.QCurDate))
def setDate(self, date): if isinstance(date, datetime.date): date = QDate(date.year, date.month, date.day) if date is not None and date.isValid(): self._line_edit.setText(str(date.toString("yyyy-MM-dd"))) else: self._line_edit.setText("")
def set_value(self, value: Union[Tuple[int, int, int], float, int]): if isinstance(value, tuple): assert len(value) == 3 date = QDate(*value) elif isinstance(value, (float, int)): loc_time = time.localtime(value) print(loc_time) date = QDate(loc_time.tm_year, loc_time.tm_mon, loc_time.tm_mday) else: raise ValueError("value is not allowed", value) self.ctrl.setDate(date)
def update_subject(self): self.name_edit.setText( self.read_dict_value(self.subject_settings, 'name')) self.id_combo.setCurrentText( self.read_dict_value(self.subject_settings, 'id')) self.sex_combo.setCurrentText( self.read_dict_value(self.subject_settings, 'sex')) dob = self.read_dict_value(self.subject_settings, 'birthday') if dob not in [None, '']: q_dob = QDate.fromString(dob, 'yyyy-MM-d') self.dob_calendar.setSelectedDate(q_dob) else: self.dob_calendar.setSelectedDate(QDate.currentDate())
def date(self): date_string = self._line_edit.text() if len(str(date_string).strip()) > 0: date = QDate.fromString(date_string, "yyyy-MM-dd") if date.isValid(): return datetime.date(date.year(), date.month(), date.day()) return None
def __init__(self): super(MyUi, self).__init__() self.ui = Ui_Main_Window() self.connection = None self.ui.setup_ui(self) self._init_db() self.ui.stocks_tree.clear() self.ui.search_btn.clicked.connect(lambda: self.search_weibo()) current_date = time.strftime("%Y/%m/%d") date_obj = datetime.strptime(current_date, "%Y/%m/%d") past = date_obj - timedelta(days=7) past_time = datetime.strftime(past, "%Y/%m/%d") QPast = QDate.fromString(past_time, "yyyy/MM/dd") Qcurdate = QDate.fromString(current_date, "yyyy/MM/dd") self.ui.start_date_edit.setDate(QPast) self.ui.end_date_edit.setDate(Qcurdate) self.ui.start_date_edit.setCalendarPopup(True) self.ui.end_date_edit.setCalendarPopup(True)
def CrearPatientInf(self): self.NameLabel=QtWidgets.QLabel("Patient Name") self.NameEdit = QtWidgets.QLineEdit() self.NameEdit.setPlaceholderText('输入姓名') self.informationLayout.addWidget(self.NameLabel,0,0) self.informationLayout.addWidget(self.NameEdit,0,1) self.IDLabel=QtWidgets.QLabel("Patient ID") self.IDEdit = QtWidgets.QLineEdit() self.IDEdit.setPlaceholderText('输入ID') self.informationLayout.addWidget(self.IDLabel,1,0) self.informationLayout.addWidget(self.IDEdit,1,1) self.BirthLabel=QtWidgets.QLabel("Date of Birth") self.BirthDateEdit=QtWidgets.QDateEdit() strdate = time.strftime("%Y-%m-%d") #gets current time to put into dateedit #dateobj = datetime.strptime(curdate, "%Y-%m-%d")#converts to datetime object self.Qdate = QDate.fromString(strdate,"yyyy-MM-dd") self.BirthDateEdit.setDate(self.Qdate ) self.informationLayout.addWidget(self.BirthLabel,2,0) self.informationLayout.addWidget(self.BirthDateEdit,2,1) self.
def __init__(self): super(MyUi, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) #cwd = os.getcwd() #cwd = str(cwd) #if os.path.isfile(cwd+"/time"): # with open("time","r") as outfile:#reads current time # history = cPickle.load(outfile) # if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours # print "Less than 12 hours. Loading previously saved Json..." # with open("time","w") as infile: #update time # cPickle.dump(datetime.now(),infile) #else: # print "More than 12 hours. Updating Json..." # data = ts.get_industry_classified() # data.to_json(cwd + "/class.json", orient="columns")#writes class data so no need to call Tushare agian #now = datetime.now() #with open("time", "w+") as outfile: #update time # cPickle.dump(now, outfile) # else: # print "No json found!"#If this is first time using tuchart in this directory # data = df() # data = ts.get_industry_classified() # print data # var = data.to_json(cwd+"/class.json",orient="columns") # with open('class.json', 'w+') as outfile: #records json # json.dump(var, outfile) # now = datetime.now() # with open("time", "w+") as outfile: # cPickle.dump(now,outfile) # series = pd.read_json(cwd + "\\class.json") series = ts.get_industry_classified() series = pd.DataFrame(series) curdate = time.strftime( "%Y/%m/%d") #gets current time to put into dateedit dateobj = datetime.strptime(curdate, "%Y/%m/%d") #converts to datetime object past = dateobj - timedelta(days=7) #minus a week to start date pasttime = datetime.strftime(past, "%Y/%m/%d") QPast = QDate.fromString( pasttime, "yyyy/MM/dd") #convert to qtime so that widget accepts the values Qcurdate = QDate.fromString(curdate, "yyyy/MM/dd") #print series list1 = series["c_name"].tolist( ) #Get industry categories. Filters out redundant ones list1 = list(set(list1)) #w = database() #zsparent = QTreeWidgetItem(self.ui.treeWidget) #zsparent.setText(0,"股票指数") #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"] for j in list1: parent = QTreeWidgetItem( self.ui.treeWidget) #populate treewidget with names parent.setText(0, j) var = series.loc[series["c_name"] == j] list2 = var["code"].tolist() name = var["name"].tolist() #var = showcollection(i) #Display database items for idx, val in enumerate(list2): child = QTreeWidgetItem(parent) child.setText(0, name[idx] + "-" + str(val)) #for i in Drag: #grandson = QTreeWidgetItem(child) #Commented out because increases program response time #grandson.setText(0, i) #self.ui.treeWidget.itemDoubleClicked.connect(self.onClickItem) #Display Collection items self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu) #self.ui.widget.setGeometry(QtCore.QRect(0, 30,1550, 861)) file_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file local_url = QUrl.fromLocalFile(file_path) self.ui.widget.load(local_url) self.ui.commandLinkButton.setFixedSize(50, 50) self.ui.commandLinkButton.clicked.connect( self.classify) #when the arrow button is clicked, trigger events #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget)) # QSizePolicy retain_size = self.ui.dateEdit_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.dateEdit_2.setSizePolicy(retain_size) retain_size = self.ui.comboBox.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.comboBox.setSizePolicy(retain_size) retain_size = self.ui.label_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.label_2.setSizePolicy(retain_size) self.ui.dateEdit.setDate(QPast) self.ui.dateEdit_2.setDate(Qcurdate) #populate widgets self.ui.dateEdit.setCalendarPopup(True) self.ui.dateEdit_2.setCalendarPopup(True) self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"]) self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove) self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.treeWidget_2.customContextMenuRequested.connect( self.openWidgetMenu) #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword)) self.ui.combobox.currentIndexChanged.connect(self.modifycombo)
from qtpy.QtCore import QDate, QDateTime, QTime, Qt from qtpy.QtWidgets import QApplication, QWidget, QMessageBox, QDesktopWidget, QMainWindow, QAction, qApp, QMenu from qtpy.QtGui import QIcon from qtpy import QtGui import sys now = QDate.currentDate() print(now.toString(Qt.ISODate)) print(now.toString(Qt.DefaultLocaleLongDate)) datetime = QDateTime.currentDateTime() print(datetime.toString()) time = QTime.currentTime() print(time.toString(Qt.DefaultLocaleLongDate)) # localdatetime print(datetime.toString(Qt.ISODate)) # Universal datetime print(datetime.toUTC().toString(Qt.ISODate)) class Example(QMainWindow): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): exitAct = QAction('&Exit', self)
def __init__(self): super(MyUi, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) cwd = os.getcwd() cwd = str(cwd) if os.path.isfile(cwd + "/time"): with open("time", "r") as outfile: #reads current time history = cPickle.load(outfile) if (datetime.now() - history ).total_seconds() < 43200: #measures if time elapse>12 hours print("Less than 12 hours. Loading previously saved Pickle...") #with open("time","w") as infile: #update time #cPickle.dump(datetime.now(),infile) # else: print("More than 12 hours. Updating Pickle...") data = ts.get_industry_classified() with open("class", "w+") as outfile: cPickle.dump(data, outfile) now = datetime.now() with open("time", "w+") as outfile: #update time cPickle.dump(now, outfile) else: print("No Pickle found!" ) #If this is first time using tuchart in this directory data = df() data = ts.get_industry_classified() with open('class', 'w+') as outfile: #records pickle cPickle.dump(data, outfile) now = datetime.now() with open("time", "w+") as outfile: cPickle.dump(now, outfile) with open("class", "r") as infile: # reads current time series = cPickle.load(infile) #series = pd.read_json(cwd + "\\class.json") #series = ts.get_industry_classified() series = pd.DataFrame(series) curdate = time.strftime( "%Y/%m/%d") # gets current time to put into dateedit curdateQ = QDate.fromString(curdate, "yyyy/MM/dd") dateobj = datetime.strptime(curdate, "%Y/%m/%d") #converts to datetime object past = dateobj - timedelta(days=7) #minus a week to start date pasttime = datetime.strftime(past, "%Y/%m/%d") pastQ = QDate.fromString( pasttime, "yyyy/MM/dd") #convert to qtime so that widget accepts the values pastL = dateobj - timedelta(days=30) # minus a month to start date pasttimeL = datetime.strftime(pastL, "%Y/%m/%d") pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd") np_indexes = np.array([['sh', '上证指数', '大盘指数'], ['sz', '深证成指', '大盘指数'], ['hs300', '沪深300指数', '大盘指数'], ['sz50', '上证50', '大盘指数'], ['zxb', '中小板', '大盘指数'], ['cyb', '创业板', '大盘指数']]) indexes = df(data=np_indexes, index=range(5000, 5006), columns=["code", "name", "c_name"]) series = indexes.append(series) list1_bfr = series["c_name"].tolist( ) #Get industry categories. Filters out redundant ones list1 = list(set(list1_bfr)) list1.sort(key=list1_bfr.index) #w = database() #zsparent = QTreeWidgetItem(self.ui.treeWidget) #zsparent.setText(0,"股票指数") #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"] self.init_treeWidget(list1, series) self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu) #self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861)) file_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file local_url = QUrl.fromLocalFile(file_path) self.ui.webView.load(local_url) #self.ui.commandLinkButton.setFixedSize(50, 50) self.ui.search_btn.clicked.connect(lambda: self.search_comp(series)) self.ui.log_btn.clicked.connect(lambda: self.log()) self.ui.init_code_btn.clicked.connect( lambda: self.code_sort_tree(series)) self.ui.init_category_btn.clicked.connect( lambda: self.init_treeWidget(list1, series)) self.ui.commandLinkButton.clicked.connect( self.classify) #when the arrow button is clicked, trigger events #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget)) # QSizePolicy try: retain_size = self.ui.dateEdit_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.dateEdit_2.setSizePolicy(retain_size) retain_size = self.ui.comboBox.sizePolicy() retain_size.setRetainSizeWhenHidden(True) # self.ui.comboBox.setSizePolicy(retain_size) retain_size = self.ui.label_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.label_2.setSizePolicy(retain_size) except AttributeError: print("No PYQT5 Binding! Widgets might be deformed") self.ui.dateEdit.setDate(pastQL) self.ui.dateEdit_2.setDate(curdateQ) #populate widgets self.ui.dateEdit.setCalendarPopup(True) self.ui.dateEdit_2.setCalendarPopup(True) self.ui.comboBox.addItems(["D"]) self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove) self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.treeWidget_2.customContextMenuRequested.connect( self.openWidgetMenu) #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword)) self.ui.combobox.currentIndexChanged.connect( lambda: self.modifycombo(pastQL, pastQ))
def __init__(self): super(MyUi, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) cwd = os.getcwd() cwd = str(cwd) if os.path.isfile(cwd+"/time"): with open("time","r") as outfile:#reads current time history = cPickle.load(outfile) if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours print("Less than 12 hours. Loading previously saved Pickle...") #with open("time","w") as infile: #update time #cPickle.dump(datetime.now(),infile) else: print("More than 12 hours. Updating Pickle...") data = ts.get_industry_classified() with open("class","w+") as outfile: cPickle.dump(data,outfile) now = datetime.now() with open("time", "w+") as outfile: #update time cPickle.dump(now, outfile) else: print("No Pickle found!") #If this is first time using tuchart in this directory data = df() data = ts.get_industry_classified() with open('class', 'w+') as outfile: #records pickle cPickle.dump(data, outfile) now = datetime.now() with open("time", "w+") as outfile: cPickle.dump(now,outfile) with open("class", "r") as infile: # reads current time series = cPickle.load(infile) #series = pd.read_json(cwd + "\\class.json") #series = ts.get_industry_classified() series = pd.DataFrame(series) curdate = time.strftime("%Y/%m/%d") # gets current time to put into dateedit curdateQ = QDate.fromString(curdate,"yyyy/MM/dd") dateobj = datetime.strptime(curdate, "%Y/%m/%d")#converts to datetime object past = dateobj - timedelta(days = 7) #minus a week to start date pasttime = datetime.strftime(past, "%Y/%m/%d") pastQ = QDate.fromString(pasttime,"yyyy/MM/dd") #convert to qtime so that widget accepts the values pastL = dateobj - timedelta(days=30) # minus a month to start date pasttimeL = datetime.strftime(pastL, "%Y/%m/%d") pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd") np_indexes = np.array([['sh', '上证指数', '大盘指数'], ['sz', '深证成指', '大盘指数'], ['hs300', '沪深300指数', '大盘指数'], ['sz50', '上证50', '大盘指数'], ['zxb', '中小板', '大盘指数'], ['cyb', '创业板', '大盘指数']]) indexes = df(data=np_indexes, index=range(5000, 5006), columns=["code", "name", "c_name"]) series = indexes.append(series) list1_bfr = series["c_name"].tolist() #Get industry categories. Filters out redundant ones list1 = list(set(list1_bfr)) list1.sort(key=list1_bfr.index) #w = database() #zsparent = QTreeWidgetItem(self.ui.treeWidget) #zsparent.setText(0,"股票指数") #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"] self.init_treeWidget(list1,series) self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu) #self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861)) file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file local_url = QUrl.fromLocalFile(file_path) self.ui.webView.load(local_url) #self.ui.commandLinkButton.setFixedSize(50, 50) self.ui.search_btn.clicked.connect(lambda: self.search_comp(series)) self.ui.init_code_btn.clicked.connect(lambda: self.code_sort_tree(series)) self.ui.init_category_btn.clicked.connect(lambda: self.init_treeWidget(list1, series)) self.ui.commandLinkButton.clicked.connect(self.classify) #when the arrow button is clicked, trigger events #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget)) # QSizePolicy try: retain_size = self.ui.dateEdit_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.dateEdit_2.setSizePolicy(retain_size) retain_size = self.ui.comboBox.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.comboBox.setSizePolicy(retain_size) retain_size = self.ui.label_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.label_2.setSizePolicy(retain_size) except AttributeError: print("No PYQT5 Binding! Widgets might be deformed") self.ui.dateEdit.setDate(pastQL) self.ui.dateEdit_2.setDate(curdateQ)#populate widgets self.ui.dateEdit.setCalendarPopup(True) self.ui.dateEdit_2.setCalendarPopup(True) self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"]) self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove) self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.treeWidget_2.customContextMenuRequested.connect(self.openWidgetMenu) #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword)) self.ui.combobox.currentIndexChanged.connect(lambda: self.modifycombo(pastQL,pastQ))
class CustomAppExample(CustomApp): # list of dicts enabling the settings tree on the user interface params = [ { 'title': 'Main settings:', 'name': 'main_settings', 'type': 'group', 'children': [{ 'title': 'Save base path:', 'name': 'base_path', 'type': 'browsepath', 'value': config('data_saving', 'h5file', 'save_path') }, { 'title': 'File name:', 'name': 'target_filename', 'type': 'str', 'value': "", 'readonly': True }, { 'title': 'Date:', 'name': 'date', 'type': 'date', 'value': QDate.currentDate() }, { 'title': 'Do something, such as showing data:', 'name': 'do_something', 'type': 'bool', 'value': False }, { 'title': 'Something done:', 'name': 'something_done', 'type': 'led', 'value': False, 'readonly': True }, { 'title': 'Infos:', 'name': 'info', 'type': 'text', 'value': "" }, { 'title': 'push:', 'name': 'push', 'type': 'bool_push', 'value': False }] }, { 'title': 'Other settings:', 'name': 'other_settings', 'type': 'group', 'children': [ { 'title': 'List of stuffs:', 'name': 'list_stuff', 'type': 'list', 'value': 'first', 'limits': ['first', 'second', 'third'], 'tip': 'choose a stuff from the list' }, { 'title': 'List of integers:', 'name': 'list_int', 'type': 'list', 'value': 0, 'limits': [0, 256, 512], 'tip': 'choose a stuff from this int list' }, { 'title': 'one integer:', 'name': 'an_integer', 'type': 'int', 'value': 500, }, { 'title': 'one float:', 'name': 'a_float', 'type': 'float', 'value': 2.7, }, ] }, ] def __init__(self, dockarea): super().__init__(dockarea) # init the object parameters self.raw_data = [] self.setup_ui() def setup_actions(self): ''' subclass method from ActionManager ''' logger.debug('setting actions') self.add_action('quit', 'Quit', 'close2', "Quit program", toolbar=self.toolbar) self.add_action('grab', 'Grab', 'camera', "Grab from camera", checkable=True, toolbar=self.toolbar) self.add_action( 'load', 'Load', 'Open', "Load target file (.h5, .png, .jpg) or data from camera", checkable=False, toolbar=self.toolbar) self.add_action('save', 'Save', 'SaveAs', "Save current data", checkable=False, toolbar=self.toolbar) self.add_action('show', 'Show/hide', 'read2', "Show Hide DAQViewer", checkable=True, toolbar=self.toolbar) logger.debug('actions set') def setup_docks(self): ''' subclass method from CustomApp ''' logger.debug('setting docks') self.dock_settings = Dock('Settings', size=(350, 350)) self.dockarea.addDock(self.dock_settings, 'left') self.dock_settings.addWidget(self.settings_tree, 10) self.dock_logger = Dock("Logger") self.logger_list = QtWidgets.QListWidget() self.logger_list.setMinimumWidth(300) self.dock_logger.addWidget(self.logger_list) self.dockarea.addDock(self.dock_logger, 'bottom', self.dock_settings) # create a dock containing a viewer object, could be 0D, 1D or 2D depending what kind of data one want to plot here a 0D dock_Viewer0D = Dock('Viewer dock', size=(350, 350)) self.dockarea.addDock(dock_Viewer0D, 'right', self.dock_logger) target_widget = QtWidgets.QWidget() self.target_viewer = Viewer0D(target_widget) dock_Viewer0D.addWidget(target_widget) # create 2 docks to display the DAQ_Viewer (one for its settings, one for its viewer) self.dock_detector_settings = Dock("Detector Settings", size=(350, 350)) self.dockarea.addDock(self.dock_detector_settings, 'right', self.dock_settings) self.dock_detector = Dock("Detector Viewer", size=(350, 350)) self.dockarea.addDock(self.dock_detector, 'right', self.dock_detector_settings) # init one daq_viewer object named detector self.detector = DAQ_Viewer(self.dockarea, dock_settings=self.dock_detector_settings, dock_viewer=self.dock_detector, title="A detector", DAQ_type='DAQ0D') # set its type to 'Mock' self.detector.daq_type = 'Mock' # init the detector and wait 1000ms for the completion self.detector.init_det() self.detector.settings.child('main_settings', 'wait_time').setValue(100) QtWidgets.QApplication.processEvents() QThread.msleep(1000) logger.debug('docks are set') def connect_things(self): ''' subclass method from CustomApp ''' logger.debug('connecting things') self.log_signal[str].connect( self.add_log ) # connect together this custom signal with the add_log method self.detector.grab_done_signal.connect(self.data_done) self.connect_action('quit', self.quit_function) self.connect_action('load', self.load_file) self.connect_action('save', self.save_data) self.connect_action('grab', self.detector.grab) self.connect_action('show', self.show_detector) logger.debug('connecting done') def show_detector(self, status): self.dock_detector.setVisible(status) self.dock_detector_settings.setVisible(status) def setup_menu(self): ''' subclass method from CustomApp ''' logger.debug('settings menu') file_menu = self.mainwindow.menuBar().addMenu('File') self.affect_to('quit', file_menu) file_menu.addSeparator() self.affect_to('load', file_menu) self.affect_to('save', file_menu) self.affect_to('quit', file_menu) logger.debug('menu set') def value_changed(self, param): logger.debug(f'calling value_changed with param {param.name()}') if param.name() == 'do_something': if param.value(): self.log_signal.emit('Do something') self.detector.grab_done_signal.connect(self.show_data) self.raw_data = [] # init the data to be finally saved self.settings.child('main_settings', 'something_done').setValue(True) else: self.log_signal.emit('Stop Doing something') self.detector.grab_done_signal.disconnect() self.settings.child('main_settings', 'something_done').setValue(False) logger.debug(f'Value change applied') @Slot(OrderedDict) def data_done(self, data): # print(data) pass @Slot(OrderedDict) def show_data(self, data): """ do stuff with data from the detector if its grab_done_signal has been connected Parameters ---------- data: (OrderedDict) #OrderedDict(name=self.title,x_axis=None,y_axis=None,z_axis=None,data0D=None,data1D=None,data2D=None) """ data0D = [[data['data0D'][key]['data']] for key in data['data0D']] if self.raw_data == []: self.raw_data = data0D else: if len(self.raw_data) != len(data0D): self.raw_data = data0D else: for ind in range(len(data0D)): self.raw_data[ind].append(data0D[ind][0]) self.target_viewer.show_data(data0D) def load_file(self): # init the data browser module widg = QtWidgets.QWidget() self.data_browser = H5Browser(widg) widg.show() def quit_function(self): # close all stuff that need to be self.detector.quit_fun() QtWidgets.QApplication.processEvents() self.mainwindow.close() def run_detector(self): self.detector.ui.grab_pb.click() def save_data(self): try: path = select_file(start_path=self.settings.child( 'main_settings', 'base_path').value(), save=True, ext='h5') if path is not None: # init the file object with an addhoc name given by the user h5saver = H5Saver(save_type='custom') h5saver.init_file(update_h5=True, addhoc_file_path=path) # save all metadata settings_str = ioxml.parameter_to_xml_string(self.settings) settings_str = b'<All_settings>' + settings_str settings_str += ioxml.parameter_to_xml_string( self.detector.settings) + ioxml.parameter_to_xml_string( h5saver.settings) + b'</All_settings>' data_group = h5saver.add_data_group( h5saver.raw_group, group_data_type='data0D', title='data from custom app', settings_as_xml=settings_str) for dat in self.raw_data: channel = h5saver.add_CH_group(data_group) data_dict = dict(data=np.array(dat), x_axis=dict(data=np.linspace( 0, len(dat) - 1, len(dat)), units='pxl')) h5saver.add_data(channel, data_dict=data_dict, scan_type='') st = 'file {:s} has been saved'.format(str(path)) self.add_log(st) self.settings.child('main_settings', 'info').setValue(st) h5saver.close_file() except Exception as e: logger.exception(str(e)) @Slot(str) def add_log(self, txt): """ Add a log to the logger list from the given text log and the current time ================ ========= ====================== **Parameters** **Type** **Description** *txt* string the log to be added ================ ========= ====================== """ now = datetime.datetime.now() new_item = QtWidgets.QListWidgetItem(str(now) + ": " + txt) self.logger_list.addItem(new_item) logger.info(txt)
def __init__(self): super(mywindow, self).__init__() self.GraphEnable = True # 绘图开关 self.ui = Ui_MainWindow() self.ui.setupUi(self) curdate = time.strftime( "%Y-%m-%d") #gets current time to put into dateedit dateobj = datetime.strptime(curdate, "%Y-%m-%d") #converts to datetime object past = dateobj - timedelta(days=365) #minus a week to start date pasttime = datetime.strftime(past, "%Y-%m-%d") self.QPast = QDate.fromString( pasttime, "yyyy-MM-dd") #convert to qtime so that widget accepts the values self.Qcurdate = QDate.fromString(curdate, "yyyy-MM-dd") self.startdate = pasttime self.enddate = curdate zsparent = QTreeWidgetItem(self.ui.treeWidget) zsparent.setText(0, "index") zsparent.setIcon(0, QtGui.QIcon('src/ico/internet.png')) zsnames = [ "上证指数-sh", "深圳成指-sz", "沪深300指数-hs300", "上证50-sz50", "中小板-zxb", "创业板-cyb" ] #股票列表 for k in zsnames: child = QTreeWidgetItem(zsparent) child.setText(0, k) zsparent2 = QTreeWidgetItem(self.ui.treeWidget) zsparent2.setText(0, "SH") zsparent2.setIcon(0, QtGui.QIcon('src/ico/batman.png')) self.shanghai = ma.list_input('sh') #print (self.shanghai) list_name = list(self.shanghai.values) for code in list_name: child = QTreeWidgetItem(zsparent2) child.setText(0, '%s %s' % (code[0], code[1])) # child.doubleClicked.connect(self.code_write(code[0])) #self.connect(self, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.code_write(code[0])) zsparent_sz = QTreeWidgetItem(self.ui.treeWidget) zsparent_sz.setText(0, "SZ") zsparent_sz.setIcon(0, QtGui.QIcon('src/ico/greenman.png')) self.shenzhen = ma.list_input('sz') list_name = list(self.shenzhen.values) i = 0 for code in list_name: i += 1 child = QTreeWidgetItem(zsparent_sz) child.setText(0, '%s %s' % (code[0], code[1])) child.setText(1, code[0]) ''' 连接 edit line 和searchButton ''' self.ui.searchButton.clicked.connect(self.ClickedSearchButton) self.ui.searchButton.pressed.connect(self.PressSearchButton) self.ui.searchButton.released.connect(self.ReleasedSearchButton) #print(shanghai) self.ui.treeWidget.itemDoubleClicked.connect( self.DoubleClicked_code_edit) self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu) ''' 导入graph ''' #引用 T2 self.GraphInit() ''' self.ui.DateLinkButton 日期设置 ''' self.ui.DateLinkButton.setFixedSize(50, 50) self.ui.DateLinkButton.clicked.connect(self.ClickedDateButton) self.ui.DateLinkButton.pressed.connect(self.PressDateButton) self.ui.DateLinkButton.released.connect(self.ReleasedDateButton) #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget)) # QSizePolicy try: retain_size = self.ui.dateEdit_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.dateEdit_2.setSizePolicy(retain_size) retain_size = self.ui.comboBox.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.comboBox.setSizePolicy(retain_size) retain_size = self.ui.label_2.sizePolicy() retain_size.setRetainSizeWhenHidden(True) self.ui.label_2.setSizePolicy(retain_size) except AttributeError: print("No PYQT5 Binding! Widgets might be deformed") self.ui.dateEdit.setDate(self.QPast) self.ui.dateEdit_2.setDate(self.Qcurdate) #populate widgets self.ui.dateEdit.setCalendarPopup(True) self.ui.dateEdit_2.setCalendarPopup(True) self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"]) #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword)) self.ui.combobox.currentIndexChanged.connect(self.modifycombo) self.initUI()