Exemplo n.º 1
0
class WindowClass(QWidget):
    def __init__(self, parent=None):

        super(WindowClass, self).__init__(parent)
        self.btn = QPushButton(self)  #self参数则让该按钮显示当前窗体中
        self.btn.setText("选择日期")
        self.btn.move(0, 0)
        self.btn.clicked.connect(self.openCalendar)
        self.le = QLabel(self)
        self.cal = QCalendarWidget(self)
        self.cal.setMinimumDate(QDate(2017, 1, 1))  #设置日期最小范围
        self.cal.setMaximumDate(QDate(2019, 12, 30))  #设置日期最大范围
        self.cal.setGridVisible(True)  #是否显示日期之间的网格
        self.cal.move(5, 30)
        self.cal.hide()  #隐藏日期控件
        self.cal.clicked[QDate].connect(
            self.showDate)  #clicked[参数],即定义showDate是传入的参数类型设置
        date = self.cal.selectedDate()  #获取选中日期,默认当前系统时间
        self.le.setText(date.toString('yyyy-MM-dd dddd'))
        self.le.move(100, 8)
        self.setGeometry(100, 100, 400, 350)  #设置当前窗体位置和大小
        self.setWindowTitle("日历控件使用")

    def showDate(self, date):
        self.le.setText(date.toString("yyyy-MM-dd dddd"))
        self.cal.close()  #关闭日期控件

    def openCalendar(self):
        self.cal.show()  #显示日期控件
