class dateWidget(QWidget): def __init__(self, parent): super(dateWidget, self).__init__(parent=parent) self.start = 0 self.end = 0 # -------------------------------------------------------------------- # Date picker self.label_from = QLabel('From', parent) self.label_from.setAlignment(Qt.AlignCenter) self.label_from.setFont(QFont("Open Sans Bold", 12)) self.label_from.setStyleSheet("background-color: rgb(134,194,50);" "color: rgb(255,255,255);") self.label_from.resize(100, 20) self.label_from.move(20, 60) self.d1 = QDateEdit(parent, calendarPopup=True) self.d1.setDateTime(QDateTime.currentDateTime()) self.d1.setStyleSheet("background-color: rgb(255, 255, 255);") self.d1.setGeometry(20, 80, 100, 25) #self.d1.dateChanged.connect(self.date_change) label_to = QLabel('To', parent) label_to.setAlignment(Qt.AlignCenter) label_to.setFont(QFont("Open Sans Bold", 12)) label_to.setStyleSheet("background-color: rgb(134,194,50);" "color: rgb(255,255,255);") label_to.resize(100, 20) label_to.move(140, 60) self.d2 = QDateEdit(parent, calendarPopup=True) self.d2.setDateTime(QDateTime.currentDateTime()) self.d2.setStyleSheet("background-color: rgb(255, 255, 255);") self.d2.setGeometry(140, 80, 100, 25) def date_change(self): self.start = self.d1.dateTime().toString('yyyy-MM-dd') self.end = self.d2.dateTime().toString('yyyy-MM-dd')
class Qt_Test_Frame(QMainWindow): Items = [] def __init__(self): #super(Qt_Test_Frame, self).__init__(*args, **kw) super().__init__() # 初始化界面 self._initUI() self.show() def _initUI(self): self.setWindowTitle("QT图形界面测试") self.resize(800, 600) wwg = QWidget() # 全局布局 wlayout = QVBoxLayout() h1_wlayout = QHBoxLayout() h2_wlayout = QHBoxLayout() h3_wlayout = QHBoxLayout() v4_wlayout = QVBoxLayout() v5_wlayout = QVBoxLayout() self.statusBar().showMessage("状态栏") # 第一层 self._frist_story(h1_wlayout) # 第二层 self._second_story(h2_wlayout) # 第三层 左 self._third_left(v4_wlayout, v5_wlayout) # 第三层 右 self._fouth_right(v5_wlayout) # 加载 splt = self._my_line() splt2 = self._my_line(False) wlayout.addSpacing(10) # 增加布局间距 wlayout.addLayout(h1_wlayout) wlayout.addSpacing(10) # 增加布局间距 wlayout.addLayout(h2_wlayout) wlayout.addSpacing(10) # 增加布局间距 wlayout.addWidget(splt) wlayout.addLayout(h3_wlayout) wlayout.addWidget(self.statusBar()) h3_wlayout.addLayout(v4_wlayout, 0) h3_wlayout.addWidget(splt2) h3_wlayout.addLayout(v5_wlayout, 2) #wlayout.setAlignment(Qt.AlignTop) wwg.setLayout(wlayout) self.setCentralWidget(wwg) def _frist_story(self, h1_wlayout): # 第一层布局 self.h1_combox1 = QComboBox(minimumWidth=100) self.h1_combox1.addItems(wind_field) self.h1_combox2 = QComboBox(minimumWidth=100) self.h1_combox2.addItems( wind_mach_chooice(self.h1_combox1.currentText())) self.h1_combox3 = QComboBox(minimumWidth=100) self.h1_combox3.addItems(wind_blade) self.h1_combox4 = QComboBox(minimumWidth=100) self.h1_combox4.addItems(signal_type) # 行为测试 暂时无法使用 h1_cb1_action = QAction("风场选择", self) h1_cb1_action.setStatusTip("请选择风场") self.h1_combox1.addAction(h1_cb1_action) h1_wlayout.addItem(QSpacerItem(20, 20)) h1_wlayout.addWidget(QLabel("风场"), 0) h1_wlayout.addWidget(self.h1_combox1, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("风机"), 0) h1_wlayout.addWidget(self.h1_combox2, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("叶片ID"), 0) h1_wlayout.addWidget(self.h1_combox3, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("信号类型"), 0) h1_wlayout.addWidget(self.h1_combox4, 0) h1_wlayout.setAlignment(Qt.AlignLeft) # 事件绑定 self.h1_combox1.currentIndexChanged.connect(self._wind_chooice) def _second_story(self, h2_wlayout): # 第二层布局 self.h2_date1 = QDateEdit(QDate.currentDate()) self.h2_date1.setCalendarPopup(True) self.h2_date2 = QDateEdit(QDate.currentDate()) self.h2_date2.setCalendarPopup(True) self.h2_button = QPushButton("运行") self.h2_button2 = QPushButton("停止") h2_wlayout.addItem(QSpacerItem(20, 20)) h2_wlayout.addWidget(QLabel("起始"), 0) h2_wlayout.addWidget(self.h2_date1) h2_wlayout.addItem(QSpacerItem(50, 20)) h2_wlayout.addWidget(QLabel("结束"), 0) h2_wlayout.addWidget(self.h2_date2) h2_wlayout.addItem(QSpacerItem(70, 20)) h2_wlayout.addWidget(self.h2_button) h2_wlayout.addWidget(self.h2_button2) h2_wlayout.setAlignment(Qt.AlignLeft) # 事件绑定 self.h2_button.clicked.connect(lambda: self._start_func()) self.h2_button2.clicked.connect(lambda: self._stop_func()) def _third_left(self, v4_wlayout, v5_wlayout): # 第三层布局 # 分量布局 v4_group_imf = QGridLayout() vbox1 = QGroupBox("分量值") self.radio_1 = QRadioButton("分量1") self.radio_2 = QRadioButton("分量2") self.radio_3 = QRadioButton("分量3") self.radio_4 = QRadioButton("分量4") self.radio_5 = QRadioButton("分量5") self.radio_6 = QRadioButton("分量6") self.radio_7 = QRadioButton("分量7") self.radio_8 = QRadioButton("分量8") self.radio_9 = QRadioButton("分量9") self.radio_1.setChecked(True) self.radio_val = self.radio_1.text() # 优先级布局 v4_group_prior = QGridLayout() vbox2 = QGroupBox("优先级") cb1 = QCheckBox("叶片1") cb2 = QCheckBox("叶片2") cb3 = QCheckBox("叶片3") self.v4_lineEdit = QLineEdit() # 时间布局 v4_group_time = QGridLayout() vbox3 = QGroupBox("时间选择") self.v4_combox1 = QComboBox(minimumWidth=100) self.v4_combox1.addItem("空") # 按键 v4_button = QPushButton("显示图形") # 写入网格格布局 v4_group_imf.addWidget(self.radio_1, 0, 0) v4_group_imf.addWidget(self.radio_2, 0, 1) v4_group_imf.addWidget(self.radio_3, 1, 0) v4_group_imf.addWidget(self.radio_4, 1, 1) v4_group_imf.addWidget(self.radio_5, 2, 0) v4_group_imf.addWidget(self.radio_6, 2, 1) v4_group_imf.addWidget(self.radio_7, 3, 0) v4_group_imf.addWidget(self.radio_8, 3, 1) v4_group_imf.addWidget(self.radio_9, 4, 0) v4_group_prior.addWidget(cb1, 1, 0) v4_group_prior.addWidget(cb2, 2, 0) v4_group_prior.addWidget(cb3, 3, 0) v4_group_prior.addWidget(QLabel("选择是:"), 4, 0) v4_group_prior.addWidget(self.v4_lineEdit, 5, 0) v4_group_time.addWidget(self.v4_combox1) # 写入左侧布局 vbox1.setLayout(v4_group_imf) vbox2.setLayout(v4_group_prior) vbox3.setLayout(v4_group_time) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox1) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox2) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox3) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(v4_button) v4_wlayout.addItem(QSpacerItem(50, 20)) # 事件绑定 self.radio_1.toggled.connect(lambda: self._changestyle(self.radio_1)) self.radio_2.toggled.connect(lambda: self._changestyle(self.radio_2)) self.radio_3.toggled.connect(lambda: self._changestyle(self.radio_3)) self.radio_4.toggled.connect(lambda: self._changestyle(self.radio_4)) self.radio_5.toggled.connect(lambda: self._changestyle(self.radio_5)) self.radio_6.toggled.connect(lambda: self._changestyle(self.radio_6)) self.radio_7.toggled.connect(lambda: self._changestyle(self.radio_7)) self.radio_8.toggled.connect(lambda: self._changestyle(self.radio_8)) self.radio_9.toggled.connect(lambda: self._changestyle(self.radio_9)) cb1.stateChanged.connect(lambda: self._prior_func(cb1)) cb2.stateChanged.connect(lambda: self._prior_func(cb2)) cb3.stateChanged.connect(lambda: self._prior_func(cb3)) v4_button.clicked.connect(lambda: self._show_func(v5_wlayout)) def _fouth_right(self, v5_wlayout): # 加载波形图 self.tmp_plt = plt_init() v5_wlayout.addWidget(self.tmp_plt) def _my_line(self, var=True): # var 为True时,为横线,否则为竖线 line = QFrame(self) line_var = QFrame.HLine sp_var = Qt.Horizontal if not var: line_var = QFrame.VLine sp_var = Qt.Vertical line.setFrameShape(line_var) line.setFrameShadow(QFrame.Sunken) splitter = QSplitter(sp_var) splitter.addWidget(line) return splitter def _wind_chooice(self): tmp_list = wind_mach_chooice(self.h1_combox1.currentText()) self.h1_combox2.clear() self.h1_combox2.addItems(tmp_list) def _start_func(self): a = self.h1_combox1.currentText() b = self.h1_combox2.currentText() c = self.h1_combox3.currentText() d = self.h1_combox4.currentText() e = self.h2_date1.dateTime().toString("yy-MM-dd") f = self.h2_date2.dateTime().toString("yy-MM-dd") self.start_func = RunThread(target=self._start_thread, args=(a, b, c, d, e, f)) #self.start_func = MyThread(target=self._print, args=(a, b, c, d, e, f)) self.start_func.start() def _stop_func(self): self.start_func.stop() print("运行结束") def _start_thread(self, a, b, c, d, e, f): print("*****运行打印*****") print(wind_mach_chooice(a)) print(a, b, c, d) print(e) print(f) print("%s" % (time.strftime('<%H:%M:%S>', time.localtime()))) self.v4_combox1.clear() self.v4_combox1.addItems(tmp_time_list) print("*****运行打印*****") def _changestyle(self, btn): # 单选项的判断函数 if btn.isChecked(): self.radio_val = btn.text() #print("%s"%(time.strftime('<%H:%M:%S>', time.localtime()))) def _prior_func(self, cb): # 复选框内容添加 if cb.isChecked(): if cb.text()[-1] not in self.Items: self.Items.append(cb.text()[-1]) shop_cart = ",".join(self.Items) self.v4_lineEdit.setText(shop_cart) else: if cb.text()[-1] in self.Items: self.Items.remove(cb.text()[-1]) shop_cart = ",".join(self.Items) self.v4_lineEdit.setText(shop_cart) def _show_func(self, v5_wlayout): print("*****显示打印*****") print(self.radio_val) num = self.v4_lineEdit.text() print(self.v4_combox1.currentText()) v5_wlayout.removeWidget(self.tmp_plt) self.tmp_plt = plt_show(num) v5_wlayout.addWidget(self.tmp_plt) print("*****显示打印*****")
class ComparisonInputDialog(QDialog): def __init__(self, parent=None): super(ComparisonInputDialog, self).__init__(parent) self.resize(200, 300) self.selectedCoin = 'BTC' self.coinList = ["BTC", "ETH", "LTC", "ZEC"] self.coinDropdown = QComboBox() self.setStyleSheet(''' QComboBox::item:checked { font-weight: bold; height: 16px; } ''') for coin in self.coinList: self.coinDropdown.addItem(coin) self.startDate = QDateEdit(self) self.startDate.setCalendarPopup(True) self.endDate = QDateEdit(self) self.endDate.setCalendarPopup(True) self.startDate.setDate(QDate(2017, 1, 1)) self.endDate.setDate(QDate(2018, 1, 1)) mainLayout = QVBoxLayout() self.label1 = QLabel("Coin: ") mainLayout.addWidget(self.label1) mainLayout.addWidget(self.coinDropdown) self.label2 = QLabel("Start Date: ") mainLayout.addWidget(self.label2) mainLayout.addWidget(self.startDate) self.label3 = QLabel("End Date: ") mainLayout.addWidget(self.label3) mainLayout.addWidget(self.endDate) self.okButton = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.okButton.accepted.connect(self.accept) self.okButton.rejected.connect(self.reject) mainLayout.addWidget(self.okButton) self.setLayout(mainLayout) self.date1 = self.startDate.dateTime().toPyDateTime() self.date2 = self.endDate.dateTime().toPyDateTime() self.startDate.dateTimeChanged.connect(self.startChange) self.endDate.dateTimeChanged.connect(self.endChange) self.coinDropdown.currentTextChanged.connect(self.coinChange) def startChange(self, date): self.date1 = date.toPyDateTime() def endChange(self, date): self.date2 = date.toPyDateTime() def coinChange(self, coin): self.selectedCoin = self.coinDropdown.currentText() @staticmethod def getUserInput(parent=None): dialog = ComparisonInputDialog(parent) result = dialog.exec_() startDate = dialog.date1 endDate = dialog.date2 coin = dialog.selectedCoin return (startDate, endDate, coin, result == QDialog.Accepted)
class mainScreen(QWidget): def __init__(self, userIndex, *args, **kwargs): super().__init__() self.dir_path = get_dir_path() self.userIndex = userIndex self.databasePath = "{}Databases/user{}.db".format( self.dir_path, hex(self.userIndex)[2:]) self.dbObj = sql_functions( self.databasePath ) #Kullanıcının günlük aktivite bilgilerinin saklandığı veritabanına bağlanılır self.rangeCount = 0 self.last = None self.ranges = list() self.jobNames = list() self.data_dict = None self.dataTypes = [(str, "str"), (str, "str"), (int, "int"), (int, "int"), (int, "int"), (int, "int")] self.predictionVariables = [ "Aktivite Adı", "İsteklilik", "Yorgunluk", "Moral", "Son Verim" ] self.dayVariables = [ "Date", "TimeRange", "Willingness", "Fatigue", "Morale", "Efficiency" ] self.sleepVariables = ["Date", "SleepRange", "SleepEfficiency"] self.newDateDBConfigurationText = "('Job','TEXT'),('TimeRange','TEXT'),('Willingness','INT'), ('Fatigue','INT'), ('Morale','INT'),('Efficiency','INT')" self.setWindowTitle("Proje") self.initUI() def initUI(self): ############################ # Layout'ların tanımlanması self.mainVerticalLayout = QVBoxLayout() self.upHorizontalLayout = QHBoxLayout() self.middleHorizontalLayout = QHBoxLayout() self.middleHorizontalLayoutRightVerticalLayout = QVBoxLayout() self.downHorizontalLayout = QHBoxLayout() self.predictionLayout = QHBoxLayout() #Gölgeler shadow = QGraphicsDropShadowEffect(blurRadius=5, xOffset=3, yOffset=3) shadow2 = QGraphicsDropShadowEffect(blurRadius=6, xOffset=5, yOffset=5) #Widget'lerin tanımlanması,tasarlanması ve layout'lara eklenemesi ############################ self.imageCheckout = QLabel() self.textCheckout = QLabel() ############################ self.sleepLabel = QLabel() self.sleepLabel.setText("Uyku Saatleri :") self.sleepLabel.setMaximumWidth(150) self.sleepLabel.setStyleSheet(""" color :#f2f3f4; background-color:#3b444b; border-left:4px Solid #a52a2a; border-right:4px Solid #a52a2a; padding:4px; font-size:14px; font-family:Courier; border-radius:1px; font-weight:650; """) self.sleepLabel.setGraphicsEffect(shadow) sep0 = QLabel(":") sep1 = QLabel(":") sep2 = QLabel("-") self.sleepLabelhourCombo1 = QComboBox() self.sleepLabelhourCombo2 = QComboBox() for i in range(24): if i < 10: element = "0" + str(i) else: element = str(i) self.sleepLabelhourCombo1.addItem(element, i) #element,index self.sleepLabelhourCombo2.addItem(element, i) #element,index self.sleepLabelMinuteCombo1 = QComboBox() self.sleepLabelMinuteCombo2 = QComboBox() for i in range(60): if i < 10: element = "0" + str(i) else: element = str(i) self.sleepLabelMinuteCombo1.addItem(element, i) self.sleepLabelMinuteCombo2.addItem(element, i) self.ComboHorizontalLayout = QHBoxLayout() self.ComboHorizontalLayout.addWidget(self.sleepLabelhourCombo1) self.ComboHorizontalLayout.addWidget(sep0) self.ComboHorizontalLayout.addWidget(self.sleepLabelMinuteCombo1) self.ComboHorizontalLayout.addWidget(sep2) self.ComboHorizontalLayout.addWidget(self.sleepLabelhourCombo2) self.ComboHorizontalLayout.addWidget(sep1) self.ComboHorizontalLayout.addWidget(self.sleepLabelMinuteCombo2) self.ComboHorizontalLayout.addStretch() self.sleepEfficiencyLabel = QLabel() self.sleepEfficiencyLabel.setText("Uyku verimi : ") self.sleepEfficiencyLabel.setStyleSheet(""" color :#f2f3f4; background-color:#3b444b; border-left:4px Solid #a52a2a; border-right:4px Solid #a52a2a; padding:4px; font-size:14px; font-family:Courier; border-radius:1px; font-weight:650; """) self.sleepEfficiencyLabel.setMaximumWidth(150) self.sleepEfficiencyLabel.setGraphicsEffect(shadow) self.sleepEfficiency = QLineEdit() self.sleepEfficiency.setMaximumWidth(168) self.sleepEfficiency.setText("0-100") self.addRange = QPushButton() self.addRange.setText("Yeni saat aralığı ekle") self.addRange.setStyleSheet(""" font-family : "Times New Roman"; font-size : 14px; font-weight:650; background-color:#065535; color:#ffc100; """) self.addRange.setMaximumWidth(150) self.addRange.setGraphicsEffect(shadow) self.addRange.clicked.connect(lambda: self.changeHorizontalHeader(-1)) ############################ self.Date = QDateEdit() date = QDate() currentDate = date.currentDate() self.Date.setDate(currentDate) ############################ ############################ self.profileButton = QPushButton("Profil") self.profileButton.clicked.connect(self.profilePageRedirection) ############################ self.downHorizontalLayout.addStretch() self.save = QPushButton() self.save.setText("Kaydet") self.save.setGraphicsEffect(shadow) self.save.setStyleSheet(""" color : #A52A2A; font-weight:bold; """) self.save.clicked.connect( self.saveToDataBase ) #Bilgileri veritabanına kaydeden fonksiyonun çağrılması ############################ #Zamalayıcılar ############################ self.timer = QTimer() self.timer.timeout.connect(self._update) self.timer.start(1000) self.timer_job = QTimer() self.timer_job.timeout.connect(self.predictionButtonControl) self.timer_job.start(1000) self.fittedColumnsTimer = QTimer() self.fittedColumnsTimer.timeout.connect(self.AlltimeFittedColumns) self.fittedColumnsTimer.start(1000) ############################ #Tablo self.tableWidget = QTableWidget() self.tableWidget.setGeometry(QRect(0, 40, 801, 511)) self.tableWidget.setRowCount(len(self.predictionVariables)) self.tableWidget.horizontalHeader().sectionDoubleClicked.connect( self.changeHorizontalHeader) self.tableWidget.setVerticalHeaderLabels(self.predictionVariables) ############################ self.efficiencyPredictionButton = QPushButton() self.efficiencyPredictionButton.setMaximumWidth(160) self.efficiencyPredictionButton.clicked.connect( self.efficiencyPredictionButtonFunction ) #Eğer gerekli şartlar sağlanmış ise tahmin şartları sağlanmış ise tahmin sayfasına yönledirecek fonksiyon self.efficiencyPredictionButton.setText("Tahmin Sayfası") self.efficiencyPredictionButton.setGraphicsEffect(shadow2) self.efficiencyPredictionButton.setStyleSheet(""" font-family:"Times New Roman"; font-size:14px; font-weight: 650; color: #d1b9c7; background-color: #130015; """) self.predictionLayout.addWidget(self.efficiencyPredictionButton) self.upHorizontalLayout.addWidget(self.Date) self.upHorizontalLayout.addStretch() self.upHorizontalLayout.addWidget(self.profileButton) self.middleHorizontalLayout.addWidget(self.tableWidget) self.middleHorizontalLayoutRightVerticalLayout.addWidget(self.addRange) self.middleHorizontalLayoutRightVerticalLayout.addWidget( self.sleepLabel) self.middleHorizontalLayoutRightVerticalLayout.addLayout( self.ComboHorizontalLayout) self.middleHorizontalLayoutRightVerticalLayout.addWidget( self.sleepEfficiencyLabel) self.middleHorizontalLayoutRightVerticalLayout.addWidget( self.sleepEfficiency) self.middleHorizontalLayoutRightVerticalLayout.addLayout( self.predictionLayout) self.middleHorizontalLayoutRightVerticalLayout.addStretch() self.downHorizontalLayout.addWidget(self.textCheckout) self.downHorizontalLayout.addWidget(self.imageCheckout) self.downHorizontalLayout.addWidget(self.save) self.middleHorizontalLayout.addLayout( self.middleHorizontalLayoutRightVerticalLayout) #Oluşturulan Layout'ların ana layouta eklenmesi self.mainVerticalLayout.addLayout(self.upHorizontalLayout) self.mainVerticalLayout.addLayout(self.middleHorizontalLayout) self.mainVerticalLayout.addLayout(self.downHorizontalLayout) self.newrangeWidget = newTimeRange() self.newrangeWidget.setHidden(True) self.newrangeWidget.newRangeSignal.connect(self.getNewRange) self.mainVerticalLayout.addWidget(self.newrangeWidget) #Tablo boyutlarının ayarlanması self.tableWidget.setMaximumWidth(666) self.tableWidget.setMinimumWidth(286) self.tableWidget.setMaximumHeight(180) self.tableWidget.setMinimumHeight(180) self.setMaximumHeight(171) self.setLayout(self.mainVerticalLayout) #Tablo ismine'sağ tıklandığında menu açılmasını sağlayan kod parçası self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) # self.tableWidget.customContextMenuRequested.connect(self.generateMenu) self.tableWidget.viewport().installEventFilter(self) ################################## def eventFilter( self, source, event ): #gelen event'ı filtreler ve eğer event aktivite ismine sağ tıklama ise menu açığa çıkartır. if (event.type() == QEvent.MouseButtonPress and event.buttons() == Qt.RightButton and source is self.tableWidget.viewport()): item = self.tableWidget.itemAt(event.pos()) if item is not None and item.row() == 0: self.menu = QMenu(self) self.menu.addAction("Aktivite bilgisi") self.menu.addAction("Aktiviteyi sil") self.menu.triggered.connect( self.menuActions) #Menu aksiyonlarına yönlendirir. else: self.menu = QMenu(self) return super(mainScreen, self).eventFilter(source, event) def generateMenu(self, pos): self.menu.exec_(self.tableWidget.mapToGlobal(pos)) def menuActions(self, action): action = action.text() if action == "Aktiviteyi sil": # aksiyon bu ise seçili aktivite kolonu veritabanından ve arayüz tablosundan silinir. timeRangeIndex = self.tableWidget.currentColumn() timeRange = self.ranges[timeRangeIndex] date = self.getValidDate() self.dbObj.delete_row(date, "TimeRange", timeRange) self._update(specialSynchronize=True) elif action == "Aktivite bilgisi": # aksiyon bu ise seçili aktivitenin bilgilerinin göstildiği sayfa açılır. activity = self.tableWidget.currentItem().text() needToDo = 15 try: data = self.data_dict[activity] doneTimes = len(data.index) except KeyError: doneTimes = 0 finally: popWindow = JobInfo(activity=activity, doneTimes=doneTimes, needToDo=needToDo) popWindow.show() def efficiencyPredictionButtonFunction( self): #verim tahmin sayfasına yönlendirir. popWindow = PredictionForm(self.data_dict, self.userIndex) popWindow.show() def findSeperator(self, data): # Verideki ayracı bulur seperator = re.findall("\D", data)[0] return seperator def rangeAmounts(self, ranges): #saat aralık miktarlarını döndürür. amounts = list() for i in ranges: if i != "[*]": data = tuple(i.split("-")) start = data[0].split(":") end = data[1].split(":") amount = self.diffrenceBetweenTwoHour(start, end) amounts.append(amount) return amounts def predictionButtonControl( self ): # Eldeki veri kümesinin tahmin şartlarını sağlayıp sağlamadığına bakar ve buna göre tahmin formu butonunu aktive eder ya da tam tersi. obj = preproccesedData(dayTableColumns=self.dayVariables, sleepTableColumns=self.sleepVariables, rawDatabasePath=self.databasePath) data = obj.get_data_Dict # Veri kümesinin kullanılabilirliği şartı ise en az iki ayrı aktivite kümesi olması ve her aktivite kümesinin en az elemanının olmasıdır. usableDatasetCount = 0 # Kullanılabilir aktivite küme sayısını bulur. for key in data: specifedDataSet = data[key] if len(specifedDataSet.index) < 15: pass else: usableDatasetCount += 1 if usableDatasetCount < 2: # Eğer 2 tane ya da daha fazla ise tahmin form butonu kilidi kalkar self.efficiencyPredictionButton.setDisabled(True) else: self.efficiencyPredictionButton.setEnabled(True) self.data_dict = data def diffrenceBetweenTwoHour(self, hour1, hour2=(0, 0), data_splittation=False ): #İki saat arasındaki otomatik olarak bulur if data_splittation: hour1, hour2 = [hour.split(":") for hour in hour1.split("-")] h1 = int(hour1[0]) m1 = int(hour1[1]) h2 = int(hour2[0]) m2 = int(hour2[1]) d1 = datetime.timedelta(hours=h1, minutes=m1) d2 = datetime.timedelta(hours=h2, minutes=m2) amount = d2 - d1 amount = amount.seconds / 60 / 60 return amount def profilePageRedirection(self): from ProfilePage import Profile popWindow = Profile(self.userIndex) popWindow.show() def getValidDate( self, makeINT=0): #Şu anki seçili tarihi parametrelere göre döndürür. date = self.Date.dateTime().toPyDateTime().date() if bool(makeINT): date = [int(i) for i in str(date).split("-")][::-1] else: dateN = "" for var in str(date).split("-")[::-1]: dateN += var + "-" dateN = dateN[:-1] date = dateN return date def usableClock(self, range_): #Saat aralığını kullanılabilir hale getirir. h1, h2 = range_.split("-") h1 = h1.split(":") h2 = h2.split(":") return (h1, h2) def inputControlAffecters(self, inData): try: inp = int(inData) if (inp > 100) or (inp < 0): return False return True except ValueError: return False def _update( self, specialSynchronize=False ): #Otomatik olarak tabloyu veritabanındaki bilgiler ile doldurur. date = self.getValidDate(makeINT=1) #Sayısal olan if not (self.last == date) or specialSynchronize: tableName = self.getValidDate( ) #Veritabanı kodunda kullanılabilir olan self.ranges = list() self.last = date sleepDataDates = [ tup[0].split(self.findSeperator(tup[0])) for tup in self.dbObj.get_column_by_name("SleepTable", "Date") ] sleepDataDates = [[int(element) for element in upElement] for upElement in sleepDataDates] controlDate = [int(element) for element in date] if controlDate in sleepDataDates: row = self.dbObj.get_row("SleepTable", "Date", tableName) range_, efficiency_ = row[1], row[2] self.sleepEfficiency.setText(str(efficiency_)) h1, h2 = self.usableClock(range_) self.sleepLabelhourCombo1.setCurrentIndex(int(h1[0])) self.sleepLabelMinuteCombo1.setCurrentIndex(int(h1[1])) self.sleepLabelhourCombo2.setCurrentIndex(int(h2[0])) self.sleepLabelMinuteCombo2.setCurrentIndex(int(h2[1])) else: self.sleepEfficiency.setText("0-100") self.sleepLabelhourCombo1.setCurrentIndex(0) self.sleepLabelhourCombo2.setCurrentIndex(0) self.sleepLabelMinuteCombo1.setCurrentIndex(0) self.sleepLabelMinuteCombo2.setCurrentIndex(0) createControl = 0 existanceControl = 0 for tup in self.dbObj.tableList(): try: element = tup[0] seperator = self.findSeperator(element) element = [int(i) for i in element.split(seperator)] if (date == element) and ( self.dbObj.get_row_count(tableName) > 0): createControl = 1 existanceControl = 1 else: pass except ValueError: pass if not (createControl): #Eğer tablo yoksa yaratlılır. exec("self.dbObj.create_table(tableName,{})".format( self.newDateDBConfigurationText) ) #Hata olmaması için tablo yaratlılır if existanceControl: for tup in self.dbObj.tableList(): try: columns = self.dbObj.get_columns(tup[0]) hourRanges = self.dbObj.get_column_by_name( tableName, "TimeRange") hourRanges = [tup[0] for tup in hourRanges] self.ranges = hourRanges self.tableWidget.setColumnCount(len(hourRanges)) self.tableWidget.setHorizontalHeaderLabels(hourRanges) columns.remove("TimeRange") indexX = 0 for column in columns: rows = self.dbObj.get_column_by_name( tableName, column) rows = [tup[0] for tup in rows] indexY = 0 for row in rows: self.tableWidget.setItem( indexX, indexY, QTableWidgetItem(str(row))) indexY += 1 indexX += 1 except ValueError: pass RangeAmounts = self.rangeAmounts(hourRanges) for index in range(len(RangeAmounts)): self.tableWidget.setColumnWidth( index, self.tableWidget.columnWidth(index) * RangeAmounts[index]) else: # Eğer seçili güne dair bir bilgi yok ise bu devre çalışır. self.tableWidget.clear() self.tableWidget.setVerticalHeaderLabels( self.predictionVariables) self.tableWidget.setColumnCount(1) self.tableWidget.setHorizontalHeaderLabels(["[\u2795]"]) def AlltimeFittedColumns( self): #Kolon uzunluklarının her zaman sabit kalmasını sağlar for index in range(self.tableWidget.columnCount()): self.tableWidget.setColumnWidth(index, 100) def getSleepRangefromCombo( self): #Combobox değerlerini string şeklinde döndürür. range_ = self.sleepLabelhourCombo1.currentText( ) + ":" + self.sleepLabelMinuteCombo1.currentText( ) + "-" + self.sleepLabelhourCombo2.currentText( ) + ":" + self.sleepLabelMinuteCombo2.currentText() return range_ def saveToDataBase( self): #Seçili tarihte girili bilgileri veritabanınına kayıt eder. date = self.getValidDate() sleepDataDates = [ tup[0].split(self.findSeperator(tup[0])) for tup in self.dbObj.get_column_by_name("SleepTable", "Date") ] separetedDate = date.split(self.findSeperator(date)) try: #Eğer uyku verimi değişkenine geçersiz değer girilirse... sleepEf = int(self.sleepEfficiency.text()) sleepRa = self.getSleepRangefromCombo() except ValueError: self.sleepEfficiency.setText( "Uyku verimi kısmı 1 ile 100 arasında sayısal bir değer alır.Başka bir veritipi girişi tespit edildi..." ) return 0 if separetedDate in sleepDataDates: self.dbObj.delete_row("SleepTable", "*Date", date) self.dbObj.insert_data("SleepTable", date, sleepRa, sleepEf) else: self.dbObj.insert_data("SleepTable", date, sleepRa, sleepEf) if self.dbObj.get_row_count(date): for dif in self.ranges: if dif != "": self.dbObj.delete_row(date, "*TimeRange", dif) else: pass if self.dbObj.get_row_count(date): pass else: pass timeRanges = self.ranges errorColumns = list() if len(timeRanges) != 0: column_index = 0 for column in range(self.tableWidget.columnCount()): rangeData = timeRanges[column] if rangeData != "[\u2795]" and rangeData != "" and self.splitableHourCheck( rangeData): data = list() index = 0 for row in range(self.tableWidget.rowCount()): try: inf = self.tableWidget.item(row, column).text() if row == 0: pass else: position = (row, column) ability = self.inputControlAffecters(inf) if ability: pass else: self.showError( "Geçersiz formatta bilgi girişi.Hata kaynağı konumu : {}" .format(position)) return 0 except AttributeError: nowD = [self.dataTypes[0]] + self.dataTypes[2:] if nowD[index][0] == str: inf = "" else: inf = 0 data.append(inf) index += 1 data.insert(1, rangeData) dataChanged = list() for iteration, dtype in zip( data, self.dataTypes): #Veri tipleri düzenenir.. if not isinstance(iteration, dtype[0]): try: iteration = eval("{}(iteration)".format( dtype[1])) except ValueError: pass dataChanged.append(iteration) self.dbObj.insert_data( date, *data) #Bilginin veritabanına yüklenmesi else: errorColumns.append(column_index) column_index += 1 #Kullanıcıya kayıtın başarı durumunun bildirilmesi if not bool(len(errorColumns)): self.showSuccess("Bilgiler kaydedilmiştir.") else: columnsText = "" for i in errorColumns: columnsText += str(i + 1) + "," columnsText = columnsText[:-1] self.showError( "Geçersiz saat aralığı girişi.Hata kaynağı sütunları : {} ". format(columnsText)) def showSuccess(self, message): self.textCheckout.setText(message) self.textCheckout.setStyleSheet(""" font-family:Courier; font-size:14px; font-weight:650; color :#5A2C63; background-color:#C4FFC1; border-left:4px solid #35632c; padding : 4px; """) self.imageCheckout.setPixmap( QPixmap("{}Images/tickIconAdjusted.png".format(self.dir_path))) QTimer.singleShot(3000, lambda: self.textCheckout.setText("")) QTimer.singleShot(3000, lambda: self.textCheckout.setStyleSheet("")) QTimer.singleShot(3000, lambda: self.imageCheckout.setPixmap(QPixmap())) def showError(self, errorMessage): self.textCheckout.setText(errorMessage) self.textCheckout.setStyleSheet(""" font-family:Courier; font-size:14px; font-weight:650; color:#d22323; background-color:#f4919f; border-left:8px solid #4F646B; padding:6px; """) self.imageCheckout.setPixmap( QPixmap("{}Images/error.png".format(self.dir_path))) QTimer.singleShot(4000, lambda: self.textCheckout.setText("")) QTimer.singleShot(4000, lambda: self.textCheckout.setStyleSheet("")) QTimer.singleShot(4000, lambda: self.imageCheckout.setPixmap(QPixmap())) def splitableHourCheck( self, data): #Saat girdisinin bölünebilirliğini kontrol eder try: h1, h2 = [hour.split(":") for hour in data.split("-")] if (len(h1) and len(h2)) == 2: return True else: return False except: return False def changeHorizontalHeader(self, index): #Yeni saat aralığının girilmesi #Saat aralığı girilirken şu şekil kullanılmalıdır: # AA:BB-CC:DD # Aksi takdirde kodlar veri tabanına hata ortaya çıkar. if index == -1: index = self.tableWidget.columnCount() if index == 1 and self.ranges == []: #and self.tableWidget.horizontalHeader.labels == "[\u2795]" index = 0 else: # Eğer tabloda saat aralığı yok ise otomatik eklenen kolon sıkıntı yaratacaktır. # Bu sebeple index sıfıra eşitlenir. pass self.horizontalHeaderIndex = index self.newrangeWidget.setHidden(False) @pyqtSlot(str) def getNewRange(self, newRange): #Düzenlemeleri yap if newRange: try: time = [hour.split(":") for hour in newRange.split("-")] #Çalışma verimi self.tableWidget.setColumnWidth(self.horizontalHeaderIndex, 150) self.ranges.append(newRange) self.tableWidget.setColumnCount(len(self.ranges)) self.tableWidget.setHorizontalHeaderLabels(self.ranges) except IndexError: pass else: pass self.newrangeWidget.cleanInputs() self.newrangeWidget.setHidden(True)
class Qt_Test_Frame(QMainWindow): Items = [] def __init__(self): #super(Qt_Test_Frame, self).__init__(*args, **kw) super().__init__() self.graph = Graph_Func() self.graph2 = Graph_Func() # 初始化界面 self._initUI() self.show() def _initUI(self): self.setWindowTitle("风机采集图形化v2") self.resize(1024, 768) wwg = QWidget() # 全局布局 wlayout = QVBoxLayout() h1_wlayout = QHBoxLayout() h2_wlayout = QHBoxLayout() h3_wlayout = QHBoxLayout() v4_wlayout = QVBoxLayout() self.v5_wlayout = QVBoxLayout() self.statusBar().showMessage("状态栏") # 第一层 self._frist_story(h1_wlayout) # 第二层 self._second_story(h2_wlayout) # 第三层 左 self._third_left(v4_wlayout) # 第三层 右 self._fouth_right() # 加载 splt = self._my_line() splt2 = self._my_line(False) wlayout.addSpacing(10) # 增加布局间距 wlayout.addLayout(h1_wlayout) wlayout.addSpacing(10) # 增加布局间距 wlayout.addLayout(h2_wlayout) wlayout.addSpacing(10) # 增加布局间距 wlayout.addWidget(splt) wlayout.addLayout(h3_wlayout) wlayout.addWidget(self.statusBar()) h3_wlayout.addLayout(v4_wlayout, 0) h3_wlayout.addWidget(splt2) h3_wlayout.addLayout(self.v5_wlayout, 2) #wlayout.setAlignment(Qt.AlignTop) wwg.setLayout(wlayout) self.setCentralWidget(wwg) def _frist_story(self, h1_wlayout): # 第一层布局 self.h1_combox1 = QComboBox(minimumWidth=100) self.h1_combox1.addItems(ParaEMD().FengChang) self.h1_combox2 = QComboBox(minimumWidth=100) self.h1_combox2.addItems(ParaEMD().wind_mach_chooice( self.h1_combox1.currentText())) self.h1_combox3 = QComboBox(minimumWidth=100) self.h1_combox3.addItems(ParaEMD().IdBlade) self.h1_combox4 = QComboBox(minimumWidth=100) self.h1_combox4.addItems(ParaEMD().TypeData) # 行为测试 暂时无法使用 h1_cb1_action = QAction("风场选择", self) h1_cb1_action.setStatusTip("请选择风场") self.h1_combox1.addAction(h1_cb1_action) h1_wlayout.addItem(QSpacerItem(20, 20)) h1_wlayout.addWidget(QLabel("风场"), 0) h1_wlayout.addWidget(self.h1_combox1, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("风机"), 0) h1_wlayout.addWidget(self.h1_combox2, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("叶片ID"), 0) h1_wlayout.addWidget(self.h1_combox3, 0) h1_wlayout.addItem(QSpacerItem(40, 20)) h1_wlayout.addWidget(QLabel("信号类型"), 0) h1_wlayout.addWidget(self.h1_combox4, 0) h1_wlayout.setAlignment(Qt.AlignLeft) # 事件绑定 self.h1_combox1.currentIndexChanged.connect(self._wind_chooice) def _second_story(self, h2_wlayout): # 第二层布局 self.h2_date1 = QDateEdit(QDate.currentDate()) self.h2_date1.setCalendarPopup(True) self.h2_date2 = QDateEdit(QDate.currentDate()) self.h2_date2.setCalendarPopup(True) self.h2_button = QPushButton("运行") self.h2_button2 = QPushButton("停止") h2_wlayout.addItem(QSpacerItem(20, 20)) h2_wlayout.addWidget(QLabel("起始"), 0) h2_wlayout.addWidget(self.h2_date1) h2_wlayout.addItem(QSpacerItem(50, 20)) h2_wlayout.addWidget(QLabel("结束"), 0) h2_wlayout.addWidget(self.h2_date2) h2_wlayout.addItem(QSpacerItem(70, 20)) h2_wlayout.addWidget(self.h2_button) h2_wlayout.addWidget(self.h2_button2) h2_wlayout.setAlignment(Qt.AlignLeft) # 事件绑定 self.h2_button.clicked.connect(lambda: self._start_func()) self.h2_button2.clicked.connect(lambda: self._stop_func()) def _third_left(self, v4_wlayout): # 第三层布局 # 分量布局 v4_group_imf = QGridLayout() vbox1 = QGroupBox("分量值") self.radio_1 = QRadioButton("分量1") self.radio_2 = QRadioButton("分量2") self.radio_3 = QRadioButton("分量3") self.radio_4 = QRadioButton("分量4") self.radio_5 = QRadioButton("分量5") self.radio_6 = QRadioButton("分量6") self.radio_7 = QRadioButton("分量7") self.radio_8 = QRadioButton("分量8") self.radio_9 = QRadioButton("分量9") self.radio_1.setChecked(True) self.radio_val = self.radio_1.text() # 优先级布局 v4_group_prior = QGridLayout() vbox2 = QGroupBox("优先级") cb1 = QCheckBox("叶片1") cb2 = QCheckBox("叶片2") cb3 = QCheckBox("叶片3") self.v4_lineEdit = QLineEdit() # 时间布局 v4_group_time = QGridLayout() vbox3 = QGroupBox("时间选择") self.v4_combox1 = QComboBox(minimumWidth=100) self.v4_combox1.addItem("空") # 按键 v4_button = QPushButton("显示图形") # 写入网格格布局 v4_group_imf.addWidget(self.radio_1, 0, 0) v4_group_imf.addWidget(self.radio_2, 0, 1) v4_group_imf.addWidget(self.radio_3, 1, 0) v4_group_imf.addWidget(self.radio_4, 1, 1) v4_group_imf.addWidget(self.radio_5, 2, 0) v4_group_imf.addWidget(self.radio_6, 2, 1) v4_group_imf.addWidget(self.radio_7, 3, 0) v4_group_imf.addWidget(self.radio_8, 3, 1) v4_group_imf.addWidget(self.radio_9, 4, 0) v4_group_prior.addWidget(cb1, 1, 0) v4_group_prior.addWidget(cb2, 2, 0) v4_group_prior.addWidget(cb3, 3, 0) v4_group_prior.addWidget(QLabel("选择是:"), 4, 0) v4_group_prior.addWidget(self.v4_lineEdit, 5, 0) v4_group_time.addWidget(self.v4_combox1) # 写入左侧布局 vbox1.setLayout(v4_group_imf) vbox2.setLayout(v4_group_prior) vbox3.setLayout(v4_group_time) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox1, 1) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox2, 1) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(vbox3, 0) v4_wlayout.addItem(QSpacerItem(50, 20)) v4_wlayout.addWidget(v4_button, 1) v4_wlayout.addItem(QSpacerItem(50, 20)) # 事件绑定 self.radio_1.toggled.connect(lambda: self._changestyle(self.radio_1)) self.radio_2.toggled.connect(lambda: self._changestyle(self.radio_2)) self.radio_3.toggled.connect(lambda: self._changestyle(self.radio_3)) self.radio_4.toggled.connect(lambda: self._changestyle(self.radio_4)) self.radio_5.toggled.connect(lambda: self._changestyle(self.radio_5)) self.radio_6.toggled.connect(lambda: self._changestyle(self.radio_6)) self.radio_7.toggled.connect(lambda: self._changestyle(self.radio_7)) self.radio_8.toggled.connect(lambda: self._changestyle(self.radio_8)) self.radio_9.toggled.connect(lambda: self._changestyle(self.radio_9)) cb1.stateChanged.connect(lambda: self._prior_func(cb1)) cb2.stateChanged.connect(lambda: self._prior_func(cb2)) cb3.stateChanged.connect(lambda: self._prior_func(cb3)) v4_button.clicked.connect(lambda: self._show_func()) def _fouth_right(self): # 加载波形图 #self.tmp_plt = self.graph.plt_init() self.v5_wlayout.addWidget(self.graph, 2) self.v5_wlayout.addWidget(self.graph2, 1) def _my_line(self, var=True): # var 为True时,为横线,否则为竖线 line = QFrame(self) line_var = QFrame.HLine sp_var = Qt.Horizontal if not var: line_var = QFrame.VLine sp_var = Qt.Vertical line.setFrameShape(line_var) line.setFrameShadow(QFrame.Sunken) splitter = QSplitter(sp_var) splitter.addWidget(line) return splitter def _wind_chooice(self): tmp_list = ParaEMD().wind_mach_chooice(self.h1_combox1.currentText()) self.h1_combox2.clear() self.h1_combox2.addItems(tmp_list) def _start_func(self): a = self.h1_combox1.currentText() b = self.h1_combox2.currentText() c = self.h1_combox3.currentText() d = self.h1_combox4.currentText() e = self.h2_date1.dateTime().toString("yyyy/MM/dd") f = self.h2_date2.dateTime().toString("yyyy/MM/dd") self.start_thread = MyThread(target=self._start_thread, args=(a, b, c, d, e, f)) self.start_thread.start() def _stop_func(self): # 停止按钮 self.start_thread.stop() print("运行结束") # 需要修改 def _start_thread(self, *args): """ 运行按钮线程,传入参数 :param args: 风场, 风机, 叶片ID, 信号类型,开始时间, 结束时间 :return: """ # print("*****运行键打印*****") # for var in args: # print(var) # location = args[0] fan = args[1] fanid = args[2] typedata = args[3] start_time = args[4] end_time = args[5] ParaEMD().EMDTRS(location, fan, fanid, typedata, start_time, end_time) #主程序 self.v4_combox1.clear() # 等函数执行完后,返回时间选择列表 参数为时间列表 self.v4_combox1.addItems(ParaEMD().tmp_list()) print("*****运行键打印*****") def _changestyle(self, btn): # 单选项的判断函数 if btn.isChecked(): self.radio_val = btn.text() #print("%s"%(time.strftime('<%H:%M:%S>', time.localtime()))) def _prior_func(self, cb): # 复选框内容添加 if cb.isChecked(): if cb.text()[-1] not in self.Items: self.Items.append(cb.text()[-1]) shop_cart = ",".join(self.Items) self.v4_lineEdit.setText(shop_cart) else: if cb.text()[-1] in self.Items: self.Items.remove(cb.text()[-1]) shop_cart = ",".join(self.Items) self.v4_lineEdit.setText(shop_cart) # 需传改 def _show_func(self): """ a: IMF分量, b: 显示优先级, c: 时间选择列表 d: 叶片ID :return: """ print("*****显示打印*****") a = self.radio_val b = self.v4_lineEdit.text() c = self.v4_combox1.currentText() d = self.h1_combox3.currentText() # 在下面函数传入数据列表 参数为:CSV文件 self.graph.set_data(ParaEMD().test1_data()) #幅值数据 #添加题注的三个gD self.graph2.set_data(ParaEMD().test1_data()) #gD数据 # 下面为画图操作,无不用修改 #self.v5_wlayout.removeWidget(self.graph) #self.tmp_plt = self.graph.plt_show(b) #self.v5_wlayout.addWidget(self.tmp_plt) self.graph.plt_show(b) self.graph2.plt_show(b) print("*****显示打印*****")
class TransactionsQueryForm(QFormLayout): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # First line: Start Date self.label1 = QLabel(self.tr("Start Date")) self.start_date_edit = QDateEdit(datetime.now()) self.start_date_edit.setDisplayFormat("dd/MM/yyyy") self.start_date_edit.setCalendarPopup(True) # Just making sure that the start date is always before the end date self.start_date_edit.dateTimeChanged.connect(self.checkDates_startdate) self.setWidget(0, self.LabelRole, self.label1) self.setWidget(0, self.FieldRole, self.start_date_edit) # Second line: End Date self.label2 = QLabel(self.tr("End Date")) self.end_date_edit = QDateEdit(datetime.now()) self.end_date_edit.setDisplayFormat("dd/MM/yyyy") self.end_date_edit.setCalendarPopup(True) # Just making sure that the end date is always after the start date self.end_date_edit.dateTimeChanged.connect(self.checkDates_enddate) self.setWidget(1, self.LabelRole, self.label2) self.setWidget(1, self.FieldRole, self.end_date_edit) # Third line: Sender Account selection self.label3 = QLabel(self.tr("Sender Account")) self.senderaccount_select = QComboBox() self.senderaccount_select.addItem("All", BoldFont()) self.senderaccount_select.setEditable(True) self.senderaccount_select.setDuplicatesEnabled(False) currentsenderaccounts = [ a[0] for a in transactions.get_all_sender_accounts() ] self.senderaccount_select.addItems(currentsenderaccounts) self.setWidget(2, self.LabelRole, self.label3) self.setWidget(2, self.FieldRole, self.senderaccount_select) # Fourth line: Receiver Account selection self.label4 = QLabel(self.tr("Receiver Account")) self.receiveraccount_select = QComboBox() self.receiveraccount_select.addItem("All", BoldFont()) self.receiveraccount_select.setEditable(True) self.receiveraccount_select.setDuplicatesEnabled(False) currentreceiveraccounts = [ a[0] for a in transactions.get_all_receiver_accounts() ] self.receiveraccount_select.addItems(currentreceiveraccounts) self.setWidget(3, self.LabelRole, self.label4) self.setWidget(3, self.FieldRole, self.receiveraccount_select) def getCurrentQuery(self): """ Returns tuple with the start date, end date and current sender and receiver accounts of the query form """ startdate = datetime.strptime( self.start_date_edit.date().toString("dd.MM.yyyy"), "%d.%m.%Y") enddate = datetime.strptime( self.end_date_edit.date().toString("dd.MM.yyyy"), "%d.%m.%Y") senderaccount = self.senderaccount_select.currentText() receiveraccount = self.receiveraccount_select.currentText() return (startdate, enddate, senderaccount, receiveraccount) def checkDates_startdate(self): """ Making sure that the start date is not bigger than the end date """ if self.end_date_edit.dateTime() < self.start_date_edit.dateTime(): # set end date same as start date self.end_date_edit.setDate(self.start_date_edit.date()) def checkDates_enddate(self): """ Making sure that the start date is not bigger than the end date """ if self.start_date_edit.dateTime() > self.end_date_edit.dateTime(): # viceversa self.start_date_edit.setDate(self.end_date_edit.date())
class FilmReviewForm(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.title_line = QLineEdit() self.title_line.setPlaceholderText("Film Title") self.direct_line = QLineEdit() self.direct_line.setPlaceholderText("Director") self.cast_line = QLineEdit() self.cast_line.setPlaceholderText("Main Cast") self.rating_line = QLineEdit() self.rating_line.setPlaceholderText("Rating /10") self.comment_line = QLineEdit() self.comment_line.setPlaceholderText("Comments") self.mpaa_cb = QComboBox(self) self.mpaa_cb.addItems(list_choices["mpaa"]) self.date_cal = QDateEdit(self) self.date_cal.setCalendarPopup(True) self.genre_tb = QToolButton(self) self.genre_tb.setText("Select Genre(s)") self.genre_tm = QMenu(self) for g in list_choices["genre"]: action = self.genre_tm.addAction(g) action.setCheckable(True) self.genre_tb.setMenu(self.genre_tm) self.genre_tb.setPopupMode(QToolButton.InstantPopup) self.theme_tb = QToolButton(self) self.theme_tb.setText("Select Theme(s)") self.theme_tm = QMenu(self) for g in list_choices["theme"]: action = self.theme_tm.addAction(g) action.setCheckable(True) self.theme_tb.setMenu(self.theme_tm) self.theme_tb.setPopupMode(QToolButton.InstantPopup) quit_button = QPushButton() quit_button.setText("Quit") quit_button.clicked.connect(self.close) submit_button = QPushButton() submit_button.setText("Submit") submit_button.clicked.connect(self.submitForm) grid = QGridLayout() grid.addWidget(self.title_line, 0, 0) grid.addWidget(self.direct_line, 0, 1) grid.addWidget(self.genre_tb, 0, 2) grid.addWidget(self.theme_tb, 1, 2) grid.addWidget(self.date_cal, 1, 0) grid.addWidget(self.mpaa_cb, 1, 1) grid.addWidget(self.cast_line, 2, 0) grid.addWidget(self.rating_line, 2, 1) grid.addWidget(self.comment_line, 2, 2) grid.addWidget(submit_button, 3, 0) grid.addWidget(quit_button, 3, 2) self.setLayout(grid) self.setGeometry(400, 400, 400, 400) self.setWindowTitle("Movie Review Form") self.show() def submitForm(self): path = "movielist.xlsx" df1 = pd.read_excel(path) s_title = df1["Title"] s_dir = df1["Director"] s_genre = df1["Genre(s)"] s_theme = df1["Theme(s)"] s_rdate = df1["Release Date"] s_mpaa = df1["MPAA"] s_cast = df1["Cast"] s_rating = df1["Rating"] s_comment = df1["Comments"] title = pd.Series(self.title_line.text()) director = pd.Series(self.direct_line.text()) cast = pd.Series(self.cast_line.text()) rating = pd.Series(self.rating_line.text()) comment = pd.Series(self.comment_line.text()) mpaa = pd.Series(self.mpaa_cb.currentText()) rdate = pd.Series(self.date_cal.dateTime().toString("MM/dd/yyyy")) c_genres = [] for g in self.genre_tm.actions(): if g.isChecked(): c_genres.append(g.text()) genres = pd.Series(", ".join(c_genres)) c_themes = [] for t in self.theme_tm.actions(): if t.isChecked(): c_themes.append(t.text()) themes = pd.Series(", ".join(c_themes)) s_title = s_title.append(title) s_dir = s_dir.append(director) s_genre = s_genre.append(genres) s_theme = s_theme.append(themes) s_rdate = s_rdate.append(rdate) s_mpaa = s_mpaa.append(mpaa) s_cast = s_cast.append(cast) s_rating = s_rating.append(rating) s_comment = s_comment.append(comment) df2 = pd.DataFrame({"Title": s_title, "Director": s_dir, "Genre(s)": s_genre, "Theme(s)": s_theme, "Release Date": s_rdate, "MPAA": s_mpaa, "Cast": s_cast, "Rating": s_rating, "Comments": s_comment}) df2.to_excel(path, index=False) print("Submitted...") self.title_line.clear() self.direct_line.clear() self.cast_line.clear() self.rating_line.clear() self.comment_line.clear() for g in self.genre_tm.actions(): if g.isChecked(): g.setChecked(False) for t in self.theme_tm.actions(): if t.isChecked(): t.setChecked(False)
class ResultsQueryForm(QFormLayout): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # First line: Start Date self.label1 = QLabel(self.tr("Start Date")) self.start_date_edit = QDateEdit(datetime.now()) self.start_date_edit.setDisplayFormat("dd/MM/yyyy") self.start_date_edit.setCalendarPopup(True) # Just making sure that the start date is always before the end date self.start_date_edit.dateTimeChanged.connect(self.checkDates_startdate) self.setWidget(0, self.LabelRole, self.label1) self.setWidget(0, self.FieldRole, self.start_date_edit) # Second line: End Date self.label2 = QLabel(self.tr("End Date")) self.end_date_edit = QDateEdit(datetime.now()) self.end_date_edit.setDisplayFormat("dd/MM/yyyy") self.end_date_edit.setCalendarPopup(True) # Just making sure that the end date is always after the start date self.end_date_edit.dateTimeChanged.connect(self.checkDates_enddate) self.setWidget(1, self.LabelRole, self.label2) self.setWidget(1, self.FieldRole, self.end_date_edit) # Third line: Account selection self.label3 = QLabel(self.tr("Account")) self.account_select = QComboBox() all_accounts = balances.get_all_account_names() self.account_select.addItem("All") self.account_select.addItems(all_accounts) self.setWidget(2, self.LabelRole, self.label3) self.setWidget(2, self.FieldRole, self.account_select) # Fourth Line: Strategy Selection self.label4 = QLabel(self.tr("Strategy")) self.strategy_select = QComboBox() all_strategies = strategies.get_all_strategy_names() self.strategy_select.addItem("All") self.strategy_select.addItems(all_strategies) self.setWidget(3, self.LabelRole, self.label4) self.setWidget(3, self.FieldRole, self.strategy_select) def checkDates_startdate(self): """ Making sure that the start date is not bigger than the end date """ if self.end_date_edit.dateTime() < self.start_date_edit.dateTime(): # set end date same as start date self.end_date_edit.setDate(self.start_date_edit.date()) def checkDates_enddate(self): """ Making sure that the start date is not bigger than the end date """ if self.start_date_edit.dateTime() > self.end_date_edit.dateTime(): # viceversa self.start_date_edit.setDate(self.end_date_edit.date())