class XonStatForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.keypath = os.path.expanduser('~/.xonotic/key_0.d0si') # Signals self.ui.btnImport.clicked.connect(self.file_import) self.ui.btnExport.clicked.connect(self.file_export) # Old style signals # QtCore.QObject.connect(self.ui.btnImport, QtCore.SIGNAL("clicked()"), self.file_import) # QtCore.QObject.connect(self.ui.btnExport, QtCore.SIGNAL("clicked()"), self.file_export) def file_import(self): sourcepath = self.ui.lineImport.text() with open(sourcepath, 'rb') as sourcefile: cache = sourcefile.read() with open(self.keypath, 'wb') as keyfile: keyfile.write(cache) def file_export(self): descpath = self.ui.lineExport.text() with open(self.keypath, 'rb') as keyfile: cache = keyfile.read() with open(descpath, 'wb') as descfile: descfile.write(cache)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("BMI Rechner") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.bmi_value.hide() self.ui.warning.hide() self.ui.button.clicked.connect(self.bmi_button_calculate) def bmi_button_calculate(self): self.ui.warning.hide() height = float(self.ui.height.value()) weight = int(self.ui.weight.value()) if height != 0 or weight != 0: bmi_calc = round(weight / (height**2), 2) self.ui.bmi_value.show() self.ui.bmi_value.setText(str(bmi_calc)) return else: self.ui.warning.setText( "Deine Größe oder dein Gewicht dürfen nicht 0 sein!") self.ui.warning.show() return
class Control(QtWidgets.QMainWindow): """Create the UI, based on PyQt5. The UI elements are defined in "mainwindow.py" and resource file "resources_rc.py", created in QT Designer. To update "mainwindow.py": Run "pyuic5.exe --from-imports mainwindow.ui -o mainwindow.py" To update "resources_rc.py": Run "pyrcc5.exe resources.qrc -o resource_rc.py" Note: Never modify "mainwindow.py" or "resource_rc.py" manually. """ def __init__(self): super().__init__() # Create the main window self.ui = Ui_MainWindow() # Set upp the UI self.ui.setupUi(self) # self.show() # Get a list of available serial ports (e.g. "COM1" in Windows) self.serial_ports = connection.get_serial_ports() self.ui.comboBox.addItems(self.serial_ports) self.setup_ui_logic() # Populate the "COM port" combo box with available serial ports #self.ui.comboBoxComPorts.addItems(self.serial_ports) def setup_ui_logic(self): """Define QT signal and slot connections and initializes UI values.""" # Connect "Restart Communication" button self.ui.quitbutton.clicked.connect(QApplication.instance().quit)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Studierendenverwaltung") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.result.hide() self.ui.result_label.hide() # bmi = [Körpergewicht in kg] / [Körpergröße in m] ^ 2 self.ui.calculate.clicked.connect(self.calculate_bmi) def calculate_bmi(self): height = self.ui.height.value() weight = self.ui.weigth.value() if height != 0: self.ui.result.show() self.ui.result_label.show() bmi = round(weight / (height**2), 2) self.ui.result.setText(str(bmi)) else: self.ui.result.setText("")
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Studierendenverwaltung") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.search) def search(self): r = sr.Recognizer() with sr.Microphone() as source: #text = "what you want to search?" #var = gTTS(text=text, lang="en-AU", slow=False) #var.save("search.mp3") #playsound(".\s.wav") audio = r.listen(source) play = r.recognize_google(audio, language='ar') pywhatkit.playonyt(play) text = "completed" var = gTTS(text=text, lang="en") var.save("search1.mp3") playsound(".\search1.mp3") #os.remove("search.mp3") os.remove("search1.mp3")
class MainWindow(QMainWindow): def __init__(self): # Load window super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.load_tab(0) # TabView slot self.ui.tabWidget.currentChanged.connect(self.load_tab) # Menu slots self.ui.actionExit.triggered.connect(sys.exit) self.ui.actionOptions.triggered.connect(self.optionsTriggered) def load_tab(self, index): module_name = self.ui.tabWidget.tabText(index) if module_name == 'Themes': if not hasattr(self, 'themesTab'): self.themesTab = themes.ThemesWindow(self.ui) self.themesTab.load_window() elif module_name == 'Presets': if not hasattr(self, 'presetsTab'): self.presetsTab = presets.PresetsWindow(self.ui) self.presetsTab.load_window() def optionsTriggered(self): from configuration import ConfigurationWindow self.configWindow = ConfigurationWindow() self.configWindow.show()
class MainWindow(QMainWindow): def __init__(self): # Load window super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.load_tab(0) # TabView slot self.ui.tabWidget.currentChanged.connect(self.load_tab) # Menu slots self.ui.actionExit.triggered.connect(sys.exit) self.ui.actionOptions.triggered.connect(self.optionsTriggered) def load_tab(self, index): module_name = self.ui.tabWidget.tabText(index) if module_name == "Themes": if not hasattr(self, "themesTab"): self.themesTab = themes.ThemesWindow(self.ui) self.themesTab.load_window() elif module_name == "Presets": if not hasattr(self, "presetsTab"): self.presetsTab = presets.PresetsWindow(self.ui) self.presetsTab.load_window() def optionsTriggered(self): from configuration import ConfigurationWindow self.configWindow = ConfigurationWindow() self.configWindow.show()
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.mainwindow = Ui_MainWindow() self.mainwindow.setupUi(self) it1 = Category(title='it1') it2 = Page('it2', 'This is it2\'s content') it3 = Page('it3', 'This is it3\'s content') it1.setChild(it1.rowCount(), it2) it1.setChild(it1.rowCount(), it3) model = QStandardItemModel() model.appendRow(it1) tv = self.mainwindow.treeView tv.setModel(model) tv.setRootIsDecorated(True) tv.setSelectionMode(QAbstractItemView.SingleSelection) tv.setSelectionBehavior(QAbstractItemView.SelectItems) tv.clicked.connect(self.printData) def printData(self): it = self.mainwindow.treeView.model().itemFromIndex(self.mainwindow.treeView.currentIndex()) print('Item: {0}'.format(type(it))) self.mainwindow.textEdit.setText(it.content)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("My window name") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.read.clicked.connect(self.onButtonClick) def onButtonClick(self): database = DatabaseConnector( ) # sqlite3.connect('E:\\Programming\\betaDB.db') database.getNewValues() temperature = round(database.latestTemperature, 1) temperature = str(temperature) + "°C" pressure = round(database.latestPressure, 0) pressure = str(pressure) + "hPa" humidity = round(database.latestHumidity, 1) humidity = str(humidity) + "%" self.ui.temperature_text.setText(temperature) self.ui.humidity_text.setText(humidity) self.ui.pressure_text.setText(pressure)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.setWindowTitle("GUI-Base") self.ui = Ui_MainWindow() self.ui.setupUi(self)
class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ctx = gpgme.Context() self.keylistModel = GPGKeyListModel(self.ctx, self.ui.treeViewKeyList) self.ui.treeViewKeyList.setModel(self.keylistModel)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Studierendenverwaltung") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.readCsvFile("./Python/Python Bootcamp/QT/CSV_Import/students.csv") self.ui.newEntryButton.clicked.connect(self.onNewEntry) self.ui.saveButton.clicked.connect(self.onSave) self.ui.actionSave.triggered.connect(self.onSave) def onSave(self): with open('./Python/Python Bootcamp/QT/CSV_Import/students.csv', 'w', newline='', encoding="utf-8") as file: writer = csv.writer(file, delimiter=",", quotechar='"') rows = self.ui.studentsTable.rowCount() for i in range(0, rows): rowContent = [ self.ui.studentsTable.item(i, 0).text(), self.ui.studentsTable.item(i, 1).text(), self.ui.studentsTable.item(i, 2).text() ] writer.writerow(rowContent) def onNewEntry(self): row = self.ui.studentsTable.rowCount() self.ui.studentsTable.insertRow(row) self.ui.studentsTable.setItem(row, 0, QtWidgets.QTableWidgetItem("")) self.ui.studentsTable.setItem(row, 1, QtWidgets.QTableWidgetItem("")) self.ui.studentsTable.setItem(row, 2, QtWidgets.QTableWidgetItem("")) cell = self.ui.studentsTable.item(row, 0) self.ui.studentsTable.editItem(cell) def readCsvFile(self, filename): self.ui.studentsTable.setRowCount(0) with open(filename, "r", newline='', encoding="utf-8") as file: reader = csv.reader(file, delimiter=',', quotechar='"') for line in reader: row = self.ui.studentsTable.rowCount() self.ui.studentsTable.insertRow(row) self.ui.studentsTable.setItem( row, 0, QtWidgets.QTableWidgetItem(line[0])) self.ui.studentsTable.setItem( row, 1, QtWidgets.QTableWidgetItem(line[1])) self.ui.studentsTable.setItem( row, 2, QtWidgets.QTableWidgetItem(line[2]))
class MainWindow(QtWidgets.QMainWindow): def __init__(self,parent = None): super().__init__(parent) self.setWindowTitle("Studentenverwaltung") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.readCsvFile("students.csv") self.ui.newEntryButton.clicked.connect(self.onNewEntry) self.ui.saveButton.clicked.connect(self.onSave) self.ui.actionSpeichern.triggered.connect(self.onSave) def onSave(self): with open ("students.csv","w",newline = '', encoding="utf-8") as file: writer = csv.writer(file,delimiter = ",", quotechar = '"') rows = self.ui.studentsTable.rowCount () for i in range(0,rows): rowContent = [ self.ui.studentsTable.item(i,0).text(), self.ui.studentsTable.item(i,1).text(), self.ui.studentsTable.item(i,2).text(), ] writer.writerow(rowContent) def onNewEntry(self): row = self.ui.studentsTable.rowCount() self.ui.studentsTable.insertRow(row) self.ui.studentsTable.setItem (row, 0, QtWidgets.QTableWidgetItem ("")) self.ui.studentsTable.setItem (row, 1, QtWidgets.QTableWidgetItem ("")) self.ui.studentsTable.setItem (row, 2, QtWidgets.QTableWidgetItem ("")) #den cursor direkt in die Zelle legen, # so kann direkt nach dem drücken des button geschrieben werden cell = self.ui.studentsTable.item(row,0) self.ui.studentsTable.editItem(cell) print(cell) def readCsvFile(self,filename): self.ui.studentsTable.setRowCount(0) with open(filename,"r",newline='',encoding="utf-8") as file: reader = csv.reader(file, delimiter=',', quotechar = '"') for line in reader: row = self.ui.studentsTable.rowCount() self.ui.studentsTable.insertRow(row) self.ui.studentsTable.setItem(row, 0, QtWidgets.QTableWidgetItem(line[0])) self.ui.studentsTable.setItem(row, 1, QtWidgets.QTableWidgetItem(line[1])) self.ui.studentsTable.setItem(row, 2, QtWidgets.QTableWidgetItem(line[2])) print(line)
class MainWIndow(QtWidgets.QMainWindow, QLCDNumber, QDialog): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.status.text() self.setWindowTitle("TEZOS password finder") self.ui.StartButton.clicked.connect(self.start_Button_click) def start_Button_click(self): self.thread = CalcThread() self.thread.start()
class Window(QtWidgets.QMainWindow): def __init__(self): super(Window, self).__init__() self.ui = Ui_MainWindow() self.aboutui = AboutWindow() self.ui.setupUi(self) self.initUI() self.ui.scene = GraphicsScene() self.ui.graphicsView.setScene(self.ui.scene) print(dir(self.ui.scene)) # self.ui.graphicsView = QtWidgets.QGraphicsView(self.ui.scene) # self.ui.graphicsView.setGeometry(QtCore.QRect(20, 10, 571, 400)) # self.ui.graphicsView.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.CrossCursor)) # self.ui.graphicsView.setMouseTracking(True) # self.ui.graphicsView.setObjectName("graphicsView") def initUI(self): self.ui.graphicsView.viewport().installEventFilter(self) # About tab self.ui.actionAbout.triggered.connect(lambda: self.aboutui.show()) self.show() self.pen = QtCore.Qt.black self.img = ImageQt.ImageQt(Image.open('ui/images/sharex.png')) def redraw(self, event): return self.ui.scene.clear() # Draw Rect import random r = QtCore.QRectF(QtCore.QPointF(event.x(), event.y()), QtCore.QSizeF(10, 10)) self.ui.scene.addRect(r, self.pen) pixMap = QtGui.QPixmap.fromImage(self.img) self.ui.scene.addPixmap(pixMap) def eventFilter(self, source, e): if e.type() == QtCore.QEvent.MouseMove: if e.buttons() == QtCore.Qt.NoButton: self.redraw(e) elif e.buttons() == QtCore.Qt.LeftButton: pass elif e.buttons() == QtCore.Qt.RightButton: pass elif e.type() == QtCore.QEvent.MouseButtonPress: if e.button() == QtCore.Qt.LeftButton: pass elif e.button() == QtCore.Qt.RightButton: pass return super(Window, self).eventFilter(source, e)
class Init_config(): def __init__(self, mainWindow=None): self.mainWindow = mainWindow self.ui = Ui_MainWindow() self.ui.setupUi(mainWindow) self.centralWidget = self.ui.centralWidget # List all label we have in the UI. self.label_lst = [ self.ui.label_1, self.ui.label_2, self.ui.label_3, self.ui.label_4, self.ui.label_5, self.ui.label_6 ] # To save the cap_label init name. # Create the self.ui.origin_label_names = [ "None", "cap45a1", "cap60a1", "cap90a1", "cap45a2", "cap60a2", "cap90a2" ] self.cap_label_name = [] # To save all available Camera name or path. self.cap_objects = [] cam_lst = basicTool().availableCamera() self.label_lst = basicTool().availableLabel(lst=self.label_lst, count=len(cam_lst)) for cam_name in cam_lst: cap = cv2.VideoCapture(cam_name) if cap.isOpened(): self.cap_objects.append(cap) else: print('%s Camera can not open.' % cam_name) # Append the cap_label object. for i in range(len(self.cap_objects)): self.cap_label_name.append( Camera(capture=self.cap_objects[i], label=self.label_lst[i])) def show(self): # Start all available Camera Thread to show in the UI. for cap_label in self.cap_label_name: cap_label.refresh() def quit(self): for cap_label in self.cap_label_name: cap_label.quit() cv2.destroyAllWindows() for cap in self.cap_objects: cap.release()
class StartWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() # Set up the user interface from Designer self.ui = Ui_MainWindow() self.ui.setupUi(self) # Connect up the buttons self.ui.btn_open.clicked.connect(self.status_msg) self.ui.btn_calc.clicked.connect(self.status_msg) def status_msg(self): sender = self.sender() self.ui.statusbar.showMessage(sender.text() + ' was pressed')
class MainWindow(QtWidgets.QMainWindow): def read_format(self): return self.ui.comboBox.currentText() def download(self): link = self.ui.lineEdit.text() f = self.read_format() logger.debug("beginning download..." + f) if (f == "mp3"): quick_mp3_download(link) elif (f == "mp4"): quick_mp4_download(link) # todo: will be led to a new class: a communicator with the console. (?) def get_information(self): information = self.sc.output_format_information( self.ui.lineEdit.text()) for item in information: self.ui.comboBox_2.addItem(item) #self.title = def on_url_change(self): # log print("url changed") url = self.ui.lineEdit.text() if (url_is_valid(url)): self.ui.downloadButton.setEnabled(True) else: self.ui.downloadButton.setDisabled(True) self.ui.lineEdit.setText( "Your link was not a valid YouTube link...") # this string will cause a graying of each element. yeah def __init__(self, parent=None): super().__init__(parent) update_ydl() logger.info("updater finished") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.dl = Downloader self.setWindowIcon(QIcon("icons/Ydl_V2.png")) self.ui.downloadButton.clicked.connect(self.download) self.ui.lineEdit.textChanged.connect(self.on_url_change) self.setWindowTitle("YouTube-Downloader Version Alpha 0.4.3")
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.treeModel = ASTTreeModel(self) self.ui.treeView.setModel(self.treeModel) @pyqtSlot() def on_actionParse_triggered(self): source = six.text_type(self.ui.plainTextEdit.toPlainText()) node = ast.parse(source) self.treeModel.setNode(node) self.ui.treeView.expandAll()
def setupUi(self, window): Ui_MainWindow.setupUi(self, window) header = QtGui.QHeaderView(QtCore.Qt.Horizontal) header.setResizeMode(QtGui.QHeaderView.Stretch) self.episodeTable.setHorizontalHeader(header) self.fetchFeedButton.clicked.connect(self._load_feed) self.downloadButton.clicked.connect(self._download) self.deleteButton.clicked.connect(self._delete_row) self.saveQueueButton.clicked.connect(self._save_queue) self.settings = SettingsDialog() self.settingsButton.clicked.connect(self.settings.show) QtGui.qApp.queuehandler.finishedLoading.connect(self._set_model) QtGui.qApp.queuehandler.load() QtGui.qApp.downloader.fileDownloaded.connect(self._downloaded) QtGui.qApp.downloader.notFound.connect(self._notfound)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent=parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.sale_Btn.clicked.connect(self.on_sale_btn_clicked) self.ui.show_stock_Btn.clicked.connect(self.show_stock_btn_clicked) self.ui.purchase_Btn.clicked.connect(self.on_purchase_btn_clicked) self.ui.return_Btn.clicked.connect(self.on_return_btn_clicked) self.ui.statistics_Btn.clicked.connect(self.on_statistics_btn_clicked) def on_sale_btn_clicked(self): self.setEnabled(False) sale_dialog = SaleDialog(self) sale_dialog.show() sale_dialog.exec_() self.setEnabled(True) def show_stock_btn_clicked(self): self.setEnabled(False) stock_dialog = StockDialog(self) stock_dialog.show() stock_dialog.exec_() self.setEnabled(True) def on_purchase_btn_clicked(self): self.setEnabled(False) purchase_dialog = PurchaseDialog(self) purchase_dialog.show() purchase_dialog.exec_() self.setEnabled(True) def on_return_btn_clicked(self): self.setEnabled(False) return_dialog = ReturnDialog(self) return_dialog.show() return_dialog.exec_() self.setEnabled(True) def on_statistics_btn_clicked(self): self.setEnabled(False) statistics_dialog = StatisticsDialog(self) statistics_dialog.show() statistics_dialog.exec_() self.setEnabled(True)
class MyApp(QtWidgets.QMainWindow): def __init__(self,parent=None): super(MyApp, self).__init__(parent) # Set up the user interface from Designer. self.ui = Ui_MainWindow() self.ui.setupUi(self) self.trackuser_obj = MyApp_trackuser() self.addcamera_obj = MyApp_AddCamera() self.viewcamera_obj= MyApp_ViewCamera() self.ui.viewuser.setVisible(False) self.ui.VisitorLog.setVisible(False) self.dbs=dbops() self.ui.trackuser.clicked.connect(self.show_trackuser) self.ui.addcamera.clicked.connect(self.show_addcamera) self.ui.viewcamera.clicked.connect(self.show_viewcamera) self.ui.attendence.clicked.connect(self.generatereport) #self.ui.adduser.setDisabled(True) #self.ui.viewuser.setDisabled(True) def generatereport(self): today = datetime.now().date() start = today - timedelta(days=today.weekday()) startday=start.day end = start + timedelta(days=6) endday=end.day now=datetime.now() month=now.month year=now.year self.dbs.generate_report(startday,endday,month,year) def show_trackuser(self): self.trackuser_obj.show() def show_addcamera(self): self.addcamera_obj.show() def show_viewcamera(self): self.viewcamera_obj.show()
class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # self.setWindowState(Qt.WindowMaximized) self.init_events() self.hub = DeviceHub() self.hub.seeked.connect(self.on_hub_seek) def init_events(self): self.ui.searchBtn.clicked.connect( self.on_searchBtn_clicked(self.ui.searchBtn)) def on_searchBtn_clicked(self, which): def on(e): which.setText('搜索中...') self.hub.seek() return on @Slot(list) def on_hub_seek(self, devices): self.ui.searchBtn.setText('搜索设备') QMessageBox.information(self, '搜索结果', '发现{}台设备'.format(len(self.hub.hold)), QMessageBox.Ok) if len(devices): self.show_result() @Slot() def show_result(self): self.panel = QFrame() self.panel.setWindowTitle('设备列表') self.panel_layout = QHBoxLayout(self.panel) for i in self.hub.hold: device = Device(serial=i.serial, hub=self.hub) self.panel_layout.addWidget(device) self.panel.show()
class MainWindow(DbConnector, QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("expense Manager - BETA") if self.serverIsOn() == True: if self.checkLogin() == True: self.fillTableWidget() else: self.msgLoginCritical() else: self.msgDbCritical() self.ui.btnExpense.clicked.connect(self.addExpense) self.ui.btnIncome.clicked.connect(self.addIncome) self.ui.btnUpdate.clicked.connect(self.fillTableWidget) self.ui.actionKategorie_bearbeiten.triggered.connect(self.confCategory) self.ui.actionDB_Konfiguration.triggered.connect(self.confDb) self.ui.actionBuchungs_bersicht.triggered.connect(self.overview) self.ui.tableWidget.cellDoubleClicked.connect(self.clickRow) def clickRow(self, row): id = str(self.ui.tableWidget.item(row, 0).text()) self.ChangeEntryWindow = ChangeEntryWindow(id) self.ChangeEntryWindow.show() def addExpense(self): self.expenseWindow = ExpenseWindow() self.expenseWindow.show() def addIncome(self): self.incomeWindow = IncomeWindow() self.incomeWindow.show() def overview(self): self.overviewWindow = OverviewWindow() self.overviewWindow.show() def confCategory(self): self.categoryWindow = CategoryWindow() self.categoryWindow.show() def confDb(self): self.dbConfWindow = DbConfiguration() self.dbConfWindow.show() def fillTableWidget(self): conn = DbConnector().connect() cur = conn.cursor() cur.execute("SELECT * FROM entries ORDER BY entry_id DESC LIMIT 40") result = cur.fetchall() self.ui.tableWidget.setRowCount(0) for rowNumber, rowData in enumerate(result): self.ui.tableWidget.insertRow(rowNumber) date = str(rowData[1].strftime("%d.%m.%Y")) self.ui.tableWidget.setItem(rowNumber, 0, QtWidgets.QTableWidgetItem(str(rowData[0]))) self.ui.tableWidget.setItem(rowNumber, 4, QtWidgets.QTableWidgetItem(str(rowData[6]))) self.ui.tableWidget.setItem(rowNumber, 1, QtWidgets.QTableWidgetItem(str(date))) self.ui.tableWidget.setItem(rowNumber, 2, QtWidgets.QTableWidgetItem(str(rowData[2]))) self.ui.tableWidget.setItem(rowNumber, 3, QtWidgets.QTableWidgetItem(str(rowData[3]))) self.ui.tableWidget.setItem(rowNumber, 5, QtWidgets.QTableWidgetItem(str(rowData[4]))) self.ui.tableWidget.setItem(rowNumber, 6, QtWidgets.QTableWidgetItem(str(rowData[5]))) self.ui.tableWidget.setColumnHidden(0, True) y, m, d = str(datetime.now().date()).split("-") cur.execute("SELECT SUM(amount) FROM entries WHERE typ = 'Ausgabe' AND date_part('month', date::date) = '{0}' AND date_part('year', date::date) = '{1}'".format(m, y)) resultExpense = cur.fetchall() expense = resultExpense[0][0] if expense == None: expense = 0 self.ui.totalExpense.setText(str(expense)) cur.execute("SELECT SUM(amount) FROM entries WHERE typ = 'Einnahme' AND date_part('month', date::date) = '{0}' AND date_part('year', date::date) = '{1}'".format(m, y)) resultReceipt = cur.fetchall() receipt = resultReceipt[0][0] if receipt == None: receipt = 0 self.ui.totalReceipt.setText(str(receipt)) diff = receipt - expense self.ui.totalDiff.setText(str(diff))
class SoftwareCenter(QMainWindow): # fx(software, category) map scmap = {} # fx(page, softwares) map psmap = {} # recommend number in fill func recommendNumber = 0 # now page nowPage = '' # search delay timer searchDTimer = '' def __init__(self,parent=None): QMainWindow.__init__(self,parent) # ui self.ui_init() # logic self.tmp_get_category() self.tmp_get_category_software() # from backend.ibackend import get_backend # self.bk = get_backend() # sl = self.bk.get_all_packages() # # self.check_software() self.psmap[self.ui.allsListWidget] = [] self.psmap[self.ui.upListWidget] = [] self.psmap[self.ui.unListWidget] = [] # test self.ui.leSearch.setPlaceholderText("请输入想要搜索的软件") self.ui.allsMSGBar.setText("已安装软件 ") self.ui.bottomText1.setText("UK软件中心:") self.ui.bottomText2.setText("1.0.12") # self.tmp_fill_recommend_softwares() # self.tmp_get_ads() self.ui.categoryView.setEnabled(False) self.ui.btnUp.setEnabled(False) self.ui.btnUn.setEnabled(False) self.ui.btnTask.setEnabled(False) self.slot_goto_homepage() # from backend.ibackend import get_backend # self.bk = get_backend() self.connect(data.backend, SIGNAL("getallpackagesover"), self.slot_get_all_packages_over) at = AsyncThread(data.backend.get_all_packages) at.setDaemon(True) at.start() # from multiprocessing import Process,Queue # q = Queue() # q.put(data.softwareList) # p = Process(target=self.check_software,args=(q,)) # p.start() # data.softwareList = q.get() # print len(data.softwareList) # p.join() # self.connect(data.sbo, SIGNAL("countiover"), self.slot_count_installed_over) # at = AsyncThread(data.sbo.count_installed_software) # at.setDaemon(True) # at.start() # # self.connect(data.sbo, SIGNAL("countuover"), self.slot_count_upgradable_over) # at = AsyncThread(data.sbo.count_upgradable_software) # at.setDaemon(True) # at.start() self.btntesttask = QPushButton(self.ui.taskWidget) self.btntesttask.setGeometry(400,20,100,30) self.raise_() self.btntesttask.clicked.connect(self.slot_testtask) def slot_testtask(self): software = data.sbo.get_software_by_name("firefox") oneitem = QListWidgetItem() tliw = TaskListItemWidget(software) self.ui.taskListWidget.addItem(oneitem) self.ui.taskListWidget.setItemWidget(oneitem, tliw) import time for i in range(100): tliw.ui.progressBar.setValue(i+1) time.sleep(0.02) def ui_init(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("Ubuntu Kylin Software-Center") self.setWindowFlags(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground, True) self.ui.headerWidget.installEventFilter(self) self.ui.categoryView.itemClicked.connect(self.slot_change_category) self.ui.allsListWidget.verticalScrollBar().valueChanged.connect(self.slot_softwidget_scroll_end) self.ui.upListWidget.verticalScrollBar().valueChanged.connect(self.slot_softwidget_scroll_end) self.ui.unListWidget.verticalScrollBar().valueChanged.connect(self.slot_softwidget_scroll_end) self.ui.btnHomepage.pressed.connect(self.slot_goto_homepage) self.ui.btnUp.pressed.connect(self.slot_goto_uppage) self.ui.btnUn.pressed.connect(self.slot_goto_unpage) self.ui.btnTask.pressed.connect(self.slot_goto_taskpage) self.ui.btnClose.clicked.connect(self.slot_close) self.ui.btnMin.clicked.connect(self.slot_min) self.connect(data.backend, SIGNAL("backendmsg"), self.slot_backend_msg) # style by code self.ui.headerWidget.setAutoFillBackground(True) palette = QPalette() img = QPixmap("res/header.png") palette.setBrush(QPalette.Window, QBrush(img)) self.ui.headerWidget.setPalette(palette) self.ui.bottomWidget.setAutoFillBackground(True) palette = QPalette() img = QPixmap("res/foot.png") palette.setBrush(QPalette.Window, QBrush(img)) self.ui.bottomWidget.setPalette(palette) self.ui.categoryView.setFocusPolicy(Qt.NoFocus) self.ui.btnDay.setFocusPolicy(Qt.NoFocus) self.ui.btnWeek.setFocusPolicy(Qt.NoFocus) self.ui.btnMonth.setFocusPolicy(Qt.NoFocus) self.ui.btnDownTimes.setFocusPolicy(Qt.NoFocus) self.ui.btnGrade.setFocusPolicy(Qt.NoFocus) self.ui.btnClose.setFocusPolicy(Qt.NoFocus) self.ui.btnMin.setFocusPolicy(Qt.NoFocus) self.ui.btnSkin.setFocusPolicy(Qt.NoFocus) self.ui.btnConf.setFocusPolicy(Qt.NoFocus) self.ui.btnBack.setFocusPolicy(Qt.NoFocus) self.ui.btnNext.setFocusPolicy(Qt.NoFocus) self.ui.btnHomepage.setFocusPolicy(Qt.NoFocus) self.ui.btnUp.setFocusPolicy(Qt.NoFocus) self.ui.btnUn.setFocusPolicy(Qt.NoFocus) self.ui.btnTask.setFocusPolicy(Qt.NoFocus) self.ui.allsListWidget.setFocusPolicy(Qt.NoFocus) self.ui.upListWidget.setFocusPolicy(Qt.NoFocus) self.ui.unListWidget.setFocusPolicy(Qt.NoFocus) self.ui.taskListWidget.setFocusPolicy(Qt.NoFocus) self.ui.allsWidget.hide() self.ui.upWidget.hide() self.ui.unWidget.hide() self.ui.taskWidget.hide() self.show() # style by qss self.ui.btnBack.setStyleSheet("QPushButton{background-image:url('res/nav-back-1.png');border:0px;}QPushButton:hover{background:url('res/nav-back-2.png');}QPushButton:pressed{background:url('res/nav-back-3.png');}") self.ui.btnNext.setStyleSheet("QPushButton{background-image:url('res/nav-next-1.png');border:0px;}QPushButton:hover{background:url('res/nav-next-2.png');}QPushButton:pressed{background:url('res/nav-next-3.png');}") self.ui.btnHomepage.setStyleSheet("QPushButton{background-image:url('res/nav-homepage-1.png');border:0px;}QPushButton:hover{background:url('res/nav-homepage-2.png');}QPushButton:pressed{background:url('res/nav-homepage-3.png');}") self.ui.btnUp.setStyleSheet("QPushButton{background-image:url('res/nav-up-1.png');border:0px;}QPushButton:hover{background:url('res/nav-up-2.png');}QPushButton:pressed{background:url('res/nav-up-3.png');}") self.ui.btnUn.setStyleSheet("QPushButton{background-image:url('res/nav-un-1.png');border:0px;}QPushButton:hover{background:url('res/nav-un-2.png');}QPushButton:pressed{background:url('res/nav-un-3.png');}") self.ui.btnTask.setStyleSheet("QPushButton{background-image:url('res/nav-task-1.png');border:0px;}QPushButton:hover{background:url('res/nav-task-2.png');}QPushButton:pressed{background:url('res/nav-task-3.png');}") self.ui.logoImg.setStyleSheet("QLabel{background-image:url('res/logo.png')}") self.ui.searchicon.setStyleSheet("QLabel{background-image:url('res/search.png')}") self.ui.leSearch.setStyleSheet("QLineEdit{border:1px solid #C3E0F4;border-radius:2px;padding-left:15px;color:#497FAB;font-size:13px;}") self.ui.userWidget.setStyleSheet("QWidget{background-color:#DDE4EA}") self.ui.userLabel.setStyleSheet("QLabel{background-image:url('res/item3')}") self.ui.item1Widget.setStyleSheet("QWidget{background-image:url('res/item1.png')}") self.ui.item2Widget.setStyleSheet("QWidget{background-image:url('res/item2.png')}") self.ui.btnClose.setStyleSheet("QPushButton{background-image:url('res/close-1.png');border:0px;}QPushButton:hover{background:url('res/close-2.png');}QPushButton:pressed{background:url('res/close-3.png');}") self.ui.btnMin.setStyleSheet("QPushButton{background-image:url('res/min-1.png');border:0px;}QPushButton:hover{background:url('res/min-2.png');}QPushButton:pressed{background:url('res/min-3.png');}") self.ui.btnSkin.setStyleSheet("QPushButton{background-image:url('res/skin-1.png');border:0px;}QPushButton:hover{background:url('res/skin-2.png');}QPushButton:pressed{background:url('res/skin-3.png');}") self.ui.btnConf.setStyleSheet("QPushButton{background-image:url('res/conf-1.png');border:0px;}QPushButton:hover{background:url('res/conf-2.png');}QPushButton:pressed{background:url('res/conf-3.png');}") self.ui.categoryView.setStyleSheet("QListWidget{border:0px;background-image:url('res/categorybg.png');}QListWidget::item{height:35px;padding-left:20px;margin-top:0px;border:0px;}QListWidget::item:hover{background:#CAD4E2;}QListWidget::item:selected{background-color:#6BB8DD;color:black;}") self.ui.categorytext.setStyleSheet("QLabel{background-image:url('res/categorybg.png');color:#7E8B97;font-weight:bold;padding-left:5px;}") self.ui.hline1.setStyleSheet("QLabel{background-image:url('res/hline1.png')}") self.ui.recommendWidget.setStyleSheet("QWidget{background-color:white}") self.ui.vline1.setStyleSheet("QLabel{background-color:#BBD1E4;}") self.ui.rankWidget.setStyleSheet("QWidget{background-color:white}") self.ui.rankLogo.setStyleSheet("QLabel{background-image:url('res/rankLogo.png')}") self.ui.rankText.setStyleSheet("QLabel{color:#7E8B97;font-size:13px;font-weight:bold;}") self.ui.btnDay.setStyleSheet("QPushButton{background-image:url('res/day1.png');border:0px;}") self.ui.btnWeek.setStyleSheet("QPushButton{background-image:url('res/week1.png');border:0px;}") self.ui.btnMonth.setStyleSheet("QPushButton{background-image:url('res/month1.png');border:0px;}") self.ui.btnDownTimes.setStyleSheet("QPushButton{font-size:14px;color:#2B8AC2;background-color:#C3E0F4;border:0px;}") self.ui.btnGrade.setStyleSheet("QPushButton{font-size:14px;color:#2B8AC2;background-color:#C3E0F4;border:0px;}") self.ui.rankView.setStyleSheet("QListWidget{border:0px;}") self.ui.bottomImg.setStyleSheet("QLabel{background-image:url('res/logo.png')}") self.ui.bottomText1.setStyleSheet("QLabel{color:white;font-size:14px;}") self.ui.bottomText2.setStyleSheet("QLabel{color:white;font-size:14px;}") self.ui.allsMSGBar.setStyleSheet("QLabel{background-color:white;font-size:14px;padding-top:25px;padding-left:10px;}") self.ui.upMSGBar.setStyleSheet("QLabel{background-color:white;font-size:14px;padding-top:25px;padding-left:10px;}") self.ui.unMSGBar.setStyleSheet("QLabel{background-color:white;font-size:14px;padding-top:25px;padding-left:10px;}") self.ui.taskMSGBar.setStyleSheet("QLabel{background-color:white;font-size:14px;padding-top:25px;padding-left:10px;}") self.ui.allsHeader.setStyleSheet("QLabel{background-image:url('res/listwidgetheader.png')}") self.ui.upHeader.setStyleSheet("QLabel{background-image:url('res/listwidgetheader.png')}") self.ui.unHeader.setStyleSheet("QLabel{background-image:url('res/listwidgetheader.png')}") self.ui.taskHeader.setStyleSheet("QLabel{background-image:url('res/taskwidgetheader.png')}") self.ui.allsListWidget.setStyleSheet("QListWidget{border:0px;}QListWidget::item{height:66px;margin-top:-1px;border:1px solid #d5e3ec;}QListWidget::item:hover{background-color:#E4F1F8;}") self.ui.upListWidget.setStyleSheet("QListWidget{border:0px;}QListWidget::item{height:66px;margin-top:-1px;border:1px solid #d5e3ec;}QListWidget::item:hover{background-color:#E4F1F8;}") self.ui.unListWidget.setStyleSheet("QListWidget{border:0px;}QListWidget::item{height:66px;margin-top:-1px;border:1px solid #d5e3ec;}QListWidget::item:hover{background-color:#E4F1F8;}") self.ui.taskListWidget.setStyleSheet("QListWidget{border:0px;}QListWidget::item{height:45;margin-top:-1px;border:1px solid #d5e3ec;}QListWidget::item:hover{background-color:#E4F1F8;}") def eventFilter(self, obj, event): if (obj == self.ui.headerWidget): if (event.type() == QEvent.MouseButtonPress): self.isMove = True # True only when click the blank place on header bar self.nowMX = event.globalX() self.nowMY = event.globalY() self.nowWX = self.x() self.nowWY = self.y() elif (event.type() == QEvent.MouseMove): if(self.isMove): incx = event.globalX() - self.nowMX incy = event.globalY() - self.nowMY self.move(self.nowWX + incx, self.nowWY + incy) elif (event.type() == QEvent.MouseButtonRelease): self.isMove = False return True def tmp_get_category(self): for c in os.listdir("res/category"): if(c == 'ubuntukylin'): oneitem = QListWidgetItem('Ubuntu Kylin') icon = QIcon() icon.addFile("res/" + c + ".png", QSize(), QIcon.Normal, QIcon.Off) oneitem.setIcon(icon) oneitem.setWhatsThis(c) self.ui.categoryView.addItem(oneitem) for c in os.listdir("res/category"): zhcnc = '' if(c == 'devel'): zhcnc = '编程开发' if(c == 'game'): zhcnc = '游戏娱乐' if(c == 'ubuntukylin'): continue # zhcnc = 'Ubuntu Kylin' if(c == 'office'): zhcnc = '办公软件' if(c == 'internet'): zhcnc = '网络工具' if(c == 'multimedia'): zhcnc = '影音播放' if(c == 'graphic'): zhcnc = '图形图像' if(c == 'profession'): zhcnc = '专业软件' if(c == 'other'): zhcnc = '其他软件' if(c == 'necessary'): zhcnc = '装机必备' oneitem = QListWidgetItem(zhcnc) icon = QIcon() icon.addFile("res/" + c + ".png", QSize(), QIcon.Normal, QIcon.Off) oneitem.setIcon(icon) oneitem.setWhatsThis(c) self.ui.categoryView.addItem(oneitem) def tmp_get_category_software(self): for c in os.listdir("res/category"): file = open(os.path.abspath("res/category/" + c), 'r') for line in file: self.scmap[line[:-1]] = c def tmp_get_ads(self): tmpads = [] tmpads.append(Advertisement("qq", "url", "ad1.png", "http://www.baidu.com")) tmpads.append(Advertisement("wps", "pkg", "ad2.png", "wps")) tmpads.append(Advertisement("qt", "pkg", "ad3.png", "qtcreator")) adw = ADWidget(tmpads, self) def tmp_fill_recommend_softwares(self): rnames = ['flashplugin-installer','vlc','openfetion','virtualbox'] for name in rnames: self.add_one_recommend_software(name) def add_one_recommend_software(self, name): for software in data.softwareList: if(software.name == name): x = 0 y = 0 recommend = RecommendItem(software,self.ui.recommendWidget) if(self.recommendNumber in (0, 1, 2)): y = 0 elif(self.recommendNumber in (3, 4, 5)): y = 88 else: y = 176 if(self.recommendNumber in (0, 3, 6)): x = 0 elif(self.recommendNumber in (1, 4, 7)): x = 176 else: x = 352 recommend.move(x, y) self.recommendNumber += 1 # delete packages from apt backend which not in category file def check_software(self, sl): slist = [] for c in os.listdir("res/category"): file = open(os.path.abspath("res/category/"+c), 'r') for line in file: slist.append(line[:-1]) i = 0 while i < len(sl): name = sl[i].name for name_ in slist: if name == name_: sl[i].category = self.scmap[name] break else: sl.pop(i) i -= 1 i += 1 self.emit(SIGNAL("chksoftwareover"), sl) def _check_software(self): slist = [] for c in os.listdir("res/category"): file = open(os.path.abspath("res/category/"+c), 'r') for line in file: slist.append(line[:-1]) data.sbo.get_all_software() i = 0 while i < len(data.softwareList): name = data.softwareList[i].name for name_ in slist: if name == name_: data.softwareList[i].category = self.scmap[name] break else: data.softwareList.pop(i) i -= 1 i += 1 self.emit(SIGNAL("chksoftwareover")) def show_more_software(self, listWidget): theRange = 0 if(len(self.psmap[listWidget]) < data.showSoftwareStep): theRange = len(self.psmap[listWidget]) else: theRange = data.showSoftwareStep for i in range(theRange): software = self.psmap[listWidget].pop(0) oneitem = QListWidgetItem() liw = ListItemWidget(software, self.nowPage) listWidget.addItem(oneitem) listWidget.setItemWidget(oneitem, liw) def switch_category(self): listWidget = self.get_current_listWidget() nowCategory = listWidget.whatsThis() if(self.nowPage == 'homepage'): self.ui.categoryView.clearSelection() else: if(nowCategory == ''): self.ui.categoryView.clearSelection() else: for i in range(self.ui.categoryView.count()): item = self.ui.categoryView.item(i) if(item.whatsThis() == nowCategory): item.setSelected(True) def get_current_listWidget(self): listWidget = '' if(self.nowPage == "homepage"): listWidget = self.ui.allsListWidget elif(self.nowPage == "uppage"): listWidget = self.ui.upListWidget elif(self.nowPage == "unpage"): listWidget = self.ui.unListWidget return listWidget #-------------------------------slots------------------------------- def slot_change_category(self, citem): listWidget = self.get_current_listWidget() category = str(citem.whatsThis()) trueCategory = listWidget.whatsThis() if(trueCategory == category): pass else: listWidget.scrollToTop() # if not, the func will trigger slot_softwidget_scroll_end() listWidget.setWhatsThis(category) # use whatsThis() to save each selected category listWidget.clear() self.psmap[listWidget] = [] for software in data.softwareList: if(software.category == category): if(self.nowPage == 'homepage'): self.psmap[listWidget].append(software) elif(self.nowPage == 'uppage'): if(software.is_upgradable): self.psmap[listWidget].append(software) elif(self.nowPage == 'unpage'): if(software.is_installed): self.psmap[listWidget].append(software) self.show_more_software(listWidget) # homepage is special if(self.nowPage == "homepage" and self.ui.allsWidget.isVisible() == False): self.ui.allsWidget.setVisible(True) def slot_softwidget_scroll_end(self, now): listWidget = self.get_current_listWidget() max = listWidget.verticalScrollBar().maximum() if(now == max): self.show_more_software(listWidget) def slot_goto_homepage(self): self.nowPage = 'homepage' self.ui.categoryView.setEnabled(True) self.switch_category() self.ui.homepageWidget.setVisible(True) self.ui.allsWidget.setVisible(False) self.ui.upWidget.setVisible(False) self.ui.unWidget.setVisible(False) self.ui.taskWidget.setVisible(False) self.ui.btnHomepage.setEnabled(False) self.ui.btnUp.setEnabled(True) self.ui.btnUn.setEnabled(True) self.ui.btnTask.setEnabled(True) self.ui.btnHomepage.setStyleSheet("QPushButton{background-image:url('res/nav-homepage-3.png');border:0px;}") self.ui.btnUp.setStyleSheet("QPushButton{background-image:url('res/nav-up-1.png');border:0px;}QPushButton:hover{background:url('res/nav-up-2.png');}QPushButton:pressed{background:url('res/nav-up-3.png');}") self.ui.btnUn.setStyleSheet("QPushButton{background-image:url('res/nav-un-1.png');border:0px;}QPushButton:hover{background:url('res/nav-un-2.png');}QPushButton:pressed{background:url('res/nav-un-3.png');}") self.ui.btnTask.setStyleSheet("QPushButton{background-image:url('res/nav-task-1.png');border:0px;}QPushButton:hover{background:url('res/nav-task-2.png');}QPushButton:pressed{background:url('res/nav-task-3.png');}") def slot_goto_uppage(self): self.nowPage = 'uppage' self.ui.categoryView.setEnabled(True) self.switch_category() self.ui.homepageWidget.setVisible(False) self.ui.allsWidget.setVisible(False) self.ui.upWidget.setVisible(True) self.ui.unWidget.setVisible(False) self.ui.taskWidget.setVisible(False) self.ui.btnHomepage.setEnabled(True) self.ui.btnUp.setEnabled(False) self.ui.btnUn.setEnabled(True) self.ui.btnTask.setEnabled(True) self.ui.btnHomepage.setStyleSheet("QPushButton{background-image:url('res/nav-homepage-1.png');border:0px;}QPushButton:hover{background:url('res/nav-homepage-2.png');}QPushButton:pressed{background:url('res/nav-homepage-3.png');}") self.ui.btnUp.setStyleSheet("QPushButton{background-image:url('res/nav-up-3.png');border:0px;}") self.ui.btnUn.setStyleSheet("QPushButton{background-image:url('res/nav-un-1.png');border:0px;}QPushButton:hover{background:url('res/nav-un-2.png');}QPushButton:pressed{background:url('res/nav-un-3.png');}") self.ui.btnTask.setStyleSheet("QPushButton{background-image:url('res/nav-task-1.png');border:0px;}QPushButton:hover{background:url('res/nav-task-2.png');}QPushButton:pressed{background:url('res/nav-task-3.png');}") def slot_goto_unpage(self): self.nowPage = 'unpage' self.ui.categoryView.setEnabled(True) self.switch_category() self.ui.homepageWidget.setVisible(False) self.ui.allsWidget.setVisible(False) self.ui.upWidget.setVisible(False) self.ui.unWidget.setVisible(True) self.ui.taskWidget.setVisible(False) self.ui.btnHomepage.setEnabled(True) self.ui.btnUp.setEnabled(True) self.ui.btnUn.setEnabled(False) self.ui.btnTask.setEnabled(True) self.ui.btnHomepage.setStyleSheet("QPushButton{background-image:url('res/nav-homepage-1.png');border:0px;}QPushButton:hover{background:url('res/nav-homepage-2.png');}QPushButton:pressed{background:url('res/nav-homepage-3.png');}") self.ui.btnUp.setStyleSheet("QPushButton{background-image:url('res/nav-up-1.png');border:0px;}QPushButton:hover{background:url('res/nav-up-2.png');}QPushButton:pressed{background:url('res/nav-up-3.png');}") self.ui.btnUn.setStyleSheet("QPushButton{background-image:url('res/nav-un-3.png');border:0px;}") self.ui.btnTask.setStyleSheet("QPushButton{background-image:url('res/nav-task-1.png');border:0px;}QPushButton:hover{background:url('res/nav-task-2.png');}QPushButton:pressed{background:url('res/nav-task-3.png');}") def slot_goto_taskpage(self): self.nowPage = 'taskpage' self.ui.categoryView.setEnabled(False) self.ui.categoryView.clearSelection() self.ui.homepageWidget.setVisible(False) self.ui.allsWidget.setVisible(False) self.ui.upWidget.setVisible(False) self.ui.unWidget.setVisible(False) self.ui.taskWidget.setVisible(True) self.ui.btnHomepage.setEnabled(True) self.ui.btnUp.setEnabled(True) self.ui.btnUn.setEnabled(True) self.ui.btnTask.setEnabled(False) self.ui.btnHomepage.setStyleSheet("QPushButton{background-image:url('res/nav-homepage-1.png');border:0px;}QPushButton:hover{background:url('res/nav-homepage-2.png');}QPushButton:pressed{background:url('res/nav-homepage-3.png');}") self.ui.btnUp.setStyleSheet("QPushButton{background-image:url('res/nav-up-1.png');border:0px;}QPushButton:hover{background:url('res/nav-up-2.png');}QPushButton:pressed{background:url('res/nav-up-3.png');}") self.ui.btnUn.setStyleSheet("QPushButton{background-image:url('res/nav-un-1.png');border:0px;}QPushButton:hover{background:url('res/nav-un-2.png');}QPushButton:pressed{background:url('res/nav-un-3.png');}") self.ui.btnTask.setStyleSheet("QPushButton{background-image:url('res/nav-task-3.png');border:0px;}") def slot_close(self): os._exit(0) def slot_min(self): self.showMinimized() def slot_click_ad(self, ad): if(ad.type == "pkg"): print ad.urlorpkgid elif(ad.type == "url"): webbrowser.open_new_tab(ad.urlorpkgid) def slot_get_all_packages_over(self, sl): print len(sl) self.connect(self, SIGNAL("chksoftwareover"), self.slot_check_software_over) at = AsyncThread(self.check_software, sl) at.setDaemon(True) at.start() # at = CheckSoftwareThread(sl, self.scmap) # at.setDaemon(True) # at.start() from multiprocessing import Process, Queue, Pipe # q = Queue() # q.put(sl) # ap = AsyncProcess(self.check_software) # ap.start() # from multiprocessing import Process,Queue # q = Queue() # q.put(sl) # sll = ['1','2','3','1','2','3'] # one = sl[0] # print one # pipe = Pipe() # p = Process(target=self.check_software,args=(pipe[1],)) # pipe[0].send(one) # p.start() # print q.get() # data.softwareList = q.get() # print len(data.softwareList) # p.join() def slot_check_software_over(self, sl): print len(sl) data.softwareList = sl self.tmp_fill_recommend_softwares() self.tmp_get_ads() self.ui.categoryView.setEnabled(True) self.ui.btnUp.setEnabled(True) self.ui.btnUn.setEnabled(True) self.ui.btnTask.setEnabled(True) self.ui.allsMSGBar.setText("所有软件 <font color='#009900'>" + str(len(data.softwareList)) + "</font> 款,系统盘可用空间 <font color='#009900'>" + vfs.get_available_size() + "</font>") self.connect(data.sbo, SIGNAL("countiover"), self.slot_count_installed_over) at = AsyncThread(data.sbo.count_installed_software) at.setDaemon(True) at.start() self.connect(data.sbo, SIGNAL("countuover"), self.slot_count_upgradable_over) at = AsyncThread(data.sbo.count_upgradable_software) at.setDaemon(True) at.start() def slot_count_installed_over(self): print "iover..." self.ui.unMSGBar.setText("可卸载软件 <font color='#009900'>" + str(data.installedCount) + "</font> 款,系统盘可用空间 <font color='#009900'>" + vfs.get_available_size() + "</font>") def slot_count_upgradable_over(self): print "uover..." self.ui.upMSGBar.setText("可升级软件 <font color='#009900'>" + str(data.upgradableCount) + "</font> 款,系统盘可用空间 <font color='#009900'>" + vfs.get_available_size() + "</font>") def slot_backend_msg(self, msg): print msg
class MyApplication(QtWidgets.QMainWindow): def __assign_displays(self): """assigns display name """ self.displays = CDisplay.detect_display_devices() self.no_of_displays = len(self.displays) self.no_of_connected_dev = self.no_of_displays if self.no_of_displays == 1: self.display1 = self.displays[0] elif self.no_of_displays == 2: self.display1 = self.displays[0] self.display2 = self.displays[1] def __init__(self, parent=None): """Initializes""" QtWidgets.QMainWindow.__init__(self, parent) self.tray_menu = None self.tray_icon = None self.display1 = None self.display2 = None self.license_widget = None self.about_widget = None self.help_widget = None self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui_icon = QIcon() self.ui_icon.addFile(Filepath_handler.get_icon_path(), QSize(), QIcon.Normal, QIcon.Off) # icon.addFile("../../../../../../usr/share/icons/hicolor/scalable/apps/brightness-controller.svg", QSize(), QIcon.Normal, QIcon.Off) self.setWindowIcon(self.ui_icon) self.temperature = 'Default' self.no_of_connected_dev = 0 self.__assign_displays() self.setup_default_directory() self.generate_dynamic_items() self.default_config = '/home/{}/.config/' \ 'brightness_controller/settings' \ .format(getpass.getuser()) self.values = [] self.array_value = 0.01 for i in range(0, 100): self.values.append(self.array_value) self.array_value += 0.01 self.connect_handlers() self.setup_widgets() if path.exists(self.default_config): self.load_settings(self.default_config) self.canCloseToTray = False if QtWidgets.QSystemTrayIcon.isSystemTrayAvailable(): self.canCloseToTray = True self.setup_tray(parent) def setup_default_directory(self): """ Create default settings directory if it doesnt exist """ directory = '/home/{}/.config/' \ 'brightness_controller/' \ .format(getpass.getuser()) if not path.exists(directory): try: makedirs(directory) except OSError as e: self._show_error(str(e)) def closeEvent(self, event): """ Override CloseEvent for system tray """ if not self.canCloseToTray: reply = QtWidgets.QMessageBox.question( self, 'Message', "Are you sure to quit?", QtWidgets.QMessageBox.Yes, # QtWidgets.QMessageBox.Yes | # QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: event.accept() sys.exit(APP.exec_()) else: event.ignore() return else: if self.isVisible() is True: self.hide() event.ignore() else: reply = QtWidgets.QMessageBox.question( self, 'Message', "Are you sure to quit?", # QtWidgets.QMessageBox.Yes | # QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: event.accept() sys.exit(APP.exec_()) # else: # # fixes an odd event bug, the app never shows but prevents closing # self.show() # self.hide() # event.ignore() def setup_tray(self, parent): """ Setup system tray """ self.tray_menu = QtWidgets.QMenu(parent) show_action = QtWidgets.QAction("Show", self, statusTip="Show", triggered=self.show) quit_action = QtWidgets.QAction("Quit", self, statusTip="Quit", triggered=self.close) self.tray_menu.addAction(show_action) self.tray_menu.addAction(quit_action) icon = QtGui.QIcon() # icon_path = "icons/brightness-controller.svg" # icon_path = Filepath_handler.find_data_file(icon_path) # icon_path = # "/usr/share/icons/hicolor/scalable/apps/brightness-controller.svg" icon_path = Filepath_handler.get_icon_path() # print(icon_path) icon.addPixmap(QtGui.QPixmap(icon_path), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.tray_icon = QtWidgets.QSystemTrayIcon(icon, self) self.tray_icon.connect( QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self._icon_activated) self.tray_icon.setContextMenu(self.tray_menu) self.tray_icon.show() def _icon_activated(self, reason): if reason in (QtWidgets.QSystemTrayIcon.Trigger, QtWidgets.QSystemTrayIcon.DoubleClick): self.show() def setup_widgets(self): """connects the form widgets with functions""" self.license_widget = LicenseForm() self.license_widget.set_main_window(self) self.license_widget.hide() self.about_widget = AboutForm() self.about_widget.set_main_window(self) self.about_widget.hide() self.help_widget = HelpForm() self.help_widget.set_main_window(self) self.help_widget.hide() def generate_dynamic_items(self): """ manages widgets that may contain dynamic items. """ self.generate_brightness_sources() def generate_brightness_sources(self): """ generates assigns display sources to combo boxes """ if self.no_of_connected_dev < 2: self.ui.secondary_combo.addItem("Disabled") self.ui.secondary_combo.setEnabled(False) self.ui.primary_combobox.addItem("Disabled") self.ui.primary_combobox.setEnabled(False) return for display in self.displays: self.ui.secondary_combo.addItem(display) self.ui.primary_combobox.addItem(display) def connect_handlers(self): """Connects the handlers of GUI widgets""" self.ui.primary_brightness.valueChanged[int]. \ connect(self.change_value_pbr) self.ui.primary_red.valueChanged[int]. \ connect(self.change_value_pr) self.ui.primary_blue.valueChanged[int]. \ connect(self.change_value_pb) self.ui.primary_green.valueChanged[int]. \ connect(self.change_value_pg) self.enable_secondary_widgets(False) if self.no_of_connected_dev >= 2: self.enable_secondary_widgets(True) self.connect_secondary_widgets() if path.exists(self.default_config): self.ui.actionClearDefault.setVisible(True) self.ui.actionClearDefault.triggered.connect( self.delete_default_settings) self.ui.actionDefault.triggered.connect( lambda: self.save_settings(True)) self.ui.comboBox.activated[str].connect(self.combo_activated) self.ui.primary_combobox.activated[str].connect( self.primary_source_combo_activated) self.ui.secondary_combo.activated[str].connect( self.secondary_source_combo_activated) self.ui.actionAbout.triggered.connect(self.show_about) self.ui.actionExit.triggered.connect(self.close) self.ui.actionHelp.triggered.connect(self.show_help) self.ui.actionLicense.triggered.connect(self.show_license) self.ui.actionSave.triggered.connect(self.save_settings) self.ui.actionLoad.triggered.connect(self.load_settings) def enable_secondary_widgets(self, boolean): """ boolean - assigns boolean value to setEnabled(boolean) """ self.ui.secondary_brightness.setEnabled(boolean) self.ui.secondary_blue.setEnabled(boolean) self.ui.secondary_red.setEnabled(boolean) self.ui.secondary_green.setEnabled(boolean) def connect_secondary_widgets(self): """ connects the secondary widgets with functions """ self.ui.secondary_brightness.valueChanged[int]. \ connect(self.change_value_sbr) self.ui.secondary_red.valueChanged[int]. \ connect(self.change_value_sr) self.ui.secondary_blue.valueChanged[int]. \ connect(self.change_value_sb) self.ui.secondary_green.valueChanged[int]. \ connect(self.change_value_sg) def change_value_pbr(self, value): """Changes Primary Display Brightness""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[value], self.values[self.ui.primary_red.value()], self.values[self.ui.primary_green.value()], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pr(self, value): """Changes Primary Display Red ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[value], self.values[self.ui.primary_green.value()], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pg(self, value): """Changes Primary Display Green ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[self.ui.primary_red.value()], self.values[value], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pb(self, value): """Changes Primary Display Blue ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[self.ui.primary_red.value()], self.values[self.ui.primary_green.value()], self.values[value]) Executor.execute_command(cmd_value) def change_value_sbr(self, value): """ Changes Secondary Display Brightness """ cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[value], self.values[self.ui.secondary_red.value()], self.values[self.ui.secondary_green.value()], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sr(self, value): """Changes Secondary Display Red ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[value], self.values[self.ui.secondary_green.value()], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sg(self, value): """Changes Secondary Display Green ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[self.ui.secondary_red.value()], self.values[value], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sb(self, value): """Changes Primary Display Blue ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[self.ui.secondary_red.value()], self.values[self.ui.secondary_green.value()], self.values[value]) Executor.execute_command(cmd_value) def changed_state(self, state): if state == QtCore.Qt.Checked: temp = self.display1 self.display1 = self.display2 self.display2 = temp else: temp = self.display1 self.display1 = self.display2 self.display2 = temp def secondary_source_combo_activated(self, text): """ assigns combo value to display """ self.display2 = text def primary_source_combo_activated(self, text): """assigns combo value to display""" self.display1 = text def combo_activated(self, text): """ Designates values to display and to sliders """ self.temperature = text if text == 'Default': rgb = [255, 255, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '1900K Candle': rgb = [255, 147, 41] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '2600K 40W Tungsten': rgb = [255, 197, 143] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '2850K 100W Tungsten': rgb = [255, 214, 170] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '3200K Halogen': rgb = [255, 241, 224] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '5200K Carbon Arc': rgb = [255, 250, 244] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '5400K High Noon': rgb = [255, 255, 251] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '6000K Direct Sun': rgb = [255, 255, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '7000K Overcast Sky': rgb = [201, 226, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '20000K Clear Blue Sky': rgb = [64, 156, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) def change_primary_sliders(self, rgb): """ rgb - based on the rgb array, assign values to primary display sliders and in turn changes primary display color """ slider_r = int((rgb[0] * 100) / 255) slider_g = int((rgb[1] * 100) / 255) slider_b = int((rgb[2] * 100) / 255) self.ui.primary_red.setValue(slider_r) self.ui.primary_green.setValue(slider_g) self.ui.primary_blue.setValue(slider_b) def change_secondary_sliders(self, rgb): """ rgb - based on the rgb array, assign values to secondary display sliders and in turn changes secondary display color rgb is given in array from a range of 0 to 255 """ slider_r = int((rgb[0] * 100) / 255) slider_g = int((rgb[1] * 100) / 255) slider_b = int((rgb[2] * 100) / 255) self.ui.secondary_red.setValue(slider_r) self.ui.secondary_green.setValue(slider_g) self.ui.secondary_blue.setValue(slider_b) def change_secondary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for secondary monitor slider """ self.ui.secondary_brightness.setValue(br_rgb[0]) self.ui.secondary_red.setValue(br_rgb[1]) self.ui.secondary_green.setValue(br_rgb[2]) self.ui.secondary_blue.setValue(br_rgb[3]) def primary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for primary monitor sliders """ self.ui.primary_brightness.setValue(br_rgb[0]) self.ui.primary_red.setValue(br_rgb[1]) self.ui.primary_green.setValue(br_rgb[2]) self.ui.primary_blue.setValue(br_rgb[3]) def secondary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for primary monitor sliders """ self.ui.secondary_brightness.setValue(br_rgb[0]) self.ui.secondary_red.setValue(br_rgb[1]) self.ui.secondary_green.setValue(br_rgb[2]) self.ui.secondary_blue.setValue(br_rgb[3]) def show_about(self): """ Shows the About widget""" self.about_widget.show() def show_license(self): """ Shows the License widget""" self.license_widget.show() def show_help(self): """ Shows the Help Widget""" self.help_widget.show() def save_settings(self, default=False): """ save current primary and secondary display settings""" file_path = self.default_config if default else QtWidgets.QFileDialog.getSaveFileName( )[0] # just a number. path.exists won't work in case it is a new file. if len(file_path) > 5: if default: self.ui.actionClearDefault.setVisible(True) if self.no_of_connected_dev == 1: WriteConfig.write_primary_display( self.return_current_primary_settings(), file_path) elif self.no_of_connected_dev >= 2: WriteConfig.write_both_display( self.return_current_primary_settings(), self.return_current_secondary_settings(), file_path) def _show_error(self, message): """ Shows an Error Message""" QtWidgets.QMessageBox.critical(self, 'Error', message) def delete_default_settings(self): """ delete default settings """ if path.exists(self.default_config): try: remove(self.default_config) self.ui.actionClearDefault.setVisible(False) except OSError as e: self._show_error(str(e)) else: return False def _load_temperature(self, text='Default'): """ Load current temperature settings """ self.temperature = text primary_temperature_index = self.ui.comboBox.findText( text, QtCore.Qt.MatchFixedString) if primary_temperature_index >= 0: self.ui.comboBox.setCurrentIndex(primary_temperature_index) def load_settings(self, location=None): """ Load current primary and secondary display settings """ file_path = location or QtWidgets.QFileDialog.getOpenFileName()[0] if path.exists(file_path): loaded_settings = ReadConfig.read_configuration(file_path) if len(loaded_settings) == 5: self._load_temperature(loaded_settings[4]) self.primary_sliders_in_rgb_0_99(loaded_settings) elif len(loaded_settings) == 11: # checks just in case saved settings are for two displays, # but loads when only one display is connected if self.no_of_connected_dev == 1: self.primary_sliders_in_rgb_0_99( (loaded_settings[0], loaded_settings[1], loaded_settings[2], loaded_settings[3])) return # sets reverse control primary_source = loaded_settings[4] secondary_source = loaded_settings[10] self._load_temperature(loaded_settings[5]) primary_combo_index = self.ui.primary_combobox.findText( primary_source, QtCore.Qt.MatchFixedString) second_combo_index = self.ui.secondary_combo.findText( secondary_source, QtCore.Qt.MatchFixedString) if primary_combo_index >= 0: self.ui.primary_combobox.setCurrentIndex( primary_combo_index) self.primary_source_combo_activated(primary_source) if second_combo_index >= 0: self.ui.secondary_combo.setCurrentIndex(second_combo_index) self.secondary_source_combo_activated(secondary_source) self.primary_sliders_in_rgb_0_99( (loaded_settings[0], loaded_settings[1], loaded_settings[2], loaded_settings[3])) # (99, 99, 99, 99, 'LVDS-1', 99, 38, 99, 99, 'VGA-1') self.secondary_sliders_in_rgb_0_99( (loaded_settings[6], loaded_settings[7], loaded_settings[8], loaded_settings[9])) def return_current_primary_settings(self): """ return p_br_rgb(primary_brightness, primary_red, primary_green, primary_blue) """ # p_br_rgb = [] p_br_rgb = [ self.ui.primary_brightness.value(), self.ui.primary_red.value(), self.ui.primary_green.value(), self.ui.primary_blue.value(), self.display1, self.temperature ] return p_br_rgb def return_current_secondary_settings(self): """ return s_br_rgb(secondary_brightness, secondary_red, secondary_green, secondary_blue) """ s_br_rgb = [ self.ui.secondary_brightness.value(), self.ui.secondary_red.value(), self.ui.secondary_green.value(), self.ui.secondary_blue.value(), self.display2 ] # s_br_rgb = [] # s_br_rgb.append(self.ui.secondary_brightness.value()) # s_br_rgb.append(self.ui.secondary_red.value()) # s_br_rgb.append(self.ui.secondary_green.value()) # s_br_rgb.append(self.ui.secondary_blue.value()) return s_br_rgb
class Main(QtGui.QMainWindow): def __init__(self, parent=None): super(Main, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setFixedSize(648, 635) self.setWindowTitle("ChessQt") self.style = ["background: #333", "background: #fff"] self.ui.actionNowa_gra.triggered.connect(self.newGame) self.next_move = False for i in xrange(8): for j in xrange(8): m_label = MyLabel(i, j, self.style[(i + j) % 2]) labels[(i, j)] = m_label self.ui.gridLayout_2.addWidget(m_label, i, j) m_label.clicked.connect(self.slotClicked) self.newGame() def createPiece(self): chessboard[(6, 0)] = BlackPawn(6, 0, True) chessboard[(6, 1)] = BlackPawn(6, 1, True) chessboard[(6, 2)] = BlackPawn(6, 2, True) chessboard[(6, 3)] = BlackPawn(6, 3, True) chessboard[(6, 4)] = BlackPawn(6, 4, True) chessboard[(6, 5)] = BlackPawn(6, 5, True) chessboard[(6, 6)] = BlackPawn(6, 6, True) # chessboard[(6, 7)] = BlackPawn(6, 7, True) chessboard[(7, 0)] = Rook(7, 0, True) chessboard[(7, 1)] = Knight(7, 1, True) chessboard[(7, 2)] = Bishop(7, 2, True) chessboard[(7, 3)] = King(7, 3, True) self.white_king = chessboard[(7, 3)] chessboard[(7, 4)] = Queen(7, 4, True) chessboard[(7, 5)] = Bishop(7, 5, True) chessboard[(7, 6)] = Knight(7, 6, True) chessboard[(7, 7)] = Rook(7, 7, True) chessboard[(0, 0)] = Rook(0, 0, False) chessboard[(0, 1)] = Knight(0, 1, False) chessboard[(0, 2)] = Bishop(0, 2, False) chessboard[(0, 3)] = King(0, 3, False) self.black_king = chessboard[(0, 3)] chessboard[(0, 4)] = Queen(0, 4, False) chessboard[(0, 5)] = Bishop(0, 5, False) chessboard[(0, 6)] = Knight(0, 6, False) chessboard[(0, 7)] = Rook(0, 7, False) # chessboard[(1, 0)] = WhitePawn(1, 0, False) chessboard[(1, 1)] = WhitePawn(1, 1, False) chessboard[(1, 2)] = WhitePawn(1, 2, False) chessboard[(1, 3)] = WhitePawn(1, 3, False) chessboard[(1, 4)] = WhitePawn(1, 4, False) chessboard[(1, 5)] = WhitePawn(1, 5, False) chessboard[(1, 6)] = WhitePawn(1, 6, False) chessboard[(1, 7)] = WhitePawn(1, 7, False) def refreshPiece(self): for i in xrange(8): for j in xrange(8): if chessboard.has_key((i, j)): piece = chessboard.get((i, j)) if piece.alive: if piece.color: labels.get((i, j)).setImagePiece(piece.src_black) else: labels.get((i, j)).setImagePiece(piece.src_white) else: labels.get((i, j)).setImagePiece("") def deselectAll(self): for i in xrange(8): for j in xrange(8): labels.get((i, j)).setStyleSheet(self.style[(i + j) % 2]) def movePiece(self, x, y): chessboard.get((self.active_x, self.active_y)).move(x, y) chessboard[(x, y)] = chessboard.get((self.active_x, self.active_y)) del chessboard[(self.active_x, self.active_y)] self.deselectAll() self.refreshPiece() self.next_move = not self.next_move if not self.black_king.alive: dialog = QtGui.QDialog() elif not self.white_king.alive: QMessageBox.about(self, "Black wins.", "") def removePiece(self): for i in xrange(8): for j in xrange(8): if chessboard.has_key((i, j)): del chessboard[(i, j)] def newGame(self): self.removePiece() self.createPiece() self.refreshPiece() def slotNewGame(self): self.newGame() def slotClicked(self, x, y): if chessboard.has_key((x, y)) and labels.get((x, y)).styleSheet() == "background: #00f": chessboard.get((x, y)).makeNotAlive() self.movePiece(x, y) elif chessboard.has_key((x, y)): if chessboard.get((x, y)).color == self.next_move: for i in xrange(8): for j in xrange(8): labels[(i, j)].setStyleSheet(self.style[(i+j) % 2]) if chessboard.get((x, y)).moveValidator(i, j) and not chessboard.get((x, y)).isSelfHere(i, j): labels.get((i, j)).setStyleSheet("background: #00f") else: labels.get((x, y)).setStyleSheet(self.style[(i+j) % 2]) labels.get((x, y)).setStyleSheet("background: #f00") self.active_x = x self.active_y = y elif labels.get((x, y)).styleSheet() == "background: #00f": self.movePiece(x, y)
class TrabalhoComputacaoGrafica(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.createObjects() self.setup() self.world.add_polygn('Teste', [(30,30), (50,30), (50,50), (30,50)]) self.ui.edWindowFactor.setText('5') def createObjects(self): self.viewport = ViewPort() self.world = World() self.window = Window(self.viewport) self.world.add_window(self.window) self.world.connect_add_event(self.add_object) def setup(self): self.ui.gvMain.setScene(self.viewport) self.ui.lvObjects.contextMenuEvent = self.lvContextMenuEvent self.ui.lvObjects.connect(SIGNAL("itemClicked(QListWidgetItem *)"), self.itemClick) self.ui.btWindowUp.clicked.connect(self.window_up) self.ui.btWindowDown.clicked.connect(self.window_down) self.ui.btWindowRight.clicked.connect(self.window_right) self.ui.btWindowLeft.clicked.connect(self.window_left) self.ui.btWindowZoomIn.clicked.connect(self.window_zoomin) self.ui.btWindowZoomOut.clicked.connect(self.window_zoomout) self.viewport.mousePressEvent = self.sceneClick self.ui.btTranslaction.clicked.connect(self.translaction) self.ui.btStagger.clicked.connect(self.stagger) self.ui.btRotate.clicked.connect(self.rotate) self.createActions() def translaction(self, *args): tx = self.ui.edXTranslaction.text().strip() ty = self.ui.edYTranslaction.text().strip() if not tx or not ty: return tx = int(tx) ty = int(ty) selected_list = self.ui.lvObjects.selectedItems() if not selected_list: return obj = selected_list[0].obj self.world.translate_object(obj, (tx, ty)) def stagger(self, *args): sx = self.ui.edXStagger.text().strip() sy = self.ui.edYStagger.text().strip() if not sx or not sy: return sx = int(sx) sy = int(sy) selected_list = self.ui.lvObjects.selectedItems() if not selected_list: return obj = selected_list[0].obj self.world.stagge_object(obj, (sx, sy)) def rotate(self, *args): degree = self.ui.edRotationDegree.text().strip() if not degree: return degree = int(degree) selected_list = self.ui.lvObjects.selectedItems() if not selected_list: return obj = selected_list[0].obj if self.ui.rbRotationCenterWorld.isChecked(): x = (self.viewport.xmax-self.viewport.xmin)/2.0 y = (self.viewport.ymax-self.viewport.ymin)/2.0 self.world.rotate_object(obj, degree, x, y) elif self.ui.rbRotationCenterObject.isChecked(): self.world.rotate_object(obj, degree) else: x = int(self.ui.edXRotationSpecific.text()) y = int(self.ui.edYRotationSpecific.text()) self.world.rotate_object(obj, degree, x, y) def itemClick(self, item): self.world.select_object(item.obj) def sceneClick(self, event): pos = event.scenePos() obj = self.window.get_object_on_viewport(pos.x(), pos.y()) if obj: self.world.select_object(obj) self.select_object_on_list(obj) def select_object_on_list(self, obj): for i in range(self.ui.lvObjects.count()): if self.ui.lvObjects.item(i).obj == obj: self.ui.lvObjects.item(i).setSelected(True) def window_up(self, *args): factor = self.ui.edWindowFactor.text().strip() if not factor: return factor = int(factor) self.window.move_up(factor) def window_down(self, *args): factor = self.ui.edWindowFactor.text().strip() if not factor: return factor = int(factor) self.window.move_down(factor) def window_right(self, *args): factor = self.ui.edWindowFactor.text().strip() if not factor: return factor = int(factor) self.window.move_right(factor) def window_left(self, *args): factor = self.ui.edWindowFactor.text().strip() if not factor: return factor = int(factor) self.window.move_left(factor) def window_zoomin(self, *args): factor = self.ui.edWindowFactor.text().strip() if not factor: return factor = int(factor) self.window.zoomin(factor) def window_zoomout(self, *args): factor = self.ui.edWindowFactor.text().strip() if not factor: return factor = int(factor) self.window.zoomout(factor) def createActions(self): self.NewObjectAct = QtGui.QAction("Novo objeto", self, statusTip="Cria um novo objeto", triggered=self.newObject) def newObject(self): obj = TrabalhoComputacaoGraficaObject(self) obj.show() def lvContextMenuEvent(self, event): menu = QtGui.QMenu(self) menu.addAction(self.NewObjectAct) menu.exec_(event.globalPos()) def add_object(self, obj): self.ui.lvObjects.clear() for obj in self.world.obj_list: item = ObjectItem(obj) self.ui.lvObjects.addItem(item)
class SvakSvat(QMainWindow): """Member Registry Application.""" def __init__(self, session): """Create the window. session -- Sqlalchemy scoped_session. """ super().__init__() self.session = session # Assuming scoped_session self.initUI() try: self.ldapmanager = useraccounts.LDAPAccountManager() except Exception as e: print(e) print("Deaktiverar LDAP-integration.") self.ldapmanager = None self.setStatusMessage("Redo!", 3000) def initUI(self): """Create the window and connect the Qt signals to slots""" self.ui = Ui_MainWindow() self.ui.setupUi(self) # Connect signals to slots. self.ui.searchfield.textChanged.connect(self.searchlist) self.ui.memberlistwidget.currentRowChanged.connect(lambda: self.showMemberInfo()) self.ui.memberlistwidget.itemActivated.connect(self.editMember) self.ui.searchfield.returnPressed.connect(self.ui.memberlistwidget.setFocus) self.ui.actionNewMember.triggered.connect(self.createMember) self.ui.actionRemoveMember.triggered.connect(self.removeMember) self.ui.actionEditMember.triggered.connect(self.editMember) self.ui.actionMakeBackup.triggered.connect(self.makeBackup) self.ui.actionRestoreFromBackup.triggered.connect(self.restoreFromBackup) self.ui.memberlistwidget.addAction(self.ui.actionEditMember) self.ui.memberlistwidget.addAction(self.ui.actionRemoveMember) self.ui.memberlistwidget.setContextMenuPolicy(Qt.ActionsContextMenu) self.populateMemberList() self.setWindowTitle('SvakSvat') def makeBackup(self): filename = QFileDialog.getSaveFileName(self, 'Välj namn för säkerhetskopia', '.')[0] with open(filename, 'wb') as f: pickler = pickle.Pickler(f) pickler.dump(backup_everything(self.session)) def restoreFromBackup(self): filename = QFileDialog.getOpenFileName(self, 'Öppna säkerthetskopia', '.') with open(filename, 'rb') as f: data = pickle.Unpickler(f).load() if restore_everything(self.session, data): self.session.commit() self.populateMemberList() def createMember(self): newmemberdialog = NewMemberDialog(self.session, self) newmemberdialog.exec() def removeMember(self): """Remove selected member.""" member = self.currentMember() wholename = member.getWholeName() confirm = "Är du säker att du vill ta bort användaren %s?" % wholename reply = QMessageBox.question(self, 'Bekräfta', confirm, QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: self.session.delete(member) self.session.commit() self.populateMemberList() self.setStatusMessage("Användare %s borttagen!" % wholename) def populateMemberList(self, choosemember=None): """Fill the memberlist from the database.""" self.memberlist = self.session.query(Member).order_by( Member.surName_fld).all() self.ui.searchfield.clear() self.searchlist() if choosemember: memberindex = self.memberlist.index(choosemember) self.ui.memberlistwidget.setCurrentRow(memberindex) def currentMember(self): """Returns the currently selected member.""" member = self.filteredmemberlist[self.ui.memberlistwidget.currentRow()] return member def editMember(self): """Edit the currently selected member.""" member = self.currentMember() self.membereditwidget = MemberEdit(self.session, member, self, self.ldapmanager) self.membereditwidget.show() def searchlist(self, pattern=''): """Perform a filter operation on the memberlist. pattern -- The string to match. """ self.filteredmemberlist = [member for member in self.memberlist if member.getWholeName().upper().find(pattern.upper()) != -1] self.ui.memberlistwidget.clear() for member in self.filteredmemberlist: self.ui.memberlistwidget.addItem(member.getWholeName()) def showMemberInfo(self, member=None): """Show the member's info in the panel below. member -- backend.orm.Member to show. """ if not member: member = self.currentMember() contactinfo = member.contactinfo memberinfo = """Namn: %s %s Address: %s %s %s %s Telefon: %s Mobiltelefon: %s Email: %s Användarnamn: %s """ % ( member.givenNames_fld, member.surName_fld, contactinfo.streetAddress_fld, contactinfo.postalCode_fld, contactinfo.city_fld, contactinfo.country_fld, contactinfo.phone_fld, contactinfo.cellPhone_fld, contactinfo.email_fld, member.username_fld ) membershipinfo = self.getMembershipInfo(member) self.ui.memberinfo.setText(memberinfo + membershipinfo) def getMembershipInfo(self, member): """Get the current membershipinfo for a member. member -- backend.orm.Member Used in showMemberInfo""" currentposts = [postmembership.post.name_fld for postmembership in member.postmemberships if postmembership.isCurrent()] currentgroups = [groupmembership.group.name_fld for groupmembership in member.groupmemberships if groupmembership.isCurrent()] return ("\n".join(["\nPoster:"] + currentposts) + "\n".join(["\n\nGrupper:"] + currentgroups)) def setStatusMessage(self, message, milliseconds=3000): """Sets a status message in the MainWindow. message -- The status message to set. milliseconds -- The lifetime of the message. """ self.ui.statusbar.showMessage(message, milliseconds)
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowIcon(QIcon('icon.png')) self.ui.actionLoad_Lyrics.triggered.connect(self._load_lyrics_thread) self.cb_backends() # about widget self.aboutUi = About() self.ui.actionAbout.triggered.connect(self._about) self.aboutUi.setWindowModality(Qt.WindowModal) self._load_lyrics_thread() def cb_backends(self): self.cb_backends = QComboBox() self.cb_backends.addItem('Auto') menuLyricSource = QMenu(self.ui.menuEdit) menuLyricSource.setTitle('Lyric source') self.lyricGroup = QActionGroup(self) def addAction(name, checked=False): action = QAction(name, self) action.setText(name) action.setCheckable(True) action.setChecked(checked) action.setActionGroup(self.lyricGroup) return action menuLyricSource.addAction(addAction('Auto', True)) menuLyricSource.addSeparator() menuLyricSource.triggered.connect(self._menu_backend_change) for backend in Pyrics.get_backends(): menuLyricSource.addAction(addAction(backend.__name__)) self.cb_backends.addItem(backend.__name__) self.ui.menuEdit.addMenu(menuLyricSource) self.ui.toolBar.addWidget(self.cb_backends) self.cb_backends.currentIndexChanged.connect(self._cb_backend_change) def _load_lyrics_thread(self): self.thread = LoadLyricsWorker(self.cb_backends.currentIndex(), self) self.thread.trigger.connect(self._load_lyrics) self.thread.start() def _load_lyrics(self, content): self.ui.txLyrics.setText(content) def _about(self): self.aboutUi.show() def _menu_backend_change(self, action): index = self.cb_backends.findText(action.text()) self._update_backend(index) def _cb_backend_change(self, item): self._update_backend(item) def _update_backend(self, index): """Keep lyrics source combo in sync with the lyrics source in the menu""" if index >= 0: self.cb_backends.setCurrentIndex(index) name = self.cb_backends.currentText() for action in self.lyricGroup.actions(): action.setChecked(False) if action.text() == name: action.setChecked(True)
class MainWindow(QMainWindow): """Main application form class""" def __init__(self, data, classifier, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.set_data(data) self.classifier = classifier self.ui.cacl_button.clicked.connect(self.do_calc) def do_calc(self): row = self.get_row() res = self.classifier.get_labels_weights(row) self.set_result(res) def get_row(self): row = [] for i in xrange(self.data_set.n_features): if self.feature_active_checkboxes[i].checkState() != Qt.Checked: row.append(numpy.nan) elif i in self.data_set.feature_class_names.keys(): row.append(self.feature_inputs[i].currentIndex()) else: row.append(self.feature_inputs[i].value()) return row def set_result(self, values_count): s = sum(values_count.values()) for i in xrange(len(self.data_set.target_names)): val = int(100 * values_count[i]/s) if values_count.has_key(i) else 0 self.target_bars[i].setValue(val) def set_data(self, data_set): self.data_set = data_set self.feature_inputs = [] self.feature_active_checkboxes = [] for i, feature_name in zip(xrange(data_set.n_features), data_set.feature_names): rowLayout = QtGui.QHBoxLayout() featureLabel = QtGui.QLabel() active_checkbox = QtGui.QCheckBox() active_checkbox.setCheckState(Qt.Checked) featureLabel.setText(feature_name) featureLabel.setFixedWidth(150) if i in data_set.feature_class_names.keys(): combo = QtGui.QComboBox() for label in data_set.feature_class_names[i]: combo.addItem(label) input = combo else: input = QtGui.QSpinBox() input.setFixedWidth(150) self.feature_inputs.append(input) a = i def abc(state): self.feature_inputs[i].setEnabled(state == Qt.Checked) active_checkbox.stateChanged.connect( abc ) self.feature_active_checkboxes.append(active_checkbox) rowLayout.addWidget(active_checkbox) rowLayout.addWidget(input) rowLayout.addWidget(featureLabel) featureLabel.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding)) self.ui.features_layout.addLayout(rowLayout) self.target_bars = [] for target_name in data_set.target_names: rowLayout = QtGui.QHBoxLayout(self) target_label = QtGui.QLabel(self) target_label.setText(target_name) target_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)) target_label.setFixedWidth(100) bar = QtGui.QProgressBar() self.target_bars.append(bar) rowLayout.addWidget(bar) rowLayout.addWidget(target_label) self.ui.result_layout.addLayout(rowLayout) class TableModel(QAbstractTableModel): def __init__(self, data_set): super(TableModel, self).__init__(None) self.data_set = data_set def rowCount(self, index=QModelIndex()): """ Returns the number of rows the model holds. """ return self.data_set.n_samples def columnCount(self, index=QModelIndex()): return self.data_set.n_features + 1 def data(self, index, role=Qt.DisplayRole): """ Depending on the index and role given, return data. If not returning data, return None (PySide equivalent of QT's "invalid QVariant"). """ if role != Qt.DisplayRole: return None if not index.isValid(): return None #noinspection PyTypeChecker if not 0 <= index.row() < self.data_set.n_samples: return None if index.column() < self.data_set.n_features: # if self.data_set.feature_class_names.has_key(index.column()): # return unicode(self.data_set.feature_class_names[index.column()][int(self.data_set.data[index.row(), index.column()])]) return unicode(self.data_set.data[index.row(), index.column()]) else: return unicode(self.data_set.target_names[int(self.data_set.target[index.row()])]) def headerData(self, section, orientation, role=Qt.DisplayRole): """ Set the headers to be displayed. """ if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: if section < self.data_set.n_features: return self.data_set.feature_names[section] elif section == self.data_set.n_features: return "DS" return None self.ui.data_view.setModel(TableModel(data_set)) self.ui.data_view.update()
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self)
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("lx Midi Converter") self.setStyleSheet("background-color: #E5FFCC;") self.ui.convert.clicked.connect(self.convert_files) self.ui.convert.setStyleSheet("background-color: yellow;") self.ui.actionMidi_Folder.triggered.connect(self.open_folder_midi) self.ui.actionPreset_Folder.triggered.connect(self.open_preset_folder) self.ui.actionClose.triggered.connect(lambda: self.close()) x = 0 y = 0 for midi_file in midi_files.folders: self.ui.listFiles.insertItem(x, midi_file) for preset_file in preset_files.folders: self.ui.comboBox.insertItem(y, preset_file) def open_folder_midi(self): if self.ui.checkBox.checkState() == 2: print("rekursiv") else: print("nicht rekursiv") self.ui.listFiles.clear() fold = QFileDialog.getExistingDirectory(self, "Select midi folder...") if not fold[-1] == "/": fold = fold + "/" midi_files.midi_list(fold) x = 0 for midi_file in midi_files.folders: if ".mid" in midi_file: self.ui.listFiles.insertItem(x, midi_file) def open_preset_folder(self): self.ui.comboBox.clear() fold = QFileDialog.getExistingDirectory(self, "Select preset folder...") if not fold[-1] == "/": fold = fold + "/" preset_files.preset_list(fold) y = 0 for preset_file in preset_files.folders: self.ui.comboBox.insertItem(y, preset_file) def convert_files(self): select = self.ui.comboBox.currentText() extension = self.ui.extension.text() #selectedPreset = self.ui.listPresets.currentItem().text() result_in_box = [] subresult = [] try: with open("./presets/" + select, "r") as file: subArrayLine = [] noteReplace = [] b = 0 for line in file: data = json.loads(line) subArrayLine.append(data['original']) subArrayLine.append(data['replace']) subArrayLine.append(data['instrument']) noteReplace.append(subArrayLine) subArrayLine = [] b = b + 1 for midi_file in midi_files.folders: if ".mid" in midi_file: subresult.append(midi_file) check_mod_exist = midi_file.replace( ".mid", extension + ".mid") if not "_mod.mid" in midi_file and not check_mod_exist in midi_files.folders: mid = MidiFile(midi_files.pathm + midi_file) for i, track in enumerate(mid.tracks): for msg in track: if "note_on" in str(msg): x = 0 for pups in noteReplace: if msg.note == noteReplace[x][0]: msg.note = noteReplace[x][1] break x = x + 1 name_new = mid.filename.replace( ".mid", extension + ".mid") mid.save(name_new) subresult.append("Converted") #print("Created new MIDI file: "+ name_new) else: #print("done nothing") subresult.append("Done nothing") pass result_in_box.append(subresult) subresult = [] print(result_in_box) #bla = QMessageBox.about(self, "tite", result_in_box. except FileNotFoundError(): print("file not found")
class MainWindow(QMainWindow): connected = pyqtSignal(bool) def __init__(self, app): QMainWindow.__init__(self) self.app = app self.ui = Ui_MainWindow() self.ui.setupUi(self) self._exit = False self.ui.action_Exit.triggered.connect(self.exit) self.ui.actionAbout_Qt.triggered.connect(app.aboutQt) self.setWindowIcon(QIcon(':/icons/logo32')) self.listener = None self.tray = None self.pusher = None self._connected = False self.settings_dlg = SettingsDlg(self) self.settings_dlg.saved.connect(self.reconnect) self.tray = PushbulletTray(self) self.connect_actions() self.connect_pushbullet() self.tray.show() def connect_actions(self): self.ui.action_Settings.triggered.connect(self.settings_dlg.show) self.ui.browseFileBtn.clicked.connect(self.choice_file) self.ui.action_Refresh.triggered.connect(self.refresh) # List Items self.ui.addItemBtn.clicked.connect(self.add_item_list) self.ui.removeItemBtn.clicked.connect(self.remove_item_list) self.ui.clearItemsBtn.clicked.connect(self.clear_item_list) self.ui.itemsList.itemDoubleClicked.connect(self.edit_item_list) @pyqtSlot() def add_item_list(self): item = QListWidgetItem("item", self.ui.itemsList) item.setFlags(item.flags() | Qt.ItemIsEditable) self.ui.itemsList.addItem(item) @pyqtSlot() def remove_item_list(self): if self.ui.itemsList.currentRow() >= 0: self.ui.itemsList.takeItem(self.ui.itemsList.currentRow()) @pyqtSlot() def clear_item_list(self): self.ui.itemsList.clear() @pyqtSlot(QListWidgetItem) def edit_item_list(self, item): self.ui.itemsList.editItem(item) @pyqtSlot() def choice_file(self): file_to_send = QFileDialog.getOpenFileName(self, "choose file to send") if file_to_send and not file_to_send.isEmpty(): self.ui.filePathEdt.setText(file_to_send) @pyqtSlot() def refresh(self): self.refresh_devices() @pyqtSlot() def refresh_devices(self): self.ui.devicesList.clear() for device in self.pusher.devices: device_item = QListWidgetItem(device.nickname) device_item.setData(Qt.UserRole, device) self.ui.devicesList.addItem(device_item) def connect_pushbullet(self): if config.value('key') is not None and not config.value('key').toString().isEmpty(): proxy_host = str(config.value('proxy.host').toString()) proxy_port, int_conv_ok = config.value('proxy.port').toInt() if proxy_host.strip() == '': proxy_host = proxy_port = None self.pusher = PushBullet(str(config.value('key').toString())) self.listener = QPushBulletListener(self, self.pusher, proxy_host, proxy_port) self.listener.start() self.connect_systray() self.connect_pushes_actions() self.refresh_devices() self.connected.emit(True) self._connected = True else: self.connected.emit(False) def disconnect_pushbullet(self): self.connected.emit(False) if False and self.listener is not None: print "systray" self.disconnect_systray() print "listener quit" self.listener.quit() print "listener terminate" self.listener.terminate() print "disconnect_pushes" self.disconnect_pushes_actions() self.listener = None @pyqtSlot() def push_note(self): if self.pusher and len(self.ui.devicesList.selectedItems()) == 1: device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject() device.push_note(str(self.ui.noteTitleEdt.text()), str(self.ui.noteTextEdt.toPlainText())) else: QMessageBox.warning(self, "Cannot push", "There is no target device selected") @pyqtSlot() def push_link(self): if self.pusher and len(self.ui.devicesList.selectedItems()) == 1: device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject() device.push_link(str(self.ui.linkTitleEdt.text()), str(self.ui.linkUrlEdt.text())) else: QMessageBox.warning(self, "Cannot push", "There is no target device selected") @pyqtSlot() def push_list(self): if self.pusher and len(self.ui.devicesList.selectedItems()) == 1: device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject() widget_items = [self.ui.itemsList.item(n) for n in range(0, self.ui.itemsList.count())] items = map(lambda x: str(x.text()), widget_items) device.push_list(str(self.ui.listTitleEdt.text()), items) else: QMessageBox.warning(self, "Cannot push", "There is no target device selected") @pyqtSlot() def push_file(self): if self.pusher and len(self.ui.devicesList.selectedItems()) == 1: device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject() fname = str(self.ui.filePathEdt.text()) with open(fname, "rb") as f_to_send: success, file_data = self.pusher.upload_file(f_to_send, os.path.basename(fname)) if success: device.push_file(**file_data) else: QMessageBox.warning(self, "Cannot push", "There is no target device selected") @pyqtSlot() def push_address(self): if self.pusher and len(self.ui.devicesList.selectedItems()) == 1: device = self.ui.devicesList.selectedItems()[0].data(Qt.UserRole).toPyObject() device.push_address(str(self.ui.addressTitleEdt.text()), str(self.ui.addressTxt.toPlainText())) else: QMessageBox.warning(self, "Cannot push", "There is no target device selected") def connect_pushes_actions(self): self.ui.sendNoteBtn.clicked.connect(self.push_note) self.ui.sendLinkBtn.clicked.connect(self.push_link) self.ui.sendFileBtn.clicked.connect(self.push_file) self.ui.sendListBtn.clicked.connect(self.push_list) self.ui.sendAddressBtn.clicked.connect(self.push_address) def disconnect_pushes_actions(self): self.ui.sendNoteBtn.clicked.disconnect(self.push_note) self.ui.sendLinkBtn.clicked.disconnect(self.push_link) self.ui.sendFileBtn.clicked.disconnect(self.push_file) self.ui.sendListBtn.clicked.disconnect(self.push_list) self.ui.sendAddressBtn.clicked.disconnect(self.push_address) def connect_systray(self, ): if self.tray is not None: self.connected.connect(self.tray.connected) self.listener.on_link.connect(self.tray.on_link) self.listener.on_note.connect(self.tray.on_note) self.connected.emit(self._connected) def disconnect_systray(self): if self.tray is not None: self.listener.on_link.disconnect(self.tray.on_link) self.listener.on_note.disconnect(self.tray.on_note) @pyqtSlot() def reconnect(self): if self.listener is not None: self.disconnect_pushbullet() self.connect_pushbullet() @pyqtSlot() def exit(self): self._exit = True self.close() def closeEvent(self, event): if not self._exit: self.hide() event.ignore() else: QMainWindow.closeEvent(self, event)
class MainWin(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.lcdcurrent.display("00:00") self.ui.lcdtotal.display("00:00") self.PORT = False self.SHOW = False self.songs = [] self.chosen = 0 ###### WINDOW SETTINGS ###### try: self.setAttribute(QtCore.Qt.WA_Maemo5StackedWindow, True) self.setAttribute(QtCore.Qt.WA_Maemo5AutoOrientation, True); except: pass self.setWindowTitle("MaAmp - Offline") # Should show artist name here self.connect(QtGui.QApplication.desktop(), QtCore.SIGNAL("resized(int)"), self.orientationChanged ); ### SETUP CUSTOM LABEL, PUSHLABEL ### self.ui.cover_art = pushLabel(self) self.ui.cover_art.setGeometry(QtCore.QRect(20, 35, 280, 280)) self.ui.cover_art.setScaledContents(True) #self.ui.cover_art.setPixmap(QtGui.QPixmap(current[3])) self.ui.cover_art.setPixmap(QtGui.QPixmap(os.path.dirname(os.path.realpath( __file__ ) )+"/empty.png")) self.connect(self.ui.cover_art, QtCore.SIGNAL("clicked()"),self.animate) ### INIT THINGS ### self.getconnected() self.disablebuttons() ### ACTIONBUTTONS (MENU) ### self.connect(self.ui.actionConfigure, QtCore.SIGNAL("triggered()"),self.configure) self.connect(self.ui.actionAbout, QtCore.SIGNAL("triggered()"),self.about) self.connect(self.ui.actionFM_Radio, QtCore.SIGNAL('triggered()'), self.fmradio) self.connect(self.ui.actionClearRefresh, QtCore.SIGNAL('triggered()'), self.clearrefresh) ### BUTTONS ### self.connect(self.ui.artistsButton, QtCore.SIGNAL("clicked()"),self.listartists) #self.connect(self.ui.albumsButton, QtCore.SIGNAL("clicked()"),self.listalbums) ### PLAYER BUTTONS ### self.connect(self.ui.playButton, QtCore.SIGNAL("clicked()"),self.play) self.connect(self.ui.stopButton, QtCore.SIGNAL("clicked()"),self.stop) self.connect(self.ui.nextButton, QtCore.SIGNAL("clicked()"),self.next) self.connect(self.ui.previousButton, QtCore.SIGNAL("clicked()"),self.prev) self.connect(self.ui.listWidget, QtCore.SIGNAL("itemClicked(QListWidgetItem*)"), self.itemClicked) ### INIT ALL ANIMATIONS ### self.f_animate = QtCore.QPropertyAnimation(self.ui.frame, "geometry") self.f_animate.setDuration(ANIMSPEED) self.f2_animate = QtCore.QPropertyAnimation(self.ui.frame_2, "geometry") self.f2_animate.setDuration(ANIMSPEED) self.l_animate = QtCore.QPropertyAnimation(self.ui.listWidget, "geometry") self.l_animate.setDuration(ANIMSPEED) ### ANIMATION GEOMETRY ### ### PORTRAIT ### self.fp_visible = QtCore.QRect(35, 655, 411, 91) self.fp_invisible = QtCore.QRect (35, 810, 411, 91) self.f2p_visible = QtCore.QRect (0, 330, 480, 311) self.f2p_invisible = QtCore.QRect (490, 330, 480, 311) self.lp_visible = QtCore.QRect (0, 330, 480, 430) self.lp_invisible = QtCore.QRect (490, 330, 480, 430) ### LANDSCAPE ### self.fl_visible = QtCore.QRect (360, 330, 411, 91) self.fl_invisible = QtCore.QRect (360, 490, 411, 91) self.f2l_visible = QtCore.QRect (320, 5, 480, 311) self.f2l_invisible = QtCore.QRect (810, 5, 480, 311) self.ll_visible = QtCore.QRect (320, 0, 480, 430) self.ll_invisible = QtCore.QRect (810, 0, 480, 430) ### SETUP & INIT PHONON SOUND ### self.mediaObject = Phonon.createPlayer(Phonon.MusicCategory) self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory) #print self.audioOutput.outputDevice().name() self.mediaObject.setTickInterval(1000) self.mediaObject.tick.connect(self.tick) self.mediaObject.stateChanged.connect(self.stateChanged) self.mediaObject.currentSourceChanged.connect(self.sourceChanged) self.mediaObject.aboutToFinish.connect(self.aboutToFinish) self.mediaObject.finished.connect(self.finished) ### CREATE AND CONNCT SEEKSLIDER TO PHONON ### self.ui.seekSlider = Phonon.SeekSlider(self.mediaObject,self.ui.frame_2) self.ui.seekSlider.setGeometry(QtCore.QRect(10, 245, 268, 61)) self.ui.seekSlider.setOrientation(QtCore.Qt.Horizontal) self.ui.seekSlider.setObjectName("seekSlider") ### JUST TO UPDATE SCREEN... HMMM.... ### self.animate() ### STILL PHONON ### def play(self): QtGui.QApplication.processEvents() playing = (self.mediaObject.state() == Phonon.PlayingState) if not playing: self.ui.lcdtotal.display(self.current_song[4]) self.mediaObject.play() else: self.mediaObject.pause() try: self.setAttribute(QtCore.Qt.WA_Maemo5ShowProgressIndicator, False); except: pass def stop(self): self.ui.playButton.setText("Play") self.mediaObject.stop() def prev(self): QtGui.QApplication.processEvents() try: self.setAttribute(QtCore.Qt.WA_Maemo5ShowProgressIndicator, True); except: pass self.chosen = self.chosen - 1 if self.chosen < 0: self.chosen = len(self.songs)-1 self.ui.listWidget.setCurrentRow(self.chosen) self.url = self.amp.getSongurl(self.songs[self.chosen][6]) self.current_song = self.songs[self.chosen] self.ui.songLabel.setText(self.songs[self.chosen][1]) self.ui.songsLabel.setText("Songs: "+str(self.current_song[0])+"/"+str(len(self.songs))) self.ui.artistLabel.setText(self.songs[self.chosen][2]) self.ui.albumLabel.setText(self.songs[self.chosen][3]) self.mediaObject.setCurrentSource(Phonon.MediaSource(self.url)) self.ui.seekSlider.setMediaObject(self.mediaObject) self.play() def next(self): QtGui.QApplication.processEvents() try: self.setAttribute(QtCore.Qt.WA_Maemo5ShowProgressIndicator, True); except: pass self.chosen = self.chosen + 1 if self.chosen > len(self.songs): self.chosen = 0 self.ui.listWidget.setCurrentRow(self.chosen) self.url = self.amp.getSongurl(self.songs[self.chosen][6]) self.current_song = self.songs[self.chosen] self.ui.songLabel.setText(self.songs[self.chosen][1]) self.ui.songsLabel.setText("Songs: "+str(self.current_song[0])+"/"+str(len(self.songs))) self.ui.artistLabel.setText(self.songs[self.chosen][2]) self.ui.albumLabel.setText(self.songs[self.chosen][3]) self.mediaObject.setCurrentSource(Phonon.MediaSource(self.url)) self.ui.seekSlider.setMediaObject(self.mediaObject) self.play() def stateChanged(self, newState, oldState): if newState == Phonon.ErrorState: if self.mediaObject.errorType() == Phonon.FatalError: QtGui.QMessageBox.warning(self, "Fatal Error", self.mediaObject.errorString()) else: QtGui.QMessageBox.warning(self, "Error", self.mediaObject.errorString()) elif newState == Phonon.PlayingState: self.ui.playButton.setText("Pause") elif newState == Phonon.StoppedState: self.ui.lcdcurrent.display("00:00") elif newState == Phonon.PausedState: self.ui.playButton.setText("Play") def tick(self, time): displayTime = QtCore.QTime(0, (time / 60000) % 60, (time / 1000) % 60) self.ui.lcdcurrent.display(displayTime.toString('mm:ss')) def sourceChanged(self, source): pass def aboutToFinish(self): ### SO WE DONT HAVE TO WAIT FOR AMPACHEE-AUTH WHEN PLAYING NEXT ### if not self.amp.is_authenticated(): self.amp.authenticate() def finished(self): self.next() ### PHONON FINISHED ### ### ENABLE BUTTONS (IF ALBUM IS LOADED) ### def enablebuttons(self): self.ui.cover_art.setEnabled(True) self.ui.playButton.setEnabled(True) self.ui.stopButton.setEnabled(True) self.ui.nextButton.setEnabled(True) self.ui.previousButton.setEnabled(True) ### DISABLE BUTTONS (IF NO ALBUM IS LOADED) def disablebuttons(self): self.ui.cover_art.setEnabled(False) self.ui.playButton.setEnabled(False) self.ui.stopButton.setEnabled(False) self.ui.nextButton.setEnabled(False) self.ui.previousButton.setEnabled(False) ### TRY TO CONNECT TO AMPACHE ### def getconnected(self): ### GET AMACHE CONFIGURATION AND STUFF ### self.amp = ampache() self.config = self.amp.getconfig() if not self.config[0] == "http://": if self.amp.authenticate(): self.ui.actionConnect.setText(QtGui.QApplication.translate("MainWindow", "Connected", None, QtGui.QApplication.UnicodeUTF8)) self.ui.actionClearRefresh.setEnabled(True) self.ui.actionFM_Radio.setEnabled(True) self.ui.actionConnect.setChecked(True) self.artists = self.amp.getArtists() self.setWindowTitle("MaAmp - Online") ONLINE = True self.ui.frame.setEnabled(True) try: QMaemo5InformationBox.information(None, "Connected ... :)", 5000) except: pass else: self.setWindowTitle("MaAmp - Offline") self.ui.frame.setEnabled(False) self.ui.cover_art.setEnabled(False) self.ui.actionConnect.setText(QtGui.QApplication.translate("MainWindow", "Connect", None, QtGui.QApplication.UnicodeUTF8)) self.ui.actionClearRefresh.setEnabled(False) self.ui.actionFM_Radio.setEnabled(False) self.ui.actionConnect.setChecked(False) ONLINE = False else: self.setWindowTitle("MaAmp - Offline") self.ui.frame.setEnabled(False) self.ui.cover_art.setEnabled(False) self.ui.actionConnect.setText(QtGui.QApplication.translate("MainWindow", "Connect", None, QtGui.QApplication.UnicodeUTF8)) self.ui.actionClearRefresh.setEnabled(False) self.ui.actionFM_Radio.setEnabled(False) self.ui.actionConnect.setChecked(False) ONLINE = False #try: QMaemo5InformationBox.information(None, "You need to configure MaAmp!", 5000) #except: # pass def about(self): ad = AboutDialog(self) if self.PORT: ad.resize(480, 650) else: ad.resize(800, 400) ad.show() def configure(self): cd = ConfigDialog(self) ### SETUP UI ### if self.PORT: cd.resize(480, 267) else: cd.resize(800, 267) self.cdui = Ui_Config() self.cdui.setupUi(cd) self.cdui.serverEdit.setText(self.config[0]) self.cdui.userEdit.setText(self.config[1]) self.cdui.passwordEdit.setText(self.config[2]) self.cdui.autoLoginCheck.setChecked(self.config[3]) cd.show() if cd.exec_() == 1: self.config = [self.cdui.serverEdit.text(),self.cdui.userEdit.text(),self.cdui.passwordEdit.text(),self.cdui.autoLoginCheck.isChecked()] cd.destroy() self.amp.setconfig(self.config) if self.config[3] == True: self.getconnected() def itemClicked(self,item): QtGui.QApplication.processEvents() try: self.setAttribute(QtCore.Qt.WA_Maemo5ShowProgressIndicator, True); except: pass self.animate() if self.ui.listWidget.row(item) < 0: self.chosen = 1 else: self.chosen = self.ui.listWidget.row(item) self.url = self.amp.getSongurl(self.songs[self.chosen][6]) self.current_song = self.songs[self.chosen] self.ui.songLabel.setText(self.songs[self.chosen][1]) self.ui.songsLabel.setText("Songs: "+str(self.current_song[0])+"/"+str(len(self.songs))) self.ui.artistLabel.setText(self.songs[self.chosen][2]) self.ui.albumLabel.setText(self.songs[self.chosen][3]) self.ui.lcdtotal.display(self.current_song[4]) self.mediaObject.setCurrentSource(Phonon.MediaSource(self.url)) self.ui.seekSlider.setMediaObject(self.mediaObject) self.ui.seekSlider.setEnabled(True) self.play() self.ui.playButton.setText("Pause") def clearrefresh(self): result = self.amp.clearCache() self.artists = result def orientationChanged ( self ): #called when N900 is rotated screenGeometry=QtGui.QApplication.desktop().screenGeometry(); if screenGeometry.width() > screenGeometry.height(): #landscape if self.SHOW: # SHOW FRAMES, HIDE LISTWIDGET self.ui.frame.setGeometry(self.fl_visible) self.ui.frame_2.setGeometry(self.f2l_visible) self.ui.listWidget.setGeometry(self.ll_invisible) else: # SHOW LISTWIDGET, HIDE FRAMES self.ui.frame.setGeometry(self.fl_invisible) self.ui.frame_2.setGeometry(self.f2l_invisible) self.ui.listWidget.setGeometry(self.ll_visible) self.ui.artistsButton.setGeometry(QtCore.QRect(10, 340, 141, 71)) self.ui.playlistButton.setGeometry(QtCore.QRect(160, 340, 141, 71)) self.PORT = False else: #portrait if self.SHOW: # SHOW FRAMES, HIDE LISTWIDGET self.ui.frame.setGeometry(self.fp_visible) self.ui.frame_2.setGeometry(self.f2p_visible) self.ui.listWidget.setGeometry(self.lp_invisible) else: # SHOW LISTWIDGET, HIDE FRAMES self.ui.frame.setGeometry(self.fp_invisible) self.ui.frame_2.setGeometry(self.f2p_invisible) self.ui.listWidget.setGeometry(self.lp_visible) self.ui.artistsButton.setGeometry(QtCore.QRect(330, 140, 141, 71)) self.ui.playlistButton.setGeometry(QtCore.QRect(330, 220, 141, 71)) self.PORT = True def animate(self): if self.PORT: if self.SHOW: # SHOW LISTWIDGET, HIDE FRAMES self.f_animate.setStartValue(self.fp_visible) self.f_animate.setEndValue(self.fp_invisible) self.f2_animate.setStartValue(self.f2p_visible) self.f2_animate.setEndValue(self.f2p_invisible) self.l_animate.setStartValue(self.lp_invisible) self.l_animate.setEndValue(self.lp_visible) self.SHOW = False else: # SHOW FRAMES HIDE LISTWIDGET self.f_animate.setStartValue(self.fp_invisible) self.f_animate.setEndValue(self.fp_visible) self.f2_animate.setStartValue(self.f2p_invisible) self.f2_animate.setEndValue(self.f2p_visible) self.l_animate.setStartValue(self.lp_visible) self.l_animate.setEndValue(self.lp_invisible) self.SHOW = True else: if self.SHOW: # SHOW LISTWIDGET HIDE FRAMES self.f_animate.setStartValue(self.fl_visible) self.f_animate.setEndValue(self.fl_invisible) self.f2_animate.setStartValue(self.f2l_visible) self.f2_animate.setEndValue(self.f2l_invisible) self.l_animate.setStartValue(self.ll_invisible) self.l_animate.setEndValue(self.ll_visible) self.SHOW = False else: # SHOW FRAMES, HIDE LISTWIDGET self.f_animate.setStartValue(self.fl_invisible) self.f_animate.setEndValue(self.fl_visible) self.f2_animate.setStartValue(self.f2l_invisible) self.f2_animate.setEndValue(self.f2l_visible) self.l_animate.setStartValue(self.ll_visible) self.l_animate.setEndValue(self.ll_invisible) self.SHOW = True self.f_animate.start() self.f2_animate.start() self.l_animate.start() def connected(self): if self.ONLINE: self.ui.actionConnect.setText(QtGui.QApplication.translate("MainWindow", "Connected", None, QtGui.QApplication.UnicodeUTF8)) self.getconnected() self.ONLINE = True else: self.ui.actionConnect.setText(QtGui.QApplication.translate("MainWindow", "Connect", None, QtGui.QApplication.UnicodeUTF8)) self.disablebuttons() self.ONLINE = False # BORROWED FROM PYRADIO! # def fmradio(self, initial=False): #Turn on FM transmitter try : #test for FM transmitter. sysbus = dbus.SystemBus() fmtx = sysbus.get_object('com.nokia.FMTx', '/com/nokia/fmtx/default', False) fmtx_iface = dbus.Interface(fmtx, dbus_interface='org.freedesktop.DBus.Properties') state = fmtx_iface.Get("com.nokia.FMTx.Device", "state") if state == 'disabled': if not initial: self.ui.actionFM_Radio.setText(QtGui.QApplication.translate("MainWindow", "Disable FM", None, QtGui.QApplication.UnicodeUTF8)) fmtx_iface.Set("com.nokia.FMTx.Device", "state", dbus.String(u'%s' % 'enabled', variant_level=1)) else: self.ui.actionFM_Radio.setText(QtGui.QApplication.translate("MainWindow", "Enable FM", None, QtGui.QApplication.UnicodeUTF8)) else: if not initial: self.ui.actionFM_Radio.setText(QtGui.QApplication.translate("MainWindow", "Enable FM", None, QtGui.QApplication.UnicodeUTF8)) fmtx_iface.Set("com.nokia.FMTx.Device", "state", dbus.String(u'%s' % 'disabled', variant_level=1)) else: self.ui.actionEnable_FM_Radio.setText(QtGui.QApplication.translate("MainWindow", "Disable FM", None, QtGui.QApplication.UnicodeUTF8)) except: print "No FM Transmitter." ########################### def listartists(self): if not self.amp.is_authenticated(): self.getconnected() self.ArtistWin = ArtistWin(self) try: self.ArtistWin.setAttribute(QtCore.Qt.WA_Maemo5ShowProgressIndicator, True); except: pass self.ArtistWin.setWindowTitle("All Artists ("+str(len(self.artists))+")") self.ArtistWin.show() self.ArtistWin.artists(self.artists) def selectedAristAlbum(self,artist_id): album = self.amp.getAlbums(artist_id) self.selectedAlbum(album,0) def selectedAlbum(self,album,nr): QtGui.QApplication.processEvents() self.songs = self.amp.getSongs(album[nr][0]) self.ui.cover_art.setPixmap(QtGui.QPixmap(album[nr][3])) self.ui.songLabel.setText(self.songs[0][1]) self.ui.artistLabel.setText(self.songs[0][2]) self.ui.albumLabel.setText(self.songs[0][3]) self.ui.yearLabel.setText("Year: "+album[nr][6]) self.ui.songsLabel.setText("Songs: 1/"+str(album[nr][2])) self.ui.tagsLabel.setText(album[nr][7]) self.ui.listWidget.clear() for row in self.songs: self.ui.listWidget.addItem(row[1]) self.url = self.amp.getSongurl(self.songs[0][6]) self.current_song = self.songs[0] self.ui.lcdtotal.display(self.current_song[4]) wasPlaying = (self.mediaObject.state() == Phonon.PlayingState) if wasPlaying: self.stop() self.mediaObject.setCurrentSource(Phonon.MediaSource(self.url)) self.ui.seekSlider.setMediaObject(self.mediaObject) self.enablebuttons() self.SHOW = True self.animate() try: self.setAttribute(QtCore.Qt.WA_Maemo5ShowProgressIndicator, False); except: pass
class MainWindow(QMainWindow): scenarioRestore = pyqtSignal(QModelIndex) scriptUpdate = pyqtSignal() def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.targetActions = [ self.ui.actionMarkdown, self.ui.actionKAG3, self.ui.actionNScripter, ] # constants self.HESTIA_ARCHIVE_FILTER = self.tr("Hestia Archive(*.hax)") width = self.ui.splitterScenario.width() w = width // 3 m = width % 3 self.ui.splitterScenario.setSizes([w, w*2+m]) self.ui.splitterScript.setSizes([w, w*2+m]) self.highlighter = ScenarioHighlighter(self.ui.textEditScenario.document()) self.scenarioRestore.connect(self.scenarioRestored) self.errorMessageDialog = ErrorMessageDialog(self) self.previewHasReady = False self.glWindow = GLWindow(self) self.glWindow.setViewSize(1280, 720) self.glWindow.ready.connect(self.previewWindow_ready) self.glWindow.next.connect(self.previewWindow_toNext) self.glWindow.prev.connect(self.previewWindow_toPrev) self.doubleBufferObject = None self.initialize() QMetaObject.invokeMethod(self.glWindow, "show") def initialize(self): self.project = ProjectFile.create() self.projectModel = ProjectTreeModel(self) self.projectModel.projectUpdated.connect(self.projectModel_projectUpdated) # file selection view self.ui.treeViewScenario.setModel(self.projectModel) self.ui.treeViewStructure.setModel(self.projectModel) self.ui.treeViewScript.setModel(self.projectModel) self.scenarioSelection = self.ui.treeViewScenario.selectionModel() self.structureSelection = self.ui.treeViewStructure.selectionModel() self.scriptSelection = self.ui.treeViewScript.selectionModel() self.scenarioSelection.currentRowChanged.connect(self.scenarioSelection_currentRowChanged, Qt.QueuedConnection) self.structureSelection.currentRowChanged.connect(self.structureSelection_currentRowChanged) self.scriptSelection.currentRowChanged.connect(self.scriptSelection_currentRowChanged) # scenario structure view self.structureModel = StructureListModel(self) self.ui.listViewStructure.setModel(self.structureModel) self.lineSelection = self.ui.listViewStructure.selectionModel() self.lineSelection.currentRowChanged.connect(self.lineSelection_currentRowChanged) self.setProject(ProjectFile.create()) self.initializeScenario() def initializeScenario(self): self.setCurrentScenario(Scenario.create()) self.ui.textEditScenario.clear() self.scenarioSelection.setCurrentIndex(QModelIndex(), QItemSelectionModel.Clear) def currentIsChanged(self): text = qt.toUnicode(self.ui.textEditScenario.toPlainText()) return not self.currentScenario.isSame(text) def open(self, filepath): """ :type filepath: str """ self.setProject(ProjectFile.open(filepath)) def save(self, filepath): """ :type filepath: str """ assert(bool(filepath)) filepath = self.hestiaArchiveName(filepath) self.project.setFilePath(filepath) self.project.save() self.setWindowModified(False) def setProject(self, project): self.project = project self.project.changed.connect(self.projectChanged) self.project.changed.connect(self.projectModel.projectUpdate) self.projectModel.setProject(self.project) self.projectModel.projectUpdate() def setCurrentScenario(self, scenario): self.currentScenario = scenario filepath = self.currentScenario.filePath() if not filepath: self.setWindowTitle(self.tr("Hestia [*]")) def getOpenFileName(self, caption, path, filter): """ :rtype: str """ return qt.toUnicode(QFileDialog.getOpenFileName(self, caption, path, filter)) def getSaveFileName(self, caption, path, filter): """ :rtype: str """ return qt.toUnicode(QFileDialog.getSaveFileName(self, caption, path, filter)) def hestiaArchiveName(self, filepath): """ :type filepath: str :rtype: str """ root, ext = os.path.splitext(filepath) if ext != HESTIA_EXT: return root + HESTIA_EXT return filepath def closeEvent(self, event): if self.project.isChanged(): ret = QMessageBox.warning(self, self.tr("Project changed"), self.tr("Do you want to continue?"), QMessageBox.Cancel | QMessageBox.Discard) if ret == QMessageBox.Cancel: event.ignore() return @pyqtSlot(object) def projectChanged(self, container): self.setWindowModified(True) if container: filepath = container.filePath() self.setWindowTitle(self.tr("%1 - Hestia [*]").arg(filepath)) @pyqtSlot() def projectModel_projectUpdated(self): self.ui.treeViewScenario.setRootIndex(self.projectModel.index(0, 0)) self.ui.treeViewStructure.setRootIndex(self.projectModel.index(0, 0)) self.ui.treeViewScript.setRootIndex(self.projectModel.index(0, 0)) self.ui.treeViewScenario.expandAll() self.ui.treeViewStructure.expandAll() self.ui.treeViewScript.expandAll() @pyqtSlot() def previewWindow_ready(self): # set default font if __debug__: path = os.path.join(os.path.dirname(__file__), DEFAULT_FONT) else: appDir = six.text_type(QCoreApplication.applicationDirPath()) path = os.path.join(appDir, DEFAULT_FONT) if not os.path.exists(path): QMessageBox.critical(self, self.tr("Font not found"), self.tr("Font \"%1\" cannot open.").arg(path) ) sys.exit(1) font = ftgl.FTPixmapFont(path.encode(DEFAULT_ENCODING)) if not font.FaceSize(30): print("FaceSize error.", file=sys.stderr) self.glWindow.context().fontRegistry.installFont(None, font) # init double buffer self.doubleBufferObject = DoubleBufferObject() self.glWindow.setDoubleBufferObject(self.doubleBufferObject) # set to ready self.previewHasReady = True @pyqtSlot() def previewWindow_toNext(self): if not self.previewHasReady: return index = self.lineSelection.currentIndex() if not index.isValid(): return next = index.sibling(index.row()+1, index.column()) if not index.isValid(): return self.lineSelection.setCurrentIndex(next, QItemSelectionModel.SelectCurrent) @pyqtSlot() def previewWindow_toPrev(self): if not self.previewHasReady: return index = self.lineSelection.currentIndex() if not index.isValid(): return next = index.sibling(index.row()-1, index.column()) if not index.isValid(): return self.lineSelection.setCurrentIndex(next, QItemSelectionModel.SelectCurrent) @pyqtSlot() def on_actionNew_triggered(self): self.initialize() @pyqtSlot() def on_actionOpen_triggered(self): filepath = self.getOpenFileName(self.tr(""), self.tr(""), self.HESTIA_ARCHIVE_FILTER) if not filepath: return self.open(filepath) @pyqtSlot() def on_actionSave_triggered(self): filepath = self.project.filePath() if not filepath: filepath = self.getSaveFileName(self.tr(""), self.tr(""), self.HESTIA_ARCHIVE_FILTER) if not filepath: return filepath = self.hestiaArchiveName(filepath) self.save(filepath) @pyqtSlot() def on_actionSaveAs_triggered(self): filepath = self.getSaveFileName(self.tr(""), self.tr(""), self.HESTIA_ARCHIVE_FILTER) if not filepath: return self.save(filepath) @pyqtSlot() def on_actionScenarioNew_triggered(self): if self.currentIsChanged(): ret = QMessageBox.warning(self, self.tr("Text changed"), self.tr("Do you want to save it?"), QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Cancel: return elif ret == QMessageBox.Save: content = qt.toUnicode(self.ui.textEditScenario.toPlainText()) self.currentScenario.setText(content) self.initializeScenario() @pyqtSlot() def on_actionScenarioSave_triggered(self): filename = self.currentScenario.filePath() if not filename: dialog = FileNameEditDialog(self) if dialog.exec_() != QDialog.Accepted: return filename = dialog.fileName() root, ext = os.path.splitext(filename) if ext not in [".txt", ".md"]: filename += DEFAULT_EXT # set content content = qt.toUnicode(self.ui.textEditScenario.toPlainText()) self.currentScenario.setText(content) if self.currentScenario.filePath(): # filename is already set return # set filepath & register self.currentScenario.setFilePath(filename) self.project.append(self.currentScenario) @pyqtSlot() def on_actionScenarioSaveAs_triggered(self): dialog = FileNameEditDialog(self) if dialog.exec_() != QDialog.Accepted: return filename = dialog.fileName() root, ext = os.path.splitext(filename) if ext not in [".txt", ".md"]: filename += DEFAULT_EXT # set content content = qt.toUnicode(self.ui.textEditScenario.toPlainText()) scenario = Scenario.create() scenario.setText(content) # set filepath & register scenario.setFilePath(filename) self.project.append(scenario) self.setCurrentScenario(scenario) @pyqtSlot() def on_actionShowPreview_triggered(self): self.glWindow.show() @pyqtSlot(QAction) def on_menuTarget_triggered(self, target): # force checked target.setChecked(True) # Toggle target for action in self.targetActions: if action == target: continue if action.isChecked(): action.setChecked(False) current = self.scriptSelection.currentIndex() self.showScript(current) @pyqtSlot(QModelIndex, QModelIndex) def scenarioSelection_currentRowChanged(self, current, previous): if not current.isValid(): return currentItem = current.internalPointer() previousItem = previous.internalPointer() if not isinstance(currentItem, FileItem): return if currentItem == previousItem: return if currentItem.object.type() != ContainerType.Scenario: return if currentItem.object == self.currentScenario: return if self.currentIsChanged(): ret = QMessageBox.information(self, self.tr("Text Changed"), self.tr("Do you want to save it?"), QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard) if ret == QMessageBox.Cancel: self.scenarioRestore.emit(previous) return elif ret == QMessageBox.Save: self.currentScenario.setText(qt.toUnicode(self.ui.textEditScenario.toPlainText())) self.setCurrentScenario(currentItem.object) self.ui.textEditScenario.setScenario(self.currentScenario) filepath = self.currentScenario.filePath() self.setWindowTitle(self.tr("%1 - Hestia [*]").arg(filepath)) @pyqtSlot(QModelIndex, QModelIndex) def structureSelection_currentRowChanged(self, current, previous): if not current.isValid(): return currentItem = current.internalPointer() previousItem = previous.internalPointer() if not isinstance(currentItem, FileItem): return root = self.indexToDOM(current) if root is None: return self.structureModel.setRoot(root) @pyqtSlot(QModelIndex, QModelIndex) def scriptSelection_currentRowChanged(self, current, previous): self.showScript(current) @pyqtSlot(QModelIndex) def showScript(self, index): if not index.isValid(): self.ui.textEditScript.clear() return item = index.internalPointer() if not isinstance(item, FileItem): self.ui.textEditScript.clear() return root = self.indexToDOM(index) if root is None: self.ui.textEditScript.clear() return script = self.makeScript(root) self.ui.textEditScript.setPlainText(script) def indexToDOM(self, index): if not index.isValid(): return None item = index.internalPointer() if not isinstance(item, FileItem): return None if item.object.type() != ContainerType.Scenario: return None text = item.object.text() xhtml = converter.toXHTML(text) return etree.fromstring(xhtml) def makeScript(self, root): xslt = self.currentTargetXSLT() return six.text_type(xslt(root)) def currentTargetXSLT(self): root = qt.toUnicode(QCoreApplication.applicationDirPath()) if __debug__: root = os.path.dirname(__file__) if self.ui.actionMarkdown.isChecked(): return etree.XSLT(etree.parse(os.path.join(root, XSLT_MARKDOWN))) elif self.ui.actionKAG3.isChecked(): return etree.XSLT(etree.parse(os.path.join(root, XSLT_KAG3))) elif self.ui.actionNScripter.isChecked(): return etree.XSLT(etree.parse(os.path.join(root, XSLT_NSCRIPTER))) else: raise Exception @pyqtSlot(QModelIndex) def scenarioRestored(self, index): self.ui.treeViewScenario.setCurrentIndex(index) @pyqtSlot(QModelIndex, QModelIndex) def lineSelection_currentRowChanged(self, current, previous): if not self.previewHasReady: return if not current.isValid(): return node = current.internalPointer() # background image if node.ctx.bg_img: texture = self.doubleBufferObject.backBuffer().backgroundTexture() path = node.ctx.bg_img.src data = self.project.loadResource(path, test_exts=[".png"]) if data: obj = Image.fromData(texture, data) self.doubleBufferObject.setBackgroundImage(obj) else: # load failed self.errorMessageDialog.appendMessage( self.tr('Resource "%1" not found.').arg(path) ) self.errorMessageDialog.show() # message window obj = ( LoadIdentity() & Ortho2DContext() & BlendWrapper( Color(0.0, 0.0, 0.0, 0.5) & RelativeQuad(Rect(0.0, 0.0, 1280, 300)) ) ) self.doubleBufferObject.setMessageWindow(obj) # message text = self.currentText(current) obj = ( LoadIdentity() & Ortho2DContext() & Color(1.0, 1.0, 1.0) & RasterPos(100, 200) & TextObject(text) ) self.doubleBufferObject.setMessage(obj) self.doubleBufferObject.flip() def currentText(self, current): item = self.structureModel.data(current) return six.text_type(item)
class GridControl(QtWidgets.QMainWindow): """Create the UI, based on PyQt5. The UI elements are defined in "mainwindow.py" and resource file "resources_rc.py", created in QT Designer. To update "mainwindow.py": Run "pyuic5.exe --from-imports mainwindow.ui -o mainwindow.py" To update "resources_rc.py": Run "pyrcc5.exe resources.qrc -o resource_rc.py" Note: Never modify "mainwindow.py" or "resource_rc.py" manually. """ def __init__(self): super().__init__() # Create the main window self.ui = Ui_MainWindow() # Set upp the UI self.ui.setupUi(self) # Object for locking the serial port while sending/receiving data self.lock = threading.Lock() # Serial communication object self.ser = serial.Serial() # Initialize WMI communication with OpenHardwareMonitor # "initialize_hwmon()" returns a WMI object self.hwmon = openhwmon.initialize_hwmon() # QSettings object for storing the UI configuration in the OS native repository (Registry for Windows, ini-file for Linux) # In Windows, parameters will be stored at HKEY_CURRENT_USER/SOFTWARE/GridControl/App self.config = QtCore.QSettings('GridControl', 'App') # Get a list of available serial ports (e.g. "COM1" in Windows) self.serial_ports = grid.get_serial_ports() # Populate the "COM port" combo box with available serial ports self.ui.comboBoxComPorts.addItems(self.serial_ports) # Read saved UI configuration settings.read_settings(self.config, self.ui, self.hwmon) # Populates the tree widget on tab "Sensor Config" with values from OpenHardwareMonitor openhwmon.populate_tree(self.hwmon, self.ui.treeWidgetHWMonData, self.ui.checkBoxStartSilently.isChecked()) # System tray icon self.trayIcon = SystemTrayIcon( QtGui.QIcon(QtGui.QPixmap(":/icons/grid.png")), self) self.trayIcon.show() # Create a QThread object that will poll the Grid for fan rpm and voltage and HWMon for temperatures # The lock is needed in all operations with the serial port self.thread = polling.PollingThread( polling_interval=int(self.ui.comboBoxPolling.currentText()), ser=self.ser, lock=self.lock, cpu_sensor_ids=self.get_cpu_sensor_ids(), gpu_sensor_ids=self.get_gpu_sensor_ids(), cpu_calc="Max" if self.ui.radioButtonCPUMax.isChecked() else "Avg", gpu_calc="Max" if self.ui.radioButtonGPUMax.isChecked() else "Avg") # Connect signals and slots self.setup_ui_logic() # Setup UI parameters that cannot be defined in QT Designer self.setup_ui_design() # Store current horizontal slider values # Used for restoring values after automatic mode has been used self.manual_value_fan1 = self.ui.horizontalSliderFan1.value() self.manual_value_fan2 = self.ui.horizontalSliderFan2.value() self.manual_value_fan3 = self.ui.horizontalSliderFan3.value() self.manual_value_fan4 = self.ui.horizontalSliderFan4.value() self.manual_value_fan5 = self.ui.horizontalSliderFan5.value() self.manual_value_fan6 = self.ui.horizontalSliderFan6.value() # Minimize to tray if enabled if self.ui.checkBoxStartMinimized.isChecked(): self.setWindowState(QtCore.Qt.WindowMinimized) else: self.show() # Initialize communication self.init_communication() def setup_ui_logic(self): """Define QT signal and slot connections and initializes UI values.""" # Update "Fan percentage" LCD values from horizontal sliders initial value self.ui.lcdNumberFan1.display(self.ui.horizontalSliderFan1.value()) self.ui.lcdNumberFan2.display(self.ui.horizontalSliderFan2.value()) self.ui.lcdNumberFan3.display(self.ui.horizontalSliderFan3.value()) self.ui.lcdNumberFan4.display(self.ui.horizontalSliderFan4.value()) self.ui.lcdNumberFan5.display(self.ui.horizontalSliderFan5.value()) self.ui.lcdNumberFan6.display(self.ui.horizontalSliderFan6.value()) # Update "fan labels" from "Fan Config" tab self.ui.groupBoxFan1.setTitle(self.ui.lineEditFan1.text()) self.ui.groupBoxFan2.setTitle(self.ui.lineEditFan2.text()) self.ui.groupBoxFan3.setTitle(self.ui.lineEditFan3.text()) self.ui.groupBoxFan4.setTitle(self.ui.lineEditFan4.text()) self.ui.groupBoxFan5.setTitle(self.ui.lineEditFan5.text()) self.ui.groupBoxFan6.setTitle(self.ui.lineEditFan6.text()) self.ui.groupBoxCurrentFan1.setTitle(self.ui.lineEditFan1.text()) self.ui.groupBoxCurrentFan2.setTitle(self.ui.lineEditFan2.text()) self.ui.groupBoxCurrentFan3.setTitle(self.ui.lineEditFan3.text()) self.ui.groupBoxCurrentFan4.setTitle(self.ui.lineEditFan4.text()) self.ui.groupBoxCurrentFan5.setTitle(self.ui.lineEditFan5.text()) self.ui.groupBoxCurrentFan6.setTitle(self.ui.lineEditFan6.text()) self.ui.groupBoxConfigFan1.setTitle(self.ui.lineEditFan1.text()) self.ui.groupBoxConfigFan2.setTitle(self.ui.lineEditFan2.text()) self.ui.groupBoxConfigFan3.setTitle(self.ui.lineEditFan3.text()) self.ui.groupBoxConfigFan4.setTitle(self.ui.lineEditFan4.text()) self.ui.groupBoxConfigFan5.setTitle(self.ui.lineEditFan5.text()) self.ui.groupBoxConfigFan6.setTitle(self.ui.lineEditFan6.text()) # Connect events from sliders to update "Fan percentage" LCD value self.ui.horizontalSliderFan1.valueChanged.connect( self.ui.lcdNumberFan1.display) self.ui.horizontalSliderFan2.valueChanged.connect( self.ui.lcdNumberFan2.display) self.ui.horizontalSliderFan3.valueChanged.connect( self.ui.lcdNumberFan3.display) self.ui.horizontalSliderFan4.valueChanged.connect( self.ui.lcdNumberFan4.display) self.ui.horizontalSliderFan5.valueChanged.connect( self.ui.lcdNumberFan5.display) self.ui.horizontalSliderFan6.valueChanged.connect( self.ui.lcdNumberFan6.display) # Connect "Manual/Automatic" fan control radio button self.ui.radioButtonManual.toggled.connect(self.disable_enable_sliders) # Connect "Simulated temperatures" checkbox self.ui.checkBoxSimulateTemp.stateChanged.connect( self.simulate_temperatures) # Connect "Restart Communication" button self.ui.pushButtonRestart.clicked.connect(self.restart) # Connect "Add CPU sensors" button self.ui.pushButtonAddCPUSensor.clicked.connect(self.add_cpu_sensors) # Connect "Add GPU sensors" button self.ui.pushButtonAddGPUSensor.clicked.connect(self.add_gpu_sensors) # Connect "Remove CPU sensors" button self.ui.pushButtonRemoveCPUSensor.clicked.connect( self.remove_cpu_sensors) # Connect "Remove GPU sensors" button self.ui.pushButtonRemoveGPUSensor.clicked.connect( self.remove_gpu_sensors) # Connect event from changed serial port combo box self.ui.comboBoxComPorts.currentIndexChanged.connect( self.init_communication) # Connect event from changed polling interval combo box self.ui.comboBoxPolling.currentIndexChanged.connect( self.init_communication) # Update fan voltage (speed) based on changes to the horizontal sliders # # "grid.calculate_voltage" converts the percent value to valid voltages supported by the Grid # "lambda" is needed to send four arguments (serial object, fan id, fan voltage and lock object) self.ui.horizontalSliderFan1.valueChanged.connect(lambda: grid.set_fan( ser=self.ser, fan=1, voltage=grid.calculate_voltage(self.ui.lcdNumberFan1.value()), lock=self.lock)) self.ui.horizontalSliderFan2.valueChanged.connect(lambda: grid.set_fan( ser=self.ser, fan=2, voltage=grid.calculate_voltage(self.ui.lcdNumberFan2.value()), lock=self.lock)) self.ui.horizontalSliderFan3.valueChanged.connect(lambda: grid.set_fan( ser=self.ser, fan=3, voltage=grid.calculate_voltage(self.ui.lcdNumberFan3.value()), lock=self.lock)) self.ui.horizontalSliderFan4.valueChanged.connect(lambda: grid.set_fan( ser=self.ser, fan=4, voltage=grid.calculate_voltage(self.ui.lcdNumberFan4.value()), lock=self.lock)) self.ui.horizontalSliderFan5.valueChanged.connect(lambda: grid.set_fan( ser=self.ser, fan=5, voltage=grid.calculate_voltage(self.ui.lcdNumberFan5.value()), lock=self.lock)) self.ui.horizontalSliderFan6.valueChanged.connect(lambda: grid.set_fan( ser=self.ser, fan=6, voltage=grid.calculate_voltage(self.ui.lcdNumberFan6.value()), lock=self.lock)) # Connect "Change value" events from "Fan config" tab (all "spin boxes") to verify that the values are valid for fan in range(1, 7): getattr(self.ui, "spinBoxMinSpeedFan" + str(fan)).valueChanged.connect(self.validate_fan_config) getattr(self.ui, "spinBoxStartIncreaseSpeedFan" + str(fan)).valueChanged.connect(self.validate_fan_config) getattr(self.ui, "spinBoxIntermediateSpeedFan" + str(fan)).valueChanged.connect(self.validate_fan_config) getattr(self.ui, "spinBoxMaxSpeedFan" + str(fan)).valueChanged.connect(self.validate_fan_config) getattr(self.ui, "spinBoxIntermediateTempFan" + str(fan)).valueChanged.connect(self.validate_fan_config) getattr(self.ui, "spinBoxMaxTempFan" + str(fan)).valueChanged.connect(self.validate_fan_config) # Connect fan rpm signal (from polling thread) to fan rpm label self.thread.rpm_signal_fan1.connect(self.ui.labelRPMFan1.setText) self.thread.rpm_signal_fan2.connect(self.ui.labelRPMFan2.setText) self.thread.rpm_signal_fan3.connect(self.ui.labelRPMFan3.setText) self.thread.rpm_signal_fan4.connect(self.ui.labelRPMFan4.setText) self.thread.rpm_signal_fan5.connect(self.ui.labelRPMFan5.setText) self.thread.rpm_signal_fan6.connect(self.ui.labelRPMFan6.setText) # Connect fan voltage signal (from polling thread) to fan voltage value self.thread.voltage_signal_fan1.connect(self.ui.labelVFan1.setText) self.thread.voltage_signal_fan2.connect(self.ui.labelVFan2.setText) self.thread.voltage_signal_fan3.connect(self.ui.labelVFan3.setText) self.thread.voltage_signal_fan4.connect(self.ui.labelVFan4.setText) self.thread.voltage_signal_fan5.connect(self.ui.labelVFan5.setText) self.thread.voltage_signal_fan6.connect(self.ui.labelVFan6.setText) # Connect pixmap signal (from polling thread) for updating the fan status icon # "lambda" is needed to transmit two arguments, "icon resource name" from the signal (x) and fan id self.thread.pixmap_signal_fan1.connect( lambda x: self.change_fan_icon(x, 1)) self.thread.pixmap_signal_fan2.connect( lambda x: self.change_fan_icon(x, 2)) self.thread.pixmap_signal_fan3.connect( lambda x: self.change_fan_icon(x, 3)) self.thread.pixmap_signal_fan4.connect( lambda x: self.change_fan_icon(x, 4)) self.thread.pixmap_signal_fan5.connect( lambda x: self.change_fan_icon(x, 5)) self.thread.pixmap_signal_fan6.connect( lambda x: self.change_fan_icon(x, 6)) # Connect CPU and GPU temperature signals (from polling thread) to GPU and CPU LCD values self.thread.cpu_temp_signal.connect( self.ui.lcdNumberCurrentCPU.display) self.thread.gpu_temp_signal.connect( self.ui.lcdNumberCurrentGPU.display) # Connect update signal to fan update function self.thread.update_signal.connect(self.update_fan_speed) # Connect CPU and GPU temperature signals (from polling thread) to function for updating HWMon status self.thread.hwmon_status_signal.connect( self.ui.labelHWMonStatus.setText) # Connect exception signal to show exception message from running thread # This is needed as it's not possible to show a message box widget from the QThread directly self.thread.exception_signal.connect(self.thread_exception_handling) def validate_fan_config(self): """Validate fan configuration values, prevent incorrect/invalid values.""" # Name of widget (spin box) calling function sender = self.sender().objectName() # Fan id is the last character in the name fan = sender[-1:] # Get current values from spin boxes min_speed_fan = getattr(self.ui, "spinBoxMinSpeedFan" + str(fan)).value() start_increase_speed_fan = getattr( self.ui, "spinBoxStartIncreaseSpeedFan" + str(fan)).value() intermediate_speed_fan = getattr( self.ui, "spinBoxIntermediateSpeedFan" + str(fan)).value() max_speed_fan = getattr(self.ui, "spinBoxMaxSpeedFan" + str(fan)).value() intermediate_temp_fan = getattr( self.ui, "spinBoxIntermediateTempFan" + str(fan)).value() max_temp_fan = getattr(self.ui, "spinBoxMaxTempFan" + str(fan)).value() # Logic for preventing incorrect/invalid values if sender.startswith("spinBoxMinSpeedFan"): if min_speed_fan >= intermediate_speed_fan: getattr(self.ui, sender).setValue(intermediate_speed_fan - 1) elif sender.startswith("spinBoxStartIncreaseSpeedFan"): if start_increase_speed_fan >= intermediate_temp_fan: getattr(self.ui, sender).setValue(intermediate_temp_fan - 1) elif sender.startswith("spinBoxIntermediateSpeedFan"): if intermediate_speed_fan >= max_speed_fan: getattr(self.ui, sender).setValue(max_speed_fan - 1) if intermediate_speed_fan <= min_speed_fan: getattr(self.ui, sender).setValue(min_speed_fan + 1) elif sender.startswith("spinBoxMaxSpeedFan"): if max_speed_fan <= intermediate_speed_fan: getattr(self.ui, sender).setValue(intermediate_speed_fan + 1) elif sender.startswith("spinBoxIntermediateTempFan"): if intermediate_temp_fan >= max_temp_fan: getattr(self.ui, sender).setValue(max_temp_fan - 1) if intermediate_temp_fan <= start_increase_speed_fan: getattr(self.ui, sender).setValue(start_increase_speed_fan + 1) elif sender.startswith("spinBoxMaxTempFan"): if max_temp_fan <= intermediate_temp_fan: getattr(self.ui, sender).setValue(intermediate_temp_fan + 1) def setup_ui_design(self): """Define UI parameters that cannot be configured in QT Creator directly.""" # "OpenHardwareMonitor tree widget" configuration self.ui.treeWidgetHWMonData.setHeaderLabels( ["Node", "ID", "Temp (at init)"]) self.ui.treeWidgetHWMonData.expandAll() self.ui.treeWidgetHWMonData.setSortingEnabled(False) self.ui.treeWidgetHWMonData.sortByColumn(0, 0) self.ui.treeWidgetHWMonData.setColumnWidth(0, 200) self.ui.treeWidgetHWMonData.setColumnWidth(1, 100) self.ui.treeWidgetHWMonData.setColumnWidth(2, 50) # treeWidget.setColumnHidden(1, True) self.ui.treeWidgetHWMonData.setSelectionMode( QtWidgets.QAbstractItemView.MultiSelection) # "Selected CPU sensors" tree widget configuration self.ui.treeWidgetSelectedCPUSensors.setHeaderLabels(["Node", "ID"]) self.ui.treeWidgetSelectedCPUSensors.setColumnWidth(0, 150) self.ui.treeWidgetSelectedCPUSensors.setColumnWidth(1, 50) self.ui.treeWidgetSelectedCPUSensors.setSelectionMode( QtWidgets.QAbstractItemView.MultiSelection) # "Selected GPU sensors" tree widget configuration self.ui.treeWidgetSelectedGPUSensors.setHeaderLabels(["Node", "ID"]) self.ui.treeWidgetSelectedGPUSensors.setColumnWidth(0, 150) self.ui.treeWidgetSelectedGPUSensors.setColumnWidth(1, 50) self.ui.treeWidgetSelectedGPUSensors.setSelectionMode( QtWidgets.QAbstractItemView.MultiSelection) # "Simulate temperatures" group box settings self.ui.checkBoxSimulateTemp.setChecked(False) self.ui.horizontalSliderCPUTemp.setEnabled(False) self.ui.horizontalSliderGPUTemp.setEnabled(False) # If manual mode is enabled, disable "Simulate temperatures" if self.ui.radioButtonManual.isChecked(): self.ui.groupBoxSimulateTemperatures.setEnabled(False) # If automatic mode is enabled, disable the horizontal sliders if self.ui.radioButtonAutomatic.isChecked(): self.ui.horizontalSliderFan1.setEnabled(False) self.ui.horizontalSliderFan2.setEnabled(False) self.ui.horizontalSliderFan3.setEnabled(False) self.ui.horizontalSliderFan4.setEnabled(False) self.ui.horizontalSliderFan5.setEnabled(False) self.ui.horizontalSliderFan6.setEnabled(False) def init_communication(self): """Configure the serial device, serial port and polling interval before starting the polling thread. Called at: - Start of application - When the "Serial port" or "Polling interval" combo box is changed - When "Restart Communication" button is clicked """ # If the polling thread is running, stop it to be able to update port/polling interval and reset fans if self.thread.isRunning(): self.thread.stop() # Reset fan and temperature data (set rpm and voltage to "---" and temp to "0") self.reset_data() # If the serial port is open, close it with self.lock: if self.ser.isOpen(): self.ser.close() # Check if a serial port is selected if self.ui.comboBoxComPorts.currentText() != "<Select port>": # Setup serial device using selected serial port grid.setup_serial(self.ser, self.ui.comboBoxComPorts.currentText(), self.lock) # Open serial device grid.open_serial(self.ser, self.lock) # If manual mode is selected, enable horizontal sliders (they are disabled if no serial port is selected) if self.ui.radioButtonManual.isChecked(): self.ui.horizontalSliderFan1.setEnabled(True) self.ui.horizontalSliderFan2.setEnabled(True) self.ui.horizontalSliderFan3.setEnabled(True) self.ui.horizontalSliderFan4.setEnabled(True) self.ui.horizontalSliderFan5.setEnabled(True) self.ui.horizontalSliderFan6.setEnabled(True) # Enable other UI elements self.ui.radioButtonManual.setEnabled(True) self.ui.radioButtonAutomatic.setEnabled(True) self.ui.checkBoxSimulateTemp.setEnabled(True) if self.ui.checkBoxSimulateTemp.isChecked(): self.ui.horizontalSliderCPUTemp.setEnabled(True) self.ui.horizontalSliderGPUTemp.setEnabled(True) # Initialize the Grid+ V2 device if grid.initialize_grid(self.ser, self.lock): # Set the initial fan speeds based on UI values self.initialize_fans() # Update the polling interval (ms) based on UI value self.thread.update_polling_interval(new_polling_interval=int( self.ui.comboBoxPolling.currentText())) # Update temperature calculation (Maximum or Average) based on UI settings on "Sensor Config" tab self.thread.set_temp_calc( cpu_calc="Max" if self.ui.radioButtonCPUMax.isChecked() else "Avg", gpu_calc="Max" if self.ui.radioButtonGPUMax.isChecked() else "Avg") # Start the polling thread self.thread.start() # Update status in UI self.ui.labelPollingStatus.setText( '<b><font color="green">Running</font></b>') # Handle unsuccessful initialization else: # As there is a communication problem, reset the "serial port" combo box index = self.ui.comboBoxComPorts.findText("<Select port>") self.ui.comboBoxComPorts.setCurrentIndex(index) # Update status in UI self.ui.labelPollingStatus.setText( '<b><font color="red">Stopped</font></b>') # If no serial port is selected, disable UI elements else: self.ui.horizontalSliderFan1.setEnabled(False) self.ui.horizontalSliderFan2.setEnabled(False) self.ui.horizontalSliderFan3.setEnabled(False) self.ui.horizontalSliderFan4.setEnabled(False) self.ui.horizontalSliderFan5.setEnabled(False) self.ui.horizontalSliderFan6.setEnabled(False) self.ui.radioButtonManual.setEnabled(False) self.ui.radioButtonAutomatic.setEnabled(False) self.ui.checkBoxSimulateTemp.setEnabled(False) self.ui.horizontalSliderCPUTemp.setEnabled(False) self.ui.horizontalSliderGPUTemp.setEnabled(False) self.ui.horizontalSliderCPUTemp.setValue(0) self.ui.horizontalSliderGPUTemp.setValue(0) def reset_data(self): """Reset fan rpm and voltage to "---" and activate the red status icon. Reset CPU and GPU temperature to "0".""" # Reset fan rpm self.ui.labelRPMFan1.setText('<b><font color="red">---</font></b>') self.ui.labelRPMFan2.setText('<b><font color="red">---</font></b>') self.ui.labelRPMFan3.setText('<b><font color="red">---</font></b>') self.ui.labelRPMFan4.setText('<b><font color="red">---</font></b>') self.ui.labelRPMFan5.setText('<b><font color="red">---</font></b>') self.ui.labelRPMFan6.setText('<b><font color="red">---</font></b>') # Reset fan voltage self.ui.labelVFan1.setText('<b><font color="red">---</font></b>') self.ui.labelVFan2.setText('<b><font color="red">---</font></b>') self.ui.labelVFan3.setText('<b><font color="red">---</font></b>') self.ui.labelVFan4.setText('<b><font color="red">---</font></b>') self.ui.labelVFan5.setText('<b><font color="red">---</font></b>') self.ui.labelVFan6.setText('<b><font color="red">---</font></b>') # Activate the red led icon self.ui.labelStatusFan1.setPixmap(QtGui.QPixmap(ICON_RED_LED)) self.ui.labelStatusFan2.setPixmap(QtGui.QPixmap(ICON_RED_LED)) self.ui.labelStatusFan3.setPixmap(QtGui.QPixmap(ICON_RED_LED)) self.ui.labelStatusFan4.setPixmap(QtGui.QPixmap(ICON_RED_LED)) self.ui.labelStatusFan5.setPixmap(QtGui.QPixmap(ICON_RED_LED)) self.ui.labelStatusFan6.setPixmap(QtGui.QPixmap(ICON_RED_LED)) # Reset temperatures self.ui.lcdNumberCurrentCPU.display(0) self.ui.lcdNumberCurrentGPU.display(0) # Update status in UI self.ui.labelPollingStatus.setText( '<b><font color="red">Stopped</font></b>') self.ui.labelHWMonStatus.setText('<b><font color="red">---</font></b>') def initialize_fans(self): """Initialize fans to the initial slider values.""" grid.set_fan(ser=self.ser, fan=1, voltage=grid.calculate_voltage( self.ui.lcdNumberFan1.value()), lock=self.lock) grid.set_fan(ser=self.ser, fan=2, voltage=grid.calculate_voltage( self.ui.lcdNumberFan2.value()), lock=self.lock) grid.set_fan(ser=self.ser, fan=3, voltage=grid.calculate_voltage( self.ui.lcdNumberFan3.value()), lock=self.lock) grid.set_fan(ser=self.ser, fan=4, voltage=grid.calculate_voltage( self.ui.lcdNumberFan4.value()), lock=self.lock) grid.set_fan(ser=self.ser, fan=5, voltage=grid.calculate_voltage( self.ui.lcdNumberFan5.value()), lock=self.lock) grid.set_fan(ser=self.ser, fan=6, voltage=grid.calculate_voltage( self.ui.lcdNumberFan6.value()), lock=self.lock) def disable_enable_sliders(self): """Disables the horizontal sliders if "Automatic" mode is selected. When changing from automatic to manual mode, restore manual values.""" # If "Automatic" radio button was clicked (i.e. it's "Checked") if self.ui.radioButtonAutomatic.isChecked(): # Save current manual values self.manual_value_fan1 = self.ui.horizontalSliderFan1.value() self.manual_value_fan2 = self.ui.horizontalSliderFan2.value() self.manual_value_fan3 = self.ui.horizontalSliderFan3.value() self.manual_value_fan4 = self.ui.horizontalSliderFan4.value() self.manual_value_fan5 = self.ui.horizontalSliderFan5.value() self.manual_value_fan6 = self.ui.horizontalSliderFan6.value() # Disable sliders self.ui.horizontalSliderFan1.setEnabled(False) self.ui.horizontalSliderFan2.setEnabled(False) self.ui.horizontalSliderFan3.setEnabled(False) self.ui.horizontalSliderFan4.setEnabled(False) self.ui.horizontalSliderFan5.setEnabled(False) self.ui.horizontalSliderFan6.setEnabled(False) # Enable simulate temperatures self.ui.groupBoxSimulateTemperatures.setEnabled(True) # If "Manual" radio button was clicked else: # Restore saved manual values self.ui.horizontalSliderFan1.setValue(self.manual_value_fan1) self.ui.horizontalSliderFan2.setValue(self.manual_value_fan2) self.ui.horizontalSliderFan3.setValue(self.manual_value_fan3) self.ui.horizontalSliderFan4.setValue(self.manual_value_fan4) self.ui.horizontalSliderFan5.setValue(self.manual_value_fan5) self.ui.horizontalSliderFan6.setValue(self.manual_value_fan6) # Enable sliders self.ui.horizontalSliderFan1.setEnabled(True) self.ui.horizontalSliderFan2.setEnabled(True) self.ui.horizontalSliderFan3.setEnabled(True) self.ui.horizontalSliderFan4.setEnabled(True) self.ui.horizontalSliderFan5.setEnabled(True) self.ui.horizontalSliderFan6.setEnabled(True) # Disable simulate temperatures self.ui.groupBoxSimulateTemperatures.setEnabled(False) self.ui.checkBoxSimulateTemp.setChecked(False) def update_fan_speed(self): """Update fan speed based on CPU and GPU temperatures.""" # If automatic mode is selected if self.ui.radioButtonAutomatic.isChecked(): # For each fan (1 ... 6) for fan in range(1, 7): # Linear equation calculation # y = k*x + m # k = (y2 - y1) / (x2 - x1) # First equation (a): # From "Start increase speed at" to "Intermediate fan speed at" (temperature on x-axis) # Temperatures (x-axis) x1_a = int( getattr(self.ui, "spinBoxStartIncreaseSpeedFan" + str(fan)).value()) x2_a = int( getattr(self.ui, "spinBoxIntermediateTempFan" + str(fan)).value()) # Speed in percent (y-axis) y1_a = int( getattr(self.ui, "spinBoxMinSpeedFan" + str(fan)).value()) y2_a = int( getattr(self.ui, "spinBoxIntermediateSpeedFan" + str(fan)).value()) # Calculate "k" and "m" k_a = (y2_a - y1_a) / (x2_a - x1_a) m_a = y1_a - k_a * x1_a # Second equation (b) # From "Intermediate fan speed at" to "Maximum fan speed at" (temperature on x-axis) # Temperatures (x-axis) x1_b = int( getattr(self.ui, "spinBoxIntermediateTempFan" + str(fan)).value()) x2_b = int( getattr(self.ui, "spinBoxMaxTempFan" + str(fan)).value()) # Speed in percent (y-axis) y1_b = int( getattr(self.ui, "spinBoxIntermediateSpeedFan" + str(fan)).value()) y2_b = int( getattr(self.ui, "spinBoxMaxSpeedFan" + str(fan)).value()) # Calculate "k" and "m" k_b = (y2_b - y1_b) / (x2_b - x1_b) m_b = y1_b - k_b * x1_b min_temperature = int( getattr(self.ui, "spinBoxStartIncreaseSpeedFan" + str(fan)).value()) intermediate_temperature = int( getattr(self.ui, "spinBoxIntermediateTempFan" + str(fan)).value()) max_temperature = int( getattr(self.ui, "spinBoxMaxTempFan" + str(fan)).value()) # If "Use CPU temperature" is selected, use current CPU temperature (from LCD widget in UI) if getattr(self.ui, "radioButtonCPUFan" + str(fan)).isChecked(): current_temperature = self.ui.lcdNumberCurrentCPU.value() # Else, use current GPU temperature (from LCD widget i UI) else: current_temperature = self.ui.lcdNumberCurrentGPU.value() if current_temperature <= min_temperature: # Set fan to minimum fan speed (constant value) fan_speed = int( getattr(self.ui, "spinBoxMinSpeedFan" + str(fan)).value()) elif current_temperature <= intermediate_temperature: # Calculate temperature according to first linear equation fan_speed = k_a * current_temperature + m_a elif current_temperature <= max_temperature: # Calculate temperature according to second linear equation fan_speed = k_b * current_temperature + m_b else: # Set fan to maximum fan speed (constant value) fan_speed = int( getattr(self.ui, "spinBoxMaxSpeedFan" + str(fan)).value()) # Update horizontal slider value getattr(self.ui, "horizontalSliderFan" + str(fan)).setValue( round(fan_speed)) def simulate_temperatures(self): """Simulate CPU and GPU temperatures, used for verifying the functionality of the fan control system.""" # If "Simulate temperatures" checkbox is enabled if self.ui.checkBoxSimulateTemp.isChecked(): # Enable sliders self.ui.horizontalSliderCPUTemp.setEnabled(True) self.ui.horizontalSliderGPUTemp.setEnabled(True) # Update CPU and GPU values from current horizontal slider values self.ui.lcdNumberCurrentCPU.display( self.ui.horizontalSliderCPUTemp.value()) self.ui.lcdNumberCurrentGPU.display( self.ui.horizontalSliderGPUTemp.value()) # Disconnect temperature signals from polling thread self.thread.cpu_temp_signal.disconnect( self.ui.lcdNumberCurrentCPU.display) self.thread.gpu_temp_signal.disconnect( self.ui.lcdNumberCurrentGPU.display) # Connect the horizontal sliders to the "CPU" and "GPU" LCD widget self.ui.horizontalSliderCPUTemp.valueChanged.connect( self.ui.lcdNumberCurrentCPU.display) self.ui.horizontalSliderGPUTemp.valueChanged.connect( self.ui.lcdNumberCurrentGPU.display) # Update group box headers to indicate simulation mode self.ui.groupBoxCurrentCPUTemp.setTitle("Sim. CPU temp") self.ui.groupBoxCurrentGPUTemp.setTitle("Sim. GPU temp") # If "Simulate temperatures" checkbox is disabled, reset settings else: # Disable horizontal sliders self.ui.horizontalSliderCPUTemp.setEnabled(False) self.ui.horizontalSliderGPUTemp.setEnabled(False) # Reconnect signals from polling thread self.thread.cpu_temp_signal.connect( self.ui.lcdNumberCurrentCPU.display) self.thread.gpu_temp_signal.connect( self.ui.lcdNumberCurrentGPU.display) # Reset headers in UI self.ui.groupBoxCurrentCPUTemp.setTitle("Current CPU temp") self.ui.groupBoxCurrentGPUTemp.setTitle("Current GPU temp") def restart(self): """Update 'Selected CPU and GPU sensors' and restart application""" # TODO: Add apply button self.thread.update_sensors(self.get_cpu_sensor_ids(), self.get_gpu_sensor_ids()) self.init_communication() def thread_exception_handling(self, msg): """Display an error message with details about the exception and reset the "serial port value" to <Select port>. Called when an exception occurs in the polling thread.""" # Show error message helper.show_error(msg) # Reset the "serial port" combo box index = self.ui.comboBoxComPorts.findText("<Select port>") self.ui.comboBoxComPorts.setCurrentIndex(index) def add_cpu_sensors(self): """Add selected temperature sensor(s) to the "Selected CPU sensor(s)" three widget.""" items = [item for item in self.ui.treeWidgetHWMonData.selectedItems()] # The new items should have the tree widget itself as parent parent = self.ui.treeWidgetSelectedCPUSensors for item in items: sensor_item = QtWidgets.QTreeWidgetItem(parent) sensor_item.setText(0, item.text(0)) sensor_item.setText(1, item.text(1)) sensor_item.setForeground(0, QtGui.QBrush( QtCore.Qt.blue)) # Text color blue # Deselect all items in the HWMon tree widget after they have been added self.ui.treeWidgetHWMonData.clearSelection() def add_gpu_sensors(self): """Add selected temperature sensor(s) to the "Selected GPU sensor(s)" three widget.""" items = [item for item in self.ui.treeWidgetHWMonData.selectedItems()] # The new items should have the tree widget itself as parent parent = self.ui.treeWidgetSelectedGPUSensors for item in items: sensor_item = QtWidgets.QTreeWidgetItem(parent) sensor_item.setText(0, item.text(0)) sensor_item.setText(1, item.text(1)) sensor_item.setForeground(0, QtGui.QBrush( QtCore.Qt.blue)) # Text color blue # Deselect all items in the HWMon tree widget after they have been added self.ui.treeWidgetHWMonData.clearSelection() def remove_cpu_sensors(self): """Remove selected CPU sensors.""" root = self.ui.treeWidgetSelectedCPUSensors.invisibleRootItem() for item in self.ui.treeWidgetSelectedCPUSensors.selectedItems(): root.removeChild(item) def remove_gpu_sensors(self): """Remove selected GPU sensors.""" root = self.ui.treeWidgetSelectedGPUSensors.invisibleRootItem() for item in self.ui.treeWidgetSelectedGPUSensors.selectedItems(): root.removeChild(item) def get_cpu_sensor_ids(self): """Get id's for each sensor in the "Selected CPU sensors" tree.""" root = self.ui.treeWidgetSelectedCPUSensors.invisibleRootItem() child_count = root.childCount() cpu_sensor_ids = [] for i in range(child_count): item = root.child(i) cpu_sensor_ids.append(item.text(1)) # Second column is the id return cpu_sensor_ids def get_gpu_sensor_ids(self): """Get id's for each sensor in the "Selected GPU sensors" tree.""" root = self.ui.treeWidgetSelectedGPUSensors.invisibleRootItem() child_count = root.childCount() gpu_sensor_ids = [] for i in range(child_count): item = root.child(i) gpu_sensor_ids.append(item.text(1)) # Second column is the id return gpu_sensor_ids def change_fan_icon(self, icon, fan): """Update the fan status icon.""" if fan == 1: self.ui.labelStatusFan1.setPixmap(QtGui.QPixmap(icon)) if fan == 2: self.ui.labelStatusFan2.setPixmap(QtGui.QPixmap(icon)) if fan == 3: self.ui.labelStatusFan3.setPixmap(QtGui.QPixmap(icon)) if fan == 4: self.ui.labelStatusFan4.setPixmap(QtGui.QPixmap(icon)) if fan == 5: self.ui.labelStatusFan5.setPixmap(QtGui.QPixmap(icon)) if fan == 6: self.ui.labelStatusFan6.setPixmap(QtGui.QPixmap(icon)) def closeEvent(self, event): """Save UI settings and stops the running thread gracefully, then exit the application. Called when closing the application window. """ # Stop the running thread if self.thread.isRunning(): self.thread.stop() print("Thread stopped") # Save UI settings settings.save_settings(self.config, self.ui) print("Settings saved") # Hide tray icon self.trayIcon.hide() # Accept the closing event and close application event.accept() def changeEvent(self, event): if event.type() == QtCore.QEvent.WindowStateChange: if self.windowState() & QtCore.Qt.WindowMinimized: if self.ui.checkBoxMinimizeToTray.isChecked(): event.ignore() self.minimize_to_tray() else: self.show() event.accept() def toggle_visibility(self): if self.isVisible(): self.minimize_to_tray() else: self.restore_from_tray() def minimize_to_tray(self): self.hide() # self.trayIcon.show() def restore_from_tray(self): self.setWindowState(self.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) self.activateWindow() self.show()
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.mainwindow = Ui_MainWindow() self.mainwindow.setupUi(self) self.current_list = session.query(List).filter_by(name=u'Default').one() self.load_data() self.editor = Editor(self) self.editor.hide() logging.basicConfig(level=logging.DEBUG) def load_data(self): tasks = session.query(Task).filter_by(taskList=self.current_list) tv = self.mainwindow.treeView model = QStandardItemModel() model.setHorizontalHeaderLabels(['Task', 'Description', 'Date due']) for task in tasks: items = [] it = QStandardItem(QIcon('ui/priority-{0}.png'.format(task.priority)),task.title) it.setData(task.title, Qt.DisplayRole) it.task = task it.column_name = 'title' it.setCheckable(True) if task.completed: it.setCheckState(Qt.CheckState.Checked) else: it.setCheckState(Qt.CheckState.Unchecked) items.append(it) it = QStandardItem() it.setData(task.description, Qt.DisplayRole) it.task = task it.column_name = 'description' items.append(it) it = QStandardItem() it.setData(str(task.date_due), Qt.DisplayRole) it.task = task it.column_name = 'date_due' items.append(it) model.appendRow(items) tv.setModel(model) tv.sortByColumn(2, Qt.SortOrder.AscendingOrder) tv.setColumnWidth(0, 120) tv.setColumnWidth(1, 300) tv.setColumnWidth(2, 165) tv.setIndentation(0) model.dataChanged.connect(self.item_data_changed) tv.selectionModel().currentChanged.connect(self.task_selection_changed) self.mainwindow.actionDelete_Task.triggered.connect(self.delete_task_action) self.mainwindow.actionEdit_Task.triggered.connect(self.edit_task_action) self.mainwindow.actionNew_Task.triggered.connect(self.new_task_action) self.mainwindow.action_Exit.triggered.connect(self.exit_action) def item_data_changed(self, item): if item.column() == 0: print('Ignoring item_data_changed... column was 0') return item = self.mainwindow.treeView.model().itemFromIndex(self.mainwindow.treeView.currentIndex()) if item.checkState(): item.task.completed = True else: item.task.completed = False setattr(item.task, item.column_name, item.data(Qt.DisplayRole)) self.mainwindow.treeView.model().item(item.row(), 0).setIcon(QIcon('ui/priority-{0}.png'.format(item.task.priority))) session.commit() def delete_task_action(self,checked=None): idx = self.mainwindow.treeView.currentIndex() # First, get the 'current' task item = self.mainwindow.treeView.model().itemFromIndex(idx) # if none selected, do nothing if not item: logging.debug('No item selected, returning...') return # Delete the task item.task.delete() session.commit() self.mainwindow.treeView.model().removeRow(idx.row()) def new_task_action(self,checked=None): # Open the task in the editor self.editor.action = 'new_task' self.editor.edit(Task(taskList=self.current_list), self.mainwindow.treeView.model()) def number_of_tasks(self): return session.query(Task).count() def edit_task_action(self,checked=None): # Open the task in the editor self.editor.action = 'edit_task' currentItem = self.mainwindow.treeView.model().itemFromIndex(self.mainwindow.treeView.currentIndex()) self.editor.edit(currentItem.task, self.mainwindow.treeView.model()) def exit_action(self): sys.exit() def task_selection_changed(self, current, previous): self.mainwindow.actionDelete_Task.setEnabled(True if current else False)
class ControlMainWindow(QtGui.QMainWindow): updateFeedbackSignal = Signal(str) def __init__(self, app): super(ControlMainWindow, self).__init__(None) # self.settings = QtCore.QSettings("root_window") self.app = app self.post = Post(self) self.widgets = {} self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.statusbar.showMessage("Not connected") self.show() self.post.initSerialBridge() self.initUi() def initUi(self): self.ui.btn_close.clicked.connect(self.close) self.widgets["call"] = Call(self) self.ui.btn_call.clicked.connect(self.widgets["call"].show) self.widgets["import_csv"] = ImportCSV(self) self.ui.btn_import_csv.clicked.connect(self.widgets["import_csv"].show) self.widgets["received_sms"] = ReceivedSMS(self) self.ui.btn_show_sms.clicked.connect(self.widgets["received_sms"].show) self.widgets["sent_sms"] = SentSMS(self) self.ui.btn_sent_sms.clicked.connect(self.widgets["sent_sms"].show) self.widgets["send_sms"] = SendSMS(self) self.ui.btn_send_sms.clicked.connect(self.widgets["send_sms"].show) self.widgets["incoming_call"] = IncomingCall(self) self.widgets["incoming_sms"] = IncomingSMS(self) self.updateFeedbackSignal.connect(self.updateFeedback) # self.widgets["import_csv"].show() # self.widgets["incomding_sms"].show() def initSerialBridge(self): self.sb = SerialBridge() time.sleep(2.0) self.sb.send("AT") self.sb.trigger_words += [ "AT", "RING", "ATA", "ATH", "ATD", "CMT", "NO CARRIER" ] self.sb.callback = self.cbSim def cbSim(self, feedback): self.updateFeedbackSignal.emit(feedback) @Slot(str) def updateFeedback(self, feedback): print "got feedback" if feedback == "RING": self.widgets["incoming_call"].incomingCall() if feedback == "ATA": self.widgets["incoming_call"].callAnswered() if feedback == "ATH": self.widgets["incoming_call"].callStopped() self.widgets["call"].callStopped() if "ATD" in feedback: self.widgets["call"].callStarted() if "AT" == feedback: self.ui.statusbar.showMessage("Connected") if "CMT" in feedback: self.widgets["incoming_sms"].incomingSMS(feedback) # if "CMGR" in feedback: # self.widgets["incoming_sms"].messageContent(feedback) if "NO CARRIER" in feedback: self.widgets["incoming_call"].callStopped() def keyPressEvent(self, e): """Summary Args: e (TYPE): Description Returns: TYPE: Description """ #closes the window on escape if e.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): try: self.sb.close() except: pass for widget in self.widgets.values(): widget.close() super(ControlMainWindow, self).closeEvent(event)
class MyApplication(QtGui.QMainWindow): def __assign_displays(self): """assigns display name """ self.displays = CDisplay.detect_display_devices() self.no_of_displays = len(self.displays) self.no_of_connected_dev = self.no_of_displays if self.no_of_displays is 1: self.display1 = self.displays[0] elif self.no_of_displays is 2: self.display1 = self.displays[0] self.display2 = self.displays[1] def __init__(self, parent=None): """Initializes""" QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.display1 = None self.display2 = None self.temperature = 'Default' self.no_of_connected_dev = 0 self.__assign_displays() self.setup_default_directory() self.generate_dynamic_items() self.default_config = '/home/{}/.config/' \ 'brightness_controller/settings' \ .format(getpass.getuser()) self.values = [] self.array_value = 0.01 for i in xrange(0, 100): self.values.append(self.array_value) self.array_value += 0.01 self.connect_handlers() self.setup_widgets() if path.exists(self.default_config): self.load_settings(self.default_config) self.setup_tray(parent) def setup_default_directory(self): """ Create default settings directory if it doesnt exist """ directory = '/home/{}/.config/' \ 'brightness_controller/' \ .format(getpass.getuser()) if not path.exists(directory): try: makedirs(directory) except error as e: self._show_error(str(e)) def closeEvent(self, event): """ Override CloseEvent for system tray """ if self.isVisible() is True: self.hide() event.ignore() else: reply = QtGui.QMessageBox.question(self, 'Message', "Are you sure to quit?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() else: # fixes an odd event bug, the app never shows but prevents closing self.show() self.hide() event.ignore() def setup_tray(self, parent): """ Setup systemtray """ self.tray_menu = QtGui.QMenu(parent) self.tray_menu.addAction(QtGui.QAction("Show ...", self, statusTip="Show", triggered=self.show)) self.tray_menu.addAction(QtGui.QAction("Quit ...", self, statusTip="Quit", triggered=self.close)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("/usr/share/icons/hicolor/scalable/apps/brightness-controller.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.tray_icon = QtGui.QSystemTrayIcon(icon, self) if self.tray_icon.isSystemTrayAvailable(): self.tray_icon.connect( QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self._icon_activated) self.tray_icon.setContextMenu(self.tray_menu) self.tray_icon.show() def _icon_activated(self, reason): if reason in (QtGui.QSystemTrayIcon.Trigger, QtGui.QSystemTrayIcon.DoubleClick): self.show() def setup_widgets(self): """connects the form widgets with functions""" self.license_widget = LicenseForm() self.license_widget.set_main_window(self) self.license_widget.hide() self.about_widget = AboutForm() self.about_widget.set_main_window(self) self.about_widget.hide() self.help_widget = HelpForm() self.help_widget.set_main_window(self) self.help_widget.hide() def generate_dynamic_items(self): ''' manages widgets that may contain dynamic items. ''' self.generate_brightness_sources() def generate_brightness_sources(self): ''' generates assigns display sources to combo boxes ''' if self.no_of_connected_dev < 2: self.ui.secondary_combo.addItem("Disabled") self.ui.secondary_combo.setEnabled(False) self.ui.primary_combobox.addItem("Disabled") self.ui.primary_combobox.setEnabled(False) return for display in self.displays: self.ui.secondary_combo.addItem(display) self.ui.primary_combobox.addItem(display) def connect_handlers(self): """Connects the handlers of GUI widgets""" self.ui.primary_brightness.valueChanged[int].\ connect(self.change_value_pbr) self.ui.primary_red.valueChanged[int].\ connect(self.change_value_pr) self.ui.primary_blue.valueChanged[int].\ connect(self.change_value_pb) self.ui.primary_green.valueChanged[int].\ connect(self.change_value_pg) self.enable_secondary_widgets(False) if self.no_of_connected_dev >= 2: self.enable_secondary_widgets(True) self.connect_secondary_widgets() if path.exists(self.default_config): self.ui.actionClearDefault.setVisible(True) self.ui.actionClearDefault.triggered.connect(self.delete_default_settings) self.ui.actionDefault.triggered.connect(lambda: self.save_settings(True)) self.ui.comboBox.activated[str].connect(self.combo_activated) self.ui.primary_combobox.activated[ str].connect(self.primary_source_combo_activated) self.ui.secondary_combo.activated[ str].connect(self.secondary_source_combo_activated) self.ui.actionAbout.triggered.connect(self.show_about) self.ui.actionExit.triggered.connect(self.close) self.ui.actionHelp.triggered.connect(self.show_help) self.ui.actionLicense.triggered.connect(self.show_license) self.ui.actionSave.triggered.connect(self.save_settings) self.ui.actionLoad.triggered.connect(self.load_settings) def enable_secondary_widgets(self, boolean): """ boolean - assigns boolean value to setEnabled(boolean) """ self.ui.secondary_brightness.setEnabled(boolean) self.ui.secondary_blue.setEnabled(boolean) self.ui.secondary_red.setEnabled(boolean) self.ui.secondary_green.setEnabled(boolean) def connect_secondary_widgets(self): """ connects the secondary widgets with functions """ self.ui.secondary_brightness.valueChanged[int].\ connect(self.change_value_sbr) self.ui.secondary_red.valueChanged[int].\ connect(self.change_value_sr) self.ui.secondary_blue.valueChanged[int].\ connect(self.change_value_sb) self.ui.secondary_green.valueChanged[int].\ connect(self.change_value_sg) def change_value_pbr(self, value): """Changes Primary Display Brightness""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[value], self.values[self.ui.primary_red.value()], self.values[self.ui.primary_green.value()], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pr(self, value): """Changes Primary Display Red ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[value], self.values[self.ui.primary_green.value()], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pg(self, value): """Changes Primary Display Green ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[self.ui.primary_red.value()], self.values[value], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pb(self, value): """Changes Primary Display Blue ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[self.ui.primary_red.value()], self.values[self.ui.primary_green.value()], self.values[value]) Executor.execute_command(cmd_value) def change_value_sbr(self, value): """ Changes Secondary Display Brightness """ cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[value], self.values[self.ui.secondary_red.value()], self.values[self.ui.secondary_green.value()], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sr(self, value): """Changes Secondary Display Red ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[value], self.values[self.ui.secondary_green.value()], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sg(self, value): """Changes Secondary Display Green ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[self.ui.secondary_red.value()], self.values[value], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sb(self, value): """Changes Primary Display Blue ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[self.ui.secondary_red.value()], self.values[self.ui.secondary_green.value()], self.values[value]) Executor.execute_command(cmd_value) def changed_state(self, state): if state == QtCore.Qt.Checked: temp = self.display1 self.display1 = self.display2 self.display2 = temp else: temp = self.display1 self.display1 = self.display2 self.display2 = temp def secondary_source_combo_activated(self, text): ''' assigns combo value to display ''' self.display2 = text def primary_source_combo_activated(self, text): '''assigns combo value to display''' self.display1 = text def combo_activated(self, text): """ Designates values to display and to sliders """ self.temperature = text if text == 'Default': rgb = [255, 255, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '1900K Candle': rgb = [255, 147, 41] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '2600K 40W Tungsten': rgb = [255, 197, 143] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '2850K 100W Tungsten': rgb = [255, 214, 170] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '3200K Halogen': rgb = [255, 241, 224] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '5200K Carbon Arc': rgb = [255, 250, 244] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '5400K High Noon': rgb = [255, 255, 251] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '6000K Direct Sun': rgb = [255, 255, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '7000K Overcast Sky': rgb = [201, 226, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '20000K Clear Blue Sky': rgb = [64, 156, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) def change_primary_sliders(self, rgb): """ rgb - based on the rgb array, assign values to primary display sliders and in turn changes primary display color """ slider_r = int((rgb[0] * 100) / 255) slider_g = int((rgb[1] * 100) / 255) slider_b = int((rgb[2] * 100) / 255) self.ui.primary_red.setValue(slider_r) self.ui.primary_green.setValue(slider_g) self.ui.primary_blue.setValue(slider_b) def change_secondary_sliders(self, rgb): """ rgb - based on the rgb array, assign values to secondary display sliders and in turn changes secondary display color rgb is given in array from a range of 0 to 255 """ slider_r = int((rgb[0] * 100) / 255) slider_g = int((rgb[1] * 100) / 255) slider_b = int((rgb[2] * 100) / 255) self.ui.secondary_red.setValue(slider_r) self.ui.secondary_green.setValue(slider_g) self.ui.secondary_blue.setValue(slider_b) def change_secondary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for secondary monitor slider """ self.ui.secondary_brightness.setValue(br_rgb[0]) self.ui.secondary_red.setValue(br_rgb[1]) self.ui.secondary_green.setValue(br_rgb[2]) self.ui.secondary_blue.setValue(br_rgb[3]) def primary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for primary monitor sliders """ self.ui.primary_brightness.setValue(br_rgb[0]) self.ui.primary_red.setValue(br_rgb[1]) self.ui.primary_green.setValue(br_rgb[2]) self.ui.primary_blue.setValue(br_rgb[3]) def secondary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for primary monitor sliders """ self.ui.secondary_brightness.setValue(br_rgb[0]) self.ui.secondary_red.setValue(br_rgb[1]) self.ui.secondary_green.setValue(br_rgb[2]) self.ui.secondary_blue.setValue(br_rgb[3]) def show_about(self): """ Shows the About widget""" self.about_widget.show() def show_license(self): """ Shows the License widget""" self.license_widget.show() def show_help(self): """ Shows the Help Widget""" self.help_widget.show() def save_settings(self, default=False): """ save current primary and secondary display settings""" file_path = self.default_config if default else QtGui.QFileDialog.getSaveFileName()[0] # just a number. path.exists won't work in case it is a new file. if len(file_path) > 5: if default: self.ui.actionClearDefault.setVisible(True) if self.no_of_connected_dev == 1: WriteConfig.write_primary_display( self.return_current_primary_settings(), file_path ) elif self.no_of_connected_dev >= 2: WriteConfig.write_both_display( self.return_current_primary_settings(), self.return_current_secondary_settings(), file_path ) def _show_error(self, message): """ Shows an Error Message""" QtGui.QMessageBox.critical(self, 'Error', message) def delete_default_settings(self): """ delete default settings """ if path.exists(self.default_config): try: remove(self.default_config) self.ui.actionClearDefault.setVisible(False) except OSError as e: self._show_error(str(e)) else: return False def _load_temperature(self, text='Default'): """ Load current temperature settings """ self.temperature = text primary_temperature_index = self.ui.comboBox.findText( text, QtCore.Qt.MatchFixedString) if primary_temperature_index >= 0: self.ui.comboBox.setCurrentIndex(primary_temperature_index) def load_settings(self, location=None): """ Load current primary and secondary display settings """ file_path = location or QtGui.QFileDialog.getOpenFileName()[0] if path.exists(file_path): loaded_settings = ReadConfig.read_configuration(file_path) if len(loaded_settings) == 5: self._load_temperature(loaded_settings[4]) self.primary_sliders_in_rgb_0_99(loaded_settings) elif len(loaded_settings) == 11: # checks just in case saved settings are for two displays, # but loads when only one display is connected if self.no_of_connected_dev == 1: self.primary_sliders_in_rgb_0_99( (loaded_settings[0], loaded_settings[1], loaded_settings[2], loaded_settings[3])) return # sets reverse control primary_source = loaded_settings[4] secondary_source = loaded_settings[10] self._load_temperature(loaded_settings[5]) primary_combo_index = self.ui.primary_combobox.findText( primary_source, QtCore.Qt.MatchFixedString) second_combo_index = self.ui.secondary_combo.findText( secondary_source, QtCore.Qt.MatchFixedString) if primary_combo_index >= 0: self.ui.primary_combobox.setCurrentIndex(primary_combo_index) self.primary_source_combo_activated(primary_source) if second_combo_index >= 0: self.ui.secondary_combo.setCurrentIndex(second_combo_index) self.secondary_source_combo_activated(secondary_source) self.primary_sliders_in_rgb_0_99( (loaded_settings[0], loaded_settings[1], loaded_settings[2], loaded_settings[3])) # (99, 99, 99, 99, 'LVDS-1', 99, 38, 99, 99, 'VGA-1') self.secondary_sliders_in_rgb_0_99( (loaded_settings[6], loaded_settings[7], loaded_settings[8], loaded_settings[9])) def return_current_primary_settings(self): """ return p_br_rgb(primary_brightness, primary_red, primary_green, primary_blue) """ # p_br_rgb = [] p_br_rgb = [ self.ui.primary_brightness.value(), self.ui.primary_red.value(), self.ui.primary_green.value(), self.ui.primary_blue.value(), self.display1, self.temperature ] return p_br_rgb def return_current_secondary_settings(self): """ return s_br_rgb(secondary_brightness, secondary_red, secondary_green, secondary_blue) """ s_br_rgb = [ self.ui.secondary_brightness.value(), self.ui.secondary_red.value(), self.ui.secondary_green.value(), self.ui.secondary_blue.value(), self.display2 ] # s_br_rgb = [] # s_br_rgb.append(self.ui.secondary_brightness.value()) # s_br_rgb.append(self.ui.secondary_red.value()) # s_br_rgb.append(self.ui.secondary_green.value()) # s_br_rgb.append(self.ui.secondary_blue.value()) return s_br_rgb
class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Sets the system date as the reference and request date value. self.ui.dateEdit_startDate.setDate(QtCore.QDate.currentDate()) self.ui.dateEdit_mesDate.setDate((QtCore.QDate.currentDate())) # Button activate self.ui.button_calculate.clicked.connect(self.on_button_click) # Calculate Button def on_button_click(self): # Function variables # Read and reformat date from form mes_date = self.ui.dateEdit_mesDate.date().toString('dd.MM.yyyy') # Read start-value from form start_value = self.ui.doubleSpinBox_startValue.value() # Set requested date in output self.ui.label_date.setText(str(mes_date)) self.calc_activity() def calc_activity(self): # Function variables # Date format that is expected date_format = "%d.%m.%Y" # half-life Iodine 125 hwz = 59.49 n_zero = self.ui.doubleSpinBox_startValue.value() # conversion factor U to mCi u_to_mci = 1.2699 # Read and reformat date from form ref_date = self.ui.dateEdit_startDate.date().toString('dd.MM.yyyy') mes_date = self.ui.dateEdit_mesDate.date().toString('dd.MM.yyyy') ref_date_calc = datetime.strptime(ref_date, date_format) mes_date_calc = datetime.strptime(mes_date, date_format) # Read combo Box from form unit = self.ui.comboBox_mesUnit.currentText() # Calculating the date difference diff_date = (ref_date_calc - mes_date_calc).days # Calculate activity on requested date - Basis Unit n_t = round(n_zero * np.exp((np.log(2) / hwz) * diff_date), 4) mci_u_t = round((n_t / u_to_mci), 4) mbq_t = round((mci_u_t * 37), 4) # Calculate activity on requested date - Basis MBq mci_mbq_t = round((n_t / 37), 4) u_mbq_t = round((mci_mbq_t * u_to_mci), 4) # Calculate activity on requested date - Basis mCi u_mci_t = round((n_t * u_to_mci), 4) mbq_mci_t = round((n_t * 37), 4) # Output in the form if unit == "Unit": self.ui.label_resUnit.setText(str(n_t)) self.ui.label_resMBq.setText(str(mbq_t)) self.ui.label_resmCi.setText(str(mci_u_t)) elif unit == "MBq": self.ui.label_resUnit.setText(str(u_mbq_t)) self.ui.label_resMBq.setText(str(n_t)) self.ui.label_resmCi.setText(str(mci_mbq_t)) elif unit == "mCi": self.ui.label_resUnit.setText(str(u_mci_t)) self.ui.label_resMBq.setText(str(mbq_mci_t)) self.ui.label_resmCi.setText(str(n_t))
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.debs = {} self.parse_packages() self.list_components() self.list_installed_components() self.update_table() def list_components(self): components = subprocess.check_output( 'hr cmd list_components install'.split(' ')) components = components.splitlines() for component in ['head', 'head-deps', 'opencog', 'opencog-deps']: if component in components: components.remove(component) self.components = components def list_installed_components(self): installed_components = subprocess.check_output( 'hr cmd list_installed'.split(' ')) self.installed_components = installed_components.splitlines() def parse_packages(self): self.debs = {} package_file = os.path.join(CWD, 'Packages.gz') with gzip.open(package_file, 'rb') as f: content = f.read() packages = content.strip().split('\n\n') for package in packages: deb = deb822.Deb822(package) name = deb['Package'] self.debs[name] = deb def get_installed_versions(self, components): cmd = r"""dpkg-query -W -f='${Package} ${Status} ${Version}\n' """+' '.join(components) versions = subprocess.check_output(cmd, shell=True).splitlines() installed_versions = {} for v in versions: if 'installed' in v: toks = v.split() if len(toks) > 4: installed_versions[toks[0]] = toks[-1] return installed_versions def update_table(self): installed_versions = self.get_installed_versions(self.installed_components) self.ui.componentTableWidget.setColumnCount(5) self.ui.componentTableWidget.setRowCount(len(self.components)) self.ui.componentTableWidget.setColumnWidth(0, 30) self.ui.componentTableWidget.setColumnWidth(1, 300) self.ui.componentTableWidget.setColumnWidth(2, 120) self.ui.componentTableWidget.setColumnWidth(3, 120) self.ui.componentTableWidget.setHorizontalHeaderLabels( ['S', 'Package', 'Installed Version', 'Latest Version', 'Description']) for row, key in enumerate(self.components): status = QtGui.QTableWidgetItem() if key in self.installed_components: status.setCheckState(QtCore.Qt.Checked) else: status.setCheckState(QtCore.Qt.Unchecked) self.ui.componentTableWidget.setItem(row, 0, status) item = QtGui.QTableWidgetItem(key) self.ui.componentTableWidget.setItem(row, 1, item) if key in self.debs: if key in installed_versions: installed_version = QtGui.QTableWidgetItem(installed_versions[key]) self.ui.componentTableWidget.setItem(row, 2, installed_version) version = QtGui.QTableWidgetItem(self.debs[key]['Version']) self.ui.componentTableWidget.setItem(row, 3, version) desc = QtGui.QTableWidgetItem(self.debs[key]['Description']) self.ui.componentTableWidget.setItem(row, 4, desc)
class Example(QWidget): MAIN_WIDTH_NORMAL=500 MAIN_HEIGHT_NORMAL=350 resizeFlag =False def __init__(self): super(Example, self).__init__() # self.dbus_Thread = initThread() # self.dbus_Thread.start() # self.backend = self.dbus_Thread.backend self.backend = InstallBackend() self.backend.init_dbus_ifaces() self.InitUI() self.work = workThread(self.backend) self.messageBox = MessageBox(self) self.ui.btnClose.clicked.connect(self.slot_close) self.backend.dbus_apt_process.connect(self.slot_status_change) self.show_debfile(LOCAL_DEB_FILE) def InitUI(self): self.ui=Ui_MainWindow() self.ui.setupUi(self) self.ui.centralwidget.paintEvent=self.set_paintEvent self.ui.icon.setStyleSheet(".QWidget{background-color:transparent;background-image:url('res/no-download.png');border:1px solid red;border-radius:0px}") self.ui.btnClose.setStyleSheet("QPushButton{background-image:url('res/close-1.png');border:0px;}QPushButton:hover{background-image:url('res/close-2.png');background-color:#c75050;}QPushButton:pressed{background-image:url('res/close-2.png');background-color:#bb3c3c;}") def mousePressEvent(self, event): if(event.button() == Qt.LeftButton): self.clickx = event.globalPos().x() self.clicky = event.globalPos().y() self.dragPosition = event.globalPos() - self.frameGeometry().topLeft() event.accept() # #函数名: 窗口拖动事件 #Function: Window drag event # def mouseMoveEvent(self, event): if(event.buttons() == Qt.LeftButton): # resize if(self.resizeFlag == True): targetWidth = event.globalX() - self.frameGeometry().topLeft().x() targetHeight = event.globalY() - self.frameGeometry().topLeft().y() if(targetWidth < self.MAIN_HEIGHT_NORMAL): if(targetHeight < self.MAIN_HEIGHT_NORMAL): self.resize(self.MAIN_WIDTH_NORMAL, self.MAIN_HEIGHT_NORMAL) else: self.resize(self.MAIN_HEIGHT_NORMAL, targetHeight) else: if(targetHeight < self.MAIN_HEIGHT_NORMAL): self.resize(targetWidth, self.MAIN_HEIGHT_NORMAL) else: self.resize(targetWidth, targetHeight) event.accept() # drag move else: if(self.dragPosition != -1): self.move(event.globalPos() - self.dragPosition) event.accept() # #函数名:重绘窗口阴影 #Function: Redraw window shadow # def set_paintEvent(self, event): painter=QPainter (self.ui.centralwidget) m_defaultBackgroundColor = QColor(qRgb(192,192,192)) m_defaultBackgroundColor.setAlpha(50) path=QPainterPath() path.setFillRule(Qt.WindingFill) path.addRoundedRect(10, 10, self.ui.centralwidget.width() - 20, self.ui.centralwidget.height() - 20, 4, 4) painter.setRenderHint(QPainter.Antialiasing, True) painter.fillPath(path, QBrush(QColor(m_defaultBackgroundColor.red(), m_defaultBackgroundColor.green(), m_defaultBackgroundColor.blue()))) color=QColor(0, 0, 0, 20) i=0 while i<4: path=QPainterPath() path.setFillRule(Qt.WindingFill) path.addRoundedRect(10 - i, 10 - i,self.ui.centralwidget.width() - (10 - i) * 2, self.ui.centralwidget.height() - (10 - i) * 2, 6, 6) color.setAlpha(100 - math.sqrt(i) * 50) painter.setPen(color) painter.drawPath(path) i=i+1 painter.setRenderHint(QPainter.Antialiasing) # #函数:关闭软件&退出dbus # def slot_close(self): try: close_filelock() self.backend.exit() sys.exit(0) except Exception as e: print("kkk",e) # # 函数:安装软件 # def install_debfile(self): #self.start_dpkg() self.work.start() # # 函数:显示软件包状态 # def show_debfile(self,path): self.debfile = DebFile(path) self.ui.pkgname.setStyleSheet(".QLabel{background-color:transparent;border:0px;font-size:26px;color:#444444}") if path == '': # self.ui.pkgname.setText() text = get_icon.setLongTextToElideFormat(self.ui.pkgname, _("暂无可安装文件")) else: text = get_icon.setLongTextToElideFormat(self.ui.pkgname, _(str(self.debfile.name))) if str(text).endswith("…") is True: self.ui.pkgname.setToolTip(self.debfile.name) self.app = self.debfile iconpath = get_icon.get_icon_path(str(self.debfile.name)) if iconpath: self.ui.icon.setStyleSheet("QLabel{background-image:url('" + iconpath + "');background-color:transparent;}") if self.debfile.version: text = get_icon.setLongTextToElideFormat(self.ui.Version, "版本号: " + self.debfile.version) if str(text).endswith("…") is True: self.ui.Version.setToolTip(self.debfile.version) else: self.ui.Version.setText("版本号:暂无") self.ui.install.clicked.connect(self.install_debfile) # # 函数:接收后台信号修改包状态 # def slot_status_change(self, name, processtype, action, percent, msg): print(("####", name, " ", processtype, " ", action, " ", msg)) if action == AppActions.INSTALLDEBFILE: if processtype == "apt" and percent < 0: self.stop_dpkg() self.ui.status.hide() self.ui.loding.stop() self.ui.progressBar.hide() self.messageBox.alert_msg("安装失败") self.ui.install.show() app.percent = 0 elif processtype == "apt" and percent == 200: self.stop_dpkg() self.messageBox.alert_msg("安装完成") self.ui.install.setText("已安裝") self.ui.install.setStyleSheet("background-color:#999999") self.ui.install.setEnabled(False) app.percent = percent elif processtype == "cancel" and percent == 0: self.stop_dpkg() elif processtype == "ensure": self.start_dpkg() # # 函数:安装完成后,修改ui界面 # def stop_dpkg(self): self.ui.loding.stop() self.ui.status.hide() self.ui.progressBar.hide() self.ui.install.show() # # 函数:开始安装后,修改ui界面 # def start_dpkg(self): self.ui.status.show() self.ui.install.hide() self.ui.loding.start() self.ui.progressBar.show()
class MyApplication(QtGui.QMainWindow): def __assign_displays(self): """assigns display name """ displays = CDisplay.detect_display_devices() no_of_displays = len(displays) self.no_of_connected_dev = no_of_displays if no_of_displays == 1: self.display1 = displays[0] elif no_of_displays == 2: if True: self.display1 = displays[0] self.display2 = displays[1] else: self.display1 = displays[1] self.display2 = displays[0] def __init__(self, parent=None): """Initializes""" QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.display1 = None self.display2 = None self.no_of_connected_dev = 0 self.__assign_displays() self.values = [] self.array_value = 0.01 for i in xrange(0, 100): self.values.append(self.array_value) self.array_value += 0.01 self.connect_handlers() self.setup_widgets() def setup_widgets(self): """connects the form widgets with functions""" self.license_widget = LicenseForm() self.license_widget.set_main_window(self) self.license_widget.hide() self.about_widget = AboutForm() self.about_widget.set_main_window(self) self.about_widget.hide() self.help_widget = HelpForm() self.help_widget.set_main_window(self) self.help_widget.hide() def connect_handlers(self): """Connects the handlers of GUI widgets""" user_interface = self.ui user_interface.primary_brightness.valueChanged[int].\ connect(self.change_value_pbr) user_interface.primary_red.valueChanged[int].\ connect(self.change_value_pr) user_interface.primary_blue.valueChanged[int].\ connect(self.change_value_pb) user_interface.primary_green.valueChanged[int].\ connect(self.change_value_pg) self.enable_secondary_widgets(False) if self.no_of_connected_dev == 2: self.enable_secondary_widgets(True) self.connect_secondary_widgets() user_interface.comboBox.activated[str].connect(self.combo_activated) user_interface.actionAbout.triggered.connect(self.show_about) user_interface.actionExit.triggered.connect(self.close) user_interface.actionHelp.triggered.connect(self.show_help) user_interface.actionLicense.triggered.connect(self.show_license) user_interface.actionSave.triggered.connect(self.save_settings) user_interface.actionLoad.triggered.connect(self.load_settings) def enable_secondary_widgets(self, boolean): """ boolean - assigns boolean value to setEnabled(boolean) """ self.ui.checkBox.setEnabled(boolean) self.ui.secondary_brightness.setEnabled(boolean) self.ui.secondary_blue.setEnabled(boolean) self.ui.secondary_red.setEnabled(boolean) self.ui.secondary_green.setEnabled(boolean) def connect_secondary_widgets(self): """ connects the secondary widgets with functions """ self.ui.secondary_brightness.valueChanged[int].\ connect(self.change_value_sbr) self.ui.secondary_red.valueChanged[int].\ connect(self.change_value_sr) self.ui.secondary_blue.valueChanged[int].\ connect(self.change_value_sb) self.ui.secondary_green.valueChanged[int].\ connect(self.change_value_sg) self.ui.checkBox.stateChanged.connect(self.changed_state) def change_value_pbr(self, value): """Changes Primary Display Brightness""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[value], self.values[self.ui.primary_red.value()], self.values[self.ui.primary_green.value()], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pr(self, value): """Changes Primary Display Red ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[value], self.values[self.ui.primary_green.value()], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pg(self, value): """Changes Primary Display Green ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[self.ui.primary_red.value()], self.values[value], self.values[self.ui.primary_blue.value()]) Executor.execute_command(cmd_value) def change_value_pb(self, value): """Changes Primary Display Blue ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display1, self.values[self.ui.primary_brightness.value()], self.values[self.ui.primary_red.value()], self.values[self.ui.primary_green.value()], self.values[value]) Executor.execute_command(cmd_value) def change_value_sbr(self, value): """ Changes Secondary Display Brightness """ cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[value], self.values[self.ui.secondary_red.value()], self.values[self.ui.secondary_green.value()], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sr(self, value): """Changes Secondary Display Red ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[value], self.values[self.ui.secondary_green.value()], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sg(self, value): """Changes Secondary Display Green ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[self.ui.secondary_red.value()], self.values[value], self.values[self.ui.secondary_blue.value()]) Executor.execute_command(cmd_value) def change_value_sb(self, value): """Changes Primary Display Blue ratio""" cmd_value = "xrandr\ --output %s \ --brightness %s\ --gamma %s:%s:%s" % \ (self.display2, self.values[self.ui.secondary_brightness.value()], self.values[self.ui.secondary_red.value()], self.values[self.ui.secondary_green.value()], self.values[value]) Executor.execute_command(cmd_value) def changed_state(self, state): if state == QtCore.Qt.Checked: temp = self.display1 self.display1 = self.display2 self.display2 = temp else: temp = self.display1 self.display1 = self.display2 self.display2 = temp def combo_activated(self, text): """ Designates values to display and to sliders """ if text == 'Default': rgb = [255, 255, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '1900K Candle': rgb = [255, 147, 41] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '2600K 40W Tungsten': rgb = [255, 197, 143] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '2850K 100W Tungsten': rgb = [255, 214, 170] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '3200K Halogen': rgb = [255, 241, 224] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '5200K Carbon Arc': rgb = [255, 250, 244] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '5400K High Noon': rgb = [255, 255, 251] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '6000K Direct Sun': rgb = [255, 255, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '7000K Overcast Sky': rgb = [201, 226, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) elif text == '20000K Clear Blue Sky': rgb = [64, 156, 255] self.change_primary_sliders(rgb) if self.no_of_connected_dev == 2: self.change_secondary_sliders(rgb) def change_primary_sliders(self, rgb): """ rgb - based on the rgb array, assign values to primary display sliders and in turn changes primary display color """ slider_r = int((rgb[0] * 100) / 255) slider_g = int((rgb[1] * 100) / 255) slider_b = int((rgb[2] * 100) / 255) self.ui.primary_red.setValue(slider_r) self.ui.primary_green.setValue(slider_g) self.ui.primary_blue.setValue(slider_b) def change_secondary_sliders(self, rgb): """ rgb - based on the rgb array, assign values to secondary display sliders and in turn changes secondary display color rgb is given in array from a range of 0 to 255 """ slider_r = int((rgb[0] * 100) / 255) slider_g = int((rgb[1] * 100) / 255) slider_b = int((rgb[2] * 100) / 255) self.ui.secondary_red.setValue(slider_r) self.ui.secondary_green.setValue(slider_g) self.ui.secondary_blue.setValue(slider_b) def change_secondary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for secondary monitor slider """ self.ui.secondary_brightness.setValue(br_rgb[0]) self.ui.secondary_red.setValue(br_rgb[1]) self.ui.secondary_green.setValue(br_rgb[2]) self.ui.secondary_blue.setValue(br_rgb[3]) def primary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for primary monitor sliders """ self.ui.primary_brightness.setValue(br_rgb[0]) self.ui.primary_red.setValue(br_rgb[1]) self.ui.primary_green.setValue(br_rgb[2]) self.ui.primary_blue.setValue(br_rgb[3]) def secondary_sliders_in_rgb_0_99(self, br_rgb): """ change slider values in rgb from a range of 0 to 99 value for primary monitor sliders """ self.ui.secondary_brightness.setValue(br_rgb[0]) self.ui.secondary_red.setValue(br_rgb[1]) self.ui.secondary_green.setValue(br_rgb[2]) self.ui.secondary_blue.setValue(br_rgb[3]) def show_about(self): """ Shows the About widget""" self.about_widget.show() def show_license(self): """ Shows the License widget""" self.license_widget.show() def show_help(self): """ Shows the Help Widget""" self.help_widget.show() def save_settings(self): """ save current primary and secondary display settings""" file_path = QtGui.QFileDialog.getSaveFileName()[0] # just a number. path.exists won't work in case it is a new file. if len(file_path) > 5: if self.no_of_connected_dev == 1: WriteConfig.write_primary_display( self.return_current_primary_settings(), file_path ) elif self.no_of_connected_dev == 2: WriteConfig.write_both_display( self.return_current_primary_settings(), self.return_current_secondary_settings(), self.ui.checkBox.isChecked(), file_path ) def load_settings(self): """ Load current primary and secondary display settings """ file_path = QtGui.QFileDialog.getOpenFileName()[0] if path.exists(file_path): loaded_settings = ReadConfig.read_configuration(file_path) if len(loaded_settings) == 4: self.primary_sliders_in_rgb_0_99(loaded_settings) elif len(loaded_settings) == 9: # checks just in case saved settings are for two displays, # but loads when only one display is connected if self.no_of_connected_dev == 1: self.primary_sliders_in_rgb_0_99( (loaded_settings[0], loaded_settings[1], loaded_settings[2], loaded_settings[3])) return # sets reverse control self.ui.checkBox.setChecked(loaded_settings[8]) self.primary_sliders_in_rgb_0_99( (loaded_settings[0], loaded_settings[1], loaded_settings[2], loaded_settings[3])) self.secondary_sliders_in_rgb_0_99( (loaded_settings[4], loaded_settings[5], loaded_settings[6], loaded_settings[7])) def return_current_primary_settings(self): """ return p_br_rgb(primary_brightness, primary_red, primary_green, primary_blue) """ #p_br_rgb = [] p_br_rgb = [ self.ui.primary_brightness.value(), self.ui.primary_red.value(), self.ui.primary_green.value(), self.ui.primary_blue.value(), ] #p_br_rgb.append(self.ui.primary_brightness.value()) #p_br_rgb.append(self.ui.primary_red.value()) #p_br_rgb.append(self.ui.primary_green.value()) #p_br_rgb.append(self.ui.primary_blue.value()) return p_br_rgb def return_current_secondary_settings(self): """ return s_br_rgb(secondary_brightness, secondary_red, secondary_green, secondary_blue) """ s_br_rgb = [ self.ui.secondary_brightness.value(), self.ui.secondary_red.value(), self.ui.secondary_green.value(), self.ui.secondary_blue.value() ] #s_br_rgb = [] #s_br_rgb.append(self.ui.secondary_brightness.value()) #s_br_rgb.append(self.ui.secondary_red.value()) #s_br_rgb.append(self.ui.secondary_green.value()) #s_br_rgb.append(self.ui.secondary_blue.value()) return s_br_rgb