Exemplo n.º 2
0
class MyTable(QTableWidget):
	def __init__(self, r, c):
		super().__init__(r, c)
		self.FileOpenProcess = False
		self.ChangeDateProcess = False
		self.initUI()
		self.ProjectName = ""
		self.ProjectManager = ""
		self.Start = ""
		self.cal = QCalendarWidget(self)


	def initUI(self):
		self.cellChanged.connect(self.c_Current)
		self.cellClicked.connect(self.c_Clicked)
		self.show()

	def c_Current(self):
		if self.FileOpenProcess == False:
			row = self.currentRow()
			col = self.currentColumn()
			self.FileOpenProcess = True
			print ("row =" + str(row) + "coloumn = " + str(col) )
			try:
				if int(col) == 6 :
					print ("in calculation")
					endDate = self.calculateEndDate(row)
					print (endDate)
					self.setItem(row, 7, QTableWidgetItem(str(endDate)))
				elif int(col) in (2,4):
					if self.circularcheck() :
						print("in change dependency" )
						self.recalcDates(row)
			except:
				print ("in Exception")
				type, value, traceback = sys.exc_info()
				print (value)
				if (self.item(row,4) is None ):
					self.setItem(row,4,QTableWidgetItem("FS"))
				elif (self.item(row,2) is None ):
					self.setItem(row,2, QTableWidgetItem("0"))
				elif (self.item(row, 5) is None):
					self.setItem(row, 5, QTableWidgetItem(str(datetime.datetime.today())))
					if (self.item(row, 6) is None):
						self.setItem(row, 6, QTableWidgetItem("1d"))
				elif (self.item(row, 6) is None):
					self.setItem(row, 6, QTableWidgetItem("1d"))
					self.recalcDates(row)
				else:
					warn = QMessageBox(QMessageBox.Warning, "Error!",  "Could Not Calculate")
					warn.setStandardButtons(QMessageBox.Ok);
					warn.exec_()
					self.setItem(row, col, QTableWidgetItem(str("")))
			self.FileOpenProcess = False

	def c_Clicked(self):
		if self.FileOpenProcess == False:
			row = self.currentRow()
			col = self.currentColumn()
			self.FileOpenProcess == True
			if int(col) in(5,7):
				self.myCal()

	def myCal(self):
		self.cal.setGridVisible(True)
		self.cal.move(QtGui.QCursor.pos().x(), QtGui.QCursor.pos().y()-60)
		print (self.mapToGlobal(QtGui.QCursor.pos()))
		self.ChangeDateProcess = True
		self.cal.clicked.connect(self.getDate)
		self.cal.setGridVisible(True)	
		self.cal.show()
		
	def getDate(self):
		row = self.currentRow()
		col = self.currentColumn()
		if self.ChangeDateProcess:
			print (self.cal.selectedDate().toString())
			date = str(datetime.datetime.strptime( self.cal.selectedDate().toString(), '%a %b %d %Y') + datetime.timedelta(hours=8))
			self.setItem(row,col,QTableWidgetItem(date))
			print (date)
			self.ChangeDateProcess = False
			self.cal.hide()
		else:
			pass

	def recalcDates(self, row):
		type = self.item(int(row),4).text()
		print (type)
		if row !=0:
			if type.lower() == "fs":
				startDate = self.item(int(self.item(int(row), 2).text()), 7).text()
			elif type.lower() == 'ss':
				startDate = self.item(int(self.item(int(row-1), 2).text()), 5).text()
			self.setItem(int(row),5, QTableWidgetItem(str(startDate)))
			self.setItem(int(row),7, QTableWidgetItem(str(self.calculateEndDate (row))))


	def calculateEndDate(self, row):
		r = re.compile("([0-9]+)([a-zA-Z]+)")
		duration = str(self.item(row,6).text())
		print(duration)
		m = r.match(duration)
		duration = int(m.group(1))
		period = str(m.group(2))
		##2018-05-12 08:00:00
		endDate =  self.item(row,6).text()
		date = datetime.datetime.strptime( self.item(row,5).text() , '%Y-%m-%d %H:%M:%S')
		if period.lower() == 'h':
			enddate = date + datetime.timedelta(hours=int(duration))
			print  (endDate)
		elif period.lower() == 'm':
			enddate = date + datetime.timedelta(minutes=int(duration))
		elif period.lower() == 'd':
			enddate = date + datetime.timedelta(days=int(duration))
		elif period.lower() == 'w':
			enddate = date + datetime.timedelta(weeks=int(duration))
		else:
			QMessageBox.warning(self.view, 'Wrong Format', msg)

		return(enddate)

	def openProject(self):
		self.FileOpenProcess = True
		file = QFileDialog.getOpenFileName(self, 'Open NPF', os.getenv('HOME'), 'NPF(*.npf)')
		if file[0] != '':
			print (file[0])
			with open(file[0], newline='') as csv_file:
				self.setRowCount(0)
				self.setColumnCount(9)
				my_file = csv.reader(csv_file, dialect='excel')
				for row_data in my_file:
					row = self.rowCount()
					self.insertRow(row)
					if len(row_data) > 8:
						self.setColumnCount(len(row_data))
					for column, stuff in enumerate(row_data):
						item = QTableWidgetItem(stuff)
						self.setItem(row, column, item)
		self.FileOpenProcess = False

	def saveProject(self):
		path = QFileDialog.getSaveFileName(self, 'Save Project', os.getenv('HOME'), 'NPF(*.npf)')
		if path[0] != '':
			with open(path[0], 'w', newline = '') as csv_file:
				writer = csv.writer(csv_file, dialect='excel')
				for row in range(self.rowCount()):
					row_data = []
					for column in range(self.columnCount()):
						item = self.item(row, column)
						if item is not None:
							row_data.append(item.text())
						else:
							row_data.append('')
					writer.writerow(row_data)
					
	def add_row(self):
		rows = self.rowCount()
		self.setRowCount(self.rowCount() + 1)

	def remove_row(self):
		row = self.currentRow()
		cancel = False
		if row is not None:
			for i in range (0,8):
				data = self.item(row,i)
				if data is not None:
					reply = QMessageBox.question(
							self,
							'Confirm Delete, There is data in this row',
							'Are you sure you want to delete this row?',
							QMessageBox.Yes | QMessageBox.No,
							QMessageBox.No)
					if reply == QMessageBox.Yes:
						i = 9
						cancel = False
					else:
						cancel = True
	
			if cancel == False:
				self.removeRow(row)

	def indent_task(self):
		self.FileOpenProcess = True
		row = self.currentRow()
		print ("Current Row == " + str(row))
		if row != 0:
			currentItemIndent = len(str(self.item(row,2).text())) - len(str(self.item(row,2).text()).lstrip())
			parentrow = self.findParent(row,currentItemIndent)
			parent = str(self.item(parentrow,3).text())
			parentIndent = len(parent) - len(parent.lstrip())
			currentItem = str(self.item(row,3).text()).lstrip()
			print ("Indent Level == " + str(parentIndent+4))
			if currentItemIndent < parentIndent:
				futureIndent = parentIndent +4
			elif currentItemIndent == 0:
				futureIndent = 4
			elif currentItemIndent > parentIndent:
				futureIndent = parentIndent + 4

			for i in range (1,futureIndent):
				currentItem = " " + currentItem
			self.setItem(row, 3, QTableWidgetItem(currentItem))
			self.renumber()
		self.FileOpenProcess = False

	def findParent(self,row,currentItemIndent):
		parentrow = row
		for i in range (row,0, -1):
			parent_indent = len(str(self.item(i,3).text())) - len(str(self.item(i,3).text()).lstrip())
			if parent_indent > currentItemIndent:
				parentrow = i
				print ("Parent Indent = " + str (parent_indent) + "Current Indent ==" + str(currentItemIndent))
				break
		print (parentrow)
		return (parentrow -1)

	def renumber(self):
		rowsNo = int(self.rowCount())
		for i in range (0,rowsNo):
			if i == 0:
				self.setItem(i, 1, QTableWidgetItem("1.0"))
			else:
				#print ("i ====" + str(i))
				#print ("Previous Item Value ====" + self.item(i-1,3).text())
				#print("Previous WBS ID ====" + self.item(i-1,1).text())
				currentText = str(self.item(i,3).text())
				PrevWbsID = float(str(self.item(i-1,1).text()))
				prevIndent =  len(currentText) - len(currentText.lstrip())
				wbsDeapth = int(prevIndent/4)
				#print (wbsDeapth)
				self.setItem(i,1,QTableWidgetItem(str(PrevWbsID +1)))

	def outdent_task(self):
		row = self.currentRow()
		itemName = str(self.item(row,3).text())
		checkforSpaces = itemName[:4]
		print ('Left' + itemName[:4])
		if checkforSpaces.strip() == '':
			newText =itemName[4:]
			self.setItem(row,3,QTableWidgetItem(newText))  
class GUI():
    def __init__(self, app):
        self.app = app
        self.var = 1

        self.initUI()

    def initUI(self):
        #Input text boxes
        self.text_company = QLineEdit(self.app)
        self.text_company.move(120, 100)

        self.cal = QCalendarWidget(self.app)
        self.cal.hide()
        self.cal.move(120, 180)

        self.lbl = QLabel('\t\t', self.app)
        self.lbl.hide()
        self.lbl.move(120, 350)

        self.text_amount = QLineEdit(self.app)
        self.text_amount.hide()
        self.text_amount.move(120, 140)

        #Lables
        self.company = QLabel('Comapny', self.app)
        self.company.move(30, 100)

        self.buy_label = QLabel('Buy date', self.app)
        self.buy_label.move(30, 180)
        self.buy_label.hide()

        self.amount = QLabel('Amount', self.app)
        self.amount.hide()
        self.amount.move(30, 140)

        #Buttons
        self.quit = QPushButton('Quit button', self.app)
        self.quit.resize(self.quit.sizeHint())
        self.quit.move(630, 428)

        self.Enter = QPushButton('Enter', self.app)
        self.Enter.resize(self.Enter.sizeHint())
        self.Enter.move(300, 100)

        #General
        self.LED = QPixmap("Logo.PNG")
        self.pic = QLabel(self.app)
        self.pic.setPixmap(self.LED)
        self.pic.show()

        #self.submit.clicked.connect(self.Push_Submit)
        self.Enter.clicked.connect(self.get_input)

        self.quit.clicked.connect(QCoreApplication.instance().quit)

        #Franme
        self.app.setGeometry(400, 180, 700, 450)
        self.app.setWindowTitle('SCE')
        self.app.setWindowIcon(QIcon('icon.png'))
        self.app.show()

    def get_input(self):
        if self.var == 1:
            if len(self.text_company.text()) == 0:
                QMessageBox.warning(self.app, 'Error!!', 'must type a name')
            else:
                self.text_company.setText(self.text_company.text().upper())
                self.text_company.setText(self.text_company.text().upper())
                self.text_company.setDisabled(True)
                self.text_amount.show()
                self.amount.show()
                self.var = self.var + 1
                self.Enter.move(300, 140)
        elif self.var == 2:
            try:
                if int(self.text_amount.text()) <= 0:
                    QMessageBox.warning(self.app, 'Error!!',
                                        'Must be more then zero')
                else:
                    self.text_amount.setText(self.text_amount.text())
                    self.text_amount.setDisabled(True)
                    #self.cal.H()
                    self.lbl.show()
                    self.var = self.var + 1
                    self.Enter.move(300, 350)
                    self.Enter.setText('Show Calender..')
                    self.Enter.resize(self.Enter.sizeHint())
            except:
                QMessageBox.warning(self.app, 'Error!!',
                                    'Must be an integer number')
        elif self.var == 3:
            self.cal.show()

            self.Enter.setText('Select date..')
            self.Enter.resize(self.Enter.sizeHint())

            self.cal.clicked[QtCore.QDate].connect(self.showDate)

    def showDate(self, date):
        date_var_date = parse_date(date.toString(), fuzzy=True)
        date_var = date_var_date.strftime("%d-%b-%Y")
        today = datetime.today()
        self.lbl.setText(date_var)
        self.lbl.move(120, 180)
        self.buy_label.show()
        if date_var_date < today:
            QMessageBox.warning(self.app, 'Error!!', 'Date must be future')
        else:
            self.cal.hide()
            self.Enter.hide()
            self.Data(date_var_date)

    def Data(self, date_var_date):
        Extract_Data(self.text_company.text(), Min_Date, Max_Date)
        Regression(str(self.company), date_var_date,
                   int(self.text_amount.text()))

        self.text_Cost = QLineEdit(self.app)
        self.text_Cost.move(300, 220)
        self.cost = QLabel(
            'The value of th stock at the day that you want to buy ', self.app)
        self.cost.resize(self.cost.sizeHint())
        self.cost.move(30, 220)

        self.text_profit = QLineEdit(self.app)
        self.text_profit.move(300, 260)
        self.profit = QLabel('Your amount after a week from the buy date',
                             self.app)
        self.profit.resize(self.profit.sizeHint())
        self.profit.move(30, 260)

        self.text_Cost.show()
        self.cost.show()
        self.text_profit.show()
        self.profit.show()
        self.text_Cost.setText(str(extracted_items.Cost[0][0]))
        self.text_profit.setText(str(extracted_items.Profit[0][0]))
Exemplo n.º 4
0
class FourthMode(MiddleWidget):
    def __init__(self, obj, name):
        super().__init__(obj, name)
        self._thread = None
        self._obj = obj
        self.name = name
        self.row = 2
        self.set_up()

    def set_up(self):
        middle_widget = QWidget()
        self.middle_layout = QGridLayout()
        middle_widget.setLayout(self.middle_layout)
        for i in range(self.row):
            middle_icon = QLabel(chr(0xf002) + f'目录_{i}:')
            middle_icon.setFont(qtawesome.font('fa', 12))
            middle_icon.setFixedSize(50, self.height)
            middle_input = QLineEdit()
            middle_input.setFixedHeight(self.height)
            middle_input.setObjectName(f'middle_input_{i}')
            middle_btn = QPushButton("…")
            middle_btn.setFixedSize(50, self.height)
            middle_btn.setObjectName(f'middle_btn_{i}')
            middle_btn.setToolTip('点击选择文件')
            middle_btn.clicked.connect(lambda: self.open_file(middle_widget))

            self.middle_layout.addWidget(middle_icon, i, 0, 1, 1)
            self.middle_layout.addWidget(middle_input, i, 1, 1, self.row - 1)
            self.middle_layout.addWidget(middle_btn, i, self.row, 1, 1)

        middle_icon = QLabel(chr(0xf002) + f'目录_{i}:')
        middle_icon.setFont(qtawesome.font('fa', 12))
        middle_icon.setFixedSize(50, self.height)

        self.middle_time = QLineEdit()
        self.middle_time.setFixedHeight(self.height)
        self.middle_time.setObjectName(f'middle_input_{i}')

        btn = QPushButton("选择日期")
        btn.clicked.connect(self.openCalendar)

        self.cal = QCalendarWidget()
        self.cal.setGridVisible(True)  # 是否显示日期之间的网格
        self.cal.setFixedSize(250, 200)
        self.cal.hide()  # 隐藏日期控件
        self.cal.clicked[QDate].connect(
            self.showDate)  # clicked[参数],即定义showDate是传入的参数类型设置

        self.middle_layout.addWidget(middle_icon, 2, 0, 1, 1)
        self.middle_layout.addWidget(self.middle_time, 2, 1, 1, self.row - 1)
        self.middle_layout.addWidget(btn, 2, self.row, 1, 1)
        self.middle_layout.addWidget(self.cal, 3, 1, 1, 1)

        self.middle_layout.setAlignment(Qt.AlignTop)
        self._obj.mid_layout.addWidget(middle_widget, 0, 0, 1, 1)

        set_first_mode_style(middle_widget)
        return True

    def showDate(self, date):
        self.middle_time.setText(date.toString("yyyy-MM-dd dddd"))
        self.cal.close()  # 关闭日期控件

    def openCalendar(self):
        self.cal.show()  # 显示日期控件

    def get_data(self):
        self.children = self.middle_layout.count()
        print(self.children)
        keys = [
            self.middle_layout.itemAt(i).widget().text()
            for i in range(self.children) if not (i % 3)
        ]
        values = [
            self.middle_layout.itemAt(i).widget().text()
            for i in range(self.children) if i % 3 == 1
        ]
        for i in range(self.children // 3):
            input_val = values[i].strip()
            if not input_val:
                continue
            elif not os.path.exists(input_val):
                print("file path error")
                return
            else:
                self.data[keys[i]] = input_val
        return True

    def set_widget_enable(self, flag=False):
        # 禁止btn等
        if flag:
            self.reset_progress()
        else:
            self._obj.tail_btn.setEnabled(True)
        for widget in (self.middle_layout.itemAt(i).widget()
                       for i in range(self.children) if i % 3):
            widget.setDisabled(flag)

    def run(self):
        if not self.get_data():
            raise GetDataError("获取页面路径错误")
        if not self.data:
            print("界面参数不能为空")
            return
        try:
            self.create_thread_run()
        except:
            self.set_widget_enable()
            traceback.print_exc()

    def create_thread_run(self):
        self._thread = MyThread()
        self._thread.sig_str.connect(self.output_log_info)
        self._thread.sig_int.connect(self.set_progress)
        # self._thread.get_data(self.data)
        self._thread.get_obj(self)
        # 线程启动时禁止button和重置进度条
        # 运行后控件禁止再点击
        self.set_widget_enable(True)
        self._thread.start()
Exemplo n.º 5
0
class NewFilterWidget(QGroupBox):
    
    def __init__(self, parent, filter_widget):
        super().__init__(parent=parent)
        self.parent=parent
        self.filter_widget=filter_widget
        self.global_layout=QHBoxLayout()
        self.setLayout(self.global_layout)
        self.item1=QComboBox()
        for column in Filter.columns:
            self.item1.addItem(column)
        self.global_layout.addWidget(self.item1)
        self.item2=QComboBox()
        for operation in ['<','<=','=','>','>=']:
            self.item2.addItem(operation)
        self.global_layout.addWidget(self.item2)
        self.item3=QLineEdit()
        self.global_layout.addWidget(self.item3)
        self.calendar=QCalendarWidget()
        self.global_layout.addWidget(self.calendar)
        self.calendar.hide()
        self.remove_button=QToolButton()
        folder=os.path.split(inspect.getfile(Curve))[0]
        self.remove_button.setIcon(QtGui.QIcon(os.path.join(folder,'minus.png')))
        self.global_layout.addWidget(self.remove_button)
        self.remove_button.clicked.connect(self.remove)
        self.activate_box = QCheckBox('activate')
        
        self.global_layout.addWidget(self.activate_box)
        self.item1.currentTextChanged.connect(self.columnchanged)
        
    def columnchanged(self, text):
        if text=='date':
            self.item3.hide()
            self.calendar.show()
            self.item2.clear()
            for operation in ['<','<=','=','>','>=']:
                self.item2.addItem(operation)
        elif text in ['name', 'project', 'sample']:
            self.calendar.hide()
            self.item2.clear()
            self.item3.show()
            for operation in ['=', 'contains']:
                self.item2.addItem(operation)
        else:
            self.calendar.hide()
            self.item3.show()
            self.item2.clear()
            for operation in ['<','<=','=','>','>=']:
                self.item2.addItem(operation)
        
    def remove(self):
        for widget in [self.remove_button,self.item1,
                       self.item2, self.item3,
                       self.activate_box]:
            widget.hide()
            self.global_layout.removeWidget(widget)
        self.filter_widget.remove_filter(self)
        self.hide()
    
    def get_query(self):
        if self.item1.currentText() in ['id', 'parent', 'sample', 'project', 'name']:
            return Filter(self.item1.currentText(),
                          self.item2.currentText(),
                          self.item3.text())
        if self.item1.currentText()=='date':
            date=self.calendar.selectedDate()
            if self.item2.currentText() in ['<','>=']:
                t=datetime(date.year(), date.month(), date.day()).timestamp()
                return Filter(self.item1.currentText(),
                              self.item2.currentText(),
                              str(t))
            elif self.item2.currentText() in ['>','<=']:
                t=datetime(date.year(), date.month(), date.day()+1).timestamp()
                return Filter(self.item1.currentText(),
                              self.item2.currentText(),
                              str(t))
            elif self.item2.currentText()=='=':
                t1=datetime(date.year(), date.month(), date.day()).timestamp()
                t2=datetime(date.year(), date.month(), date.day()+1).timestamp()
                return [Filter(self.item1.currentText(),
                              '>',
                              str(t1)),
                        Filter(self.item1.currentText(),
                              '<',
                              str(t2))]