コード例 #1
0
ファイル: installpage.py プロジェクト: bjones1/enki
class InstallPage(QWidget):
    """Settings page for the installed plugins"""
    def __init__(self, parent, repo):
        """QWidget Dictionary -> Void
        Consumes the parent and the repository dictionary and sets up the
        install page in the settings area"""
        QWidget.__init__(self, parent)
        self._userPlugins = helper.getPlugins()
        self._repo = repo

        # Add a scrollArea that if they are more plugins that fit into the
        # settings page
        scrollArea = QScrollArea(self)
        scrollArea.setWidgetResizable(True)
        scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        baseLayout = QVBoxLayout()
        baseLayout.setAlignment(Qt.AlignTop)
        self.setLayout(baseLayout)
        baseWidget = QWidget()
        scrollArea.setWidget(baseWidget)
        baseLayout.addWidget(scrollArea)

        self._vbox = QVBoxLayout()
        baseWidget.setLayout(self._vbox)

    def update(self, userPlugins):
        """ListOfUserpluginEntry -> Void
        Consume a list of UserpluginEntry and repopulates the install page"""
        for i in reversed(range(self._vbox.count())):
            try:
                self._vbox.itemAt(i).widget().setParent(None)
            except AttributeError as e:
                qWarning("Can't call setParent of None type")

        labelText = "<h2>Install Plugins</h2>"
        if (len(self._repo["plugins"]) < 1):
            labelText += "<p>It seems we could not load the plugin repository.</p>"
            labelText += "<p style='color:red'>Make shure your internet connection is working and restart Enki.</p><p></p>"
        self._vbox.addWidget(QLabel(labelText))

        for entry in self._repo["plugins"]:
            isInstalled = helper.isPluginInstalled(entry["name"], userPlugins)
            if isInstalled:
                self._vbox.addWidget(pluginspage.PluginTitlecard(isInstalled))
            else:
                self._vbox.addWidget(InstallableTitlecard(entry, self))

    def addPluginToUserPlugins(self, installableTitlecard):
        """InstallableTitlecard -> Void
        Consumes an InstallableTitlecard and insert an PluginTitleCard instead
        of itself"""
        index = self._vbox.indexOf(installableTitlecard)
        name = installableTitlecard.modulename()
        pluginEntry = helper.initPlugin(name)

        if pluginEntry:
            self._userPlugins.append(pluginEntry)
            self._vbox.insertWidget(index,
                                    pluginspage.PluginTitlecard(pluginEntry))
コード例 #2
0
ファイル: pluginspage.py プロジェクト: hlamer/enki
class PluginsPage(QWidget):
    """Settings page for the installed plugins"""
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        # Add a scrollArea that if they are more plugins that fit into the
        # settings page
        scrollArea = QScrollArea(self)
        scrollArea.setWidgetResizable(True)
        scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        baseLayout = QVBoxLayout()
        self.setLayout(baseLayout)
        baseWidget = QWidget()
        scrollArea.setWidget(baseWidget)
        baseLayout.addWidget(scrollArea)

        self._vbox = QVBoxLayout()
        baseWidget.setLayout(self._vbox)

    def update(self, userPlugins):
        """ListOfUserpluginEntry -> Void
        Consume a list of UserpluginEntry and repopulates the plugins page"""
        for i in reversed(range(self._vbox.count())):
            try:
                self._vbox.itemAt(i).widget().setParent(None)
            except AttributeError as e:
                qWarning("Can't call setParent of None type")

        self._vbox.addWidget(QLabel(
            """<h2>Installed Plugins: <code>%i</code></h2>
            <p>Add plugins by putting them into <code>%s</code></p>
            <p></p>""" % (len(userPlugins), PLUGIN_DIR_PATH)))
        for entry in userPlugins:
            self._vbox.addWidget(PluginTitlecard(entry))

        self._vbox.addStretch(1)
コード例 #3
0
class StudentInfo(QGroupBox):
    '''
    编辑书本信息的界面
    传入{
        'sno': str,
        'sname': str,
        'dept': str,
        'majority': str,
        'max_book': int
    }
    返回{
        'sno': str,
        'sname': str,
        'password': str,
        'dept': str,
        'majority': str,
        'max_book': int
    }
    '''
    after_close = pyqtSignal(dict)

    def __init__(self, stu_info: dict):
        super().__init__()
        self.stu_info = stu_info

        self.title = QLabel()
        self.title.setText('学生信息')

        self.subTitle = QLabel()
        self.subTitle.setText('编辑学生信息')

        # 学号输入框
        self.SIDInput = QLineEdit()
        self.SIDInput.setFixedSize(400, 40)
        self.SIDInput.setText(self.stu_info['sno'])
        self.SIDInput.initText = '请输入学号'
        self.SIDInput.setEnabled(False)

        # 姓名输入框
        self.nameInput = QLineEdit()
        self.nameInput.setFixedSize(400, 40)
        self.nameInput.setText(self.stu_info['sname'])
        self.nameInput.initText = '请输入姓名'
        self.nameInput.setTextMargins(5, 5, 5, 5)
        self.nameInput.mousePressEvent = lambda x: self.inputClick(self.
                                                                   nameInput)

        # 密码
        self.passwordInput = QLineEdit()
        self.passwordInput.setFixedSize(400, 40)
        self.passwordInput.setText('请输入密码')
        self.passwordInput.initText = '请输入密码'
        self.passwordInput.setTextMargins(5, 5, 5, 5)
        self.passwordInput.mousePressEvent = lambda x: self.inputClick(
            self.passwordInput)

        # 重复密码
        self.repPasswordInput = QLineEdit()
        self.repPasswordInput.setFixedSize(400, 40)
        self.repPasswordInput.setText('请重复输入密码')
        self.repPasswordInput.initText = '请重复输入密码'
        self.repPasswordInput.setTextMargins(5, 5, 5, 5)
        self.repPasswordInput.mousePressEvent = lambda x: self.inputClick(
            self.repPasswordInput)

        # 最大借书数
        self.maxNumInput = QLineEdit()
        self.maxNumInput.setFixedSize(400, 40)
        self.maxNumInput.setText(str(self.stu_info['max_book']))
        self.maxNumInput.initText = '请输入最大借书数'
        self.maxNumInput.setTextMargins(5, 5, 5, 5)
        self.maxNumInput.mousePressEvent = lambda x: self.inputClick(
            self.maxNumInput)

        # 学院
        self.deptInput = QLineEdit()
        self.deptInput.setFixedSize(400, 40)
        self.deptInput.setText(self.stu_info['dept'])
        self.deptInput.initText = '请输入所在学院'
        self.deptInput.setTextMargins(5, 5, 5, 5)
        self.deptInput.mousePressEvent = lambda x: self.inputClick(self.
                                                                   deptInput)

        # 专业
        self.majorInput = QLineEdit()
        self.majorInput.setFixedSize(400, 40)
        self.majorInput.setText(self.stu_info['majority'])
        self.majorInput.initText = '请输入所在专业'
        self.majorInput.setTextMargins(5, 5, 5, 5)
        self.majorInput.mousePressEvent = lambda x: self.inputClick(self.
                                                                    majorInput)

        # 提交
        self.submit = QToolButton()
        self.submit.setText('提交')
        self.submit.setFixedSize(400, 40)
        self.submit.clicked.connect(self.submitFunction)

        # 退出
        self.back = QToolButton()
        self.back.setText('退出')
        self.back.setFixedSize(400, 40)
        self.back.clicked.connect(self.close)

        self.btnList = [
            self.SIDInput, self.nameInput, self.passwordInput,
            self.repPasswordInput, self.deptInput, self.majorInput,
            self.maxNumInput
        ]

        self.bodyLayout = QVBoxLayout()
        self.bodyLayout.addWidget(self.title)
        self.bodyLayout.addWidget(self.subTitle)
        for i in self.btnList:
            self.bodyLayout.addWidget(i)
        self.bodyLayout.addWidget(self.submit)
        self.bodyLayout.addWidget(self.back)

        self.setLayout(self.bodyLayout)
        self.initUI()

    def inputClick(self, e):
        for i in range(2, 9):
            item = self.bodyLayout.itemAt(i).widget()
            if item.text() == '':
                item.setText(item.initText)
                if item is self.passwordInput or item is self.repPasswordInput:
                    item.setEchoMode(QLineEdit.Normal)

        if e.text() == e.initText:
            e.setText('')
        if e is self.passwordInput or e is self.repPasswordInput:
            e.setEchoMode(QLineEdit.Password)

    def submitFunction(self):
        if not self.maxNumInput.text().isalnum():
            print('最大数量输入错误')
            return
        if self.passwordInput.text() != self.passwordInput.initText:
            if self.passwordInput.text() != self.repPasswordInput.text():
                msgBox = QMessageBox(QMessageBox.Warning, "错误!", '两次输入密码不一致!',
                                     QMessageBox.NoButton, self)
                msgBox.addButton("确认", QMessageBox.AcceptRole)
                msgBox.exec_()
                return
            self.stu_info['password'] = func.encrypt(self.passwordInput.text())
        self.stu_info['sname'] = self.nameInput.text()
        self.stu_info['dept'] = self.deptInput.text()
        self.stu_info['majority'] = self.majorInput.text()
        self.stu_info['max_book'] = int(self.maxNumInput.text())
        self.close()
        self.after_close.emit(self.stu_info)

    def initUI(self):
        self.setFixedSize(422, 500)
        self.setWindowTitle('编辑学生信息')
        self.setWindowIcon(QIcon('icon/person.png'))
        self.setMyStyle()

    def setMyStyle(self):
        self.setStyleSheet('''
        QWidget{
            background-color: white;
        }
        QLineEdit{
            border:0px;
            border-bottom: 1px solid rgba(229, 229, 229, 1);
            color: grey;
        }
        QToolButton{
            border: 0px;
            background-color:rgba(52, 118, 176, 1);
            color: white;
            font-size: 25px;
            font-family: 微软雅黑;
        }
        QGroupBox{
            border: 1px solid rgba(229, 229, 229, 1);
            border-radius: 5px;
        }
        ''')
        self.title.setStyleSheet('''
        *{
            color: rgba(113, 118, 121, 1);
            font-size: 30px;
            font-family: 微软雅黑;
        }
        ''')
        self.subTitle.setStyleSheet('''
        *{
            color: rgba(184, 184, 184, 1);
        }
        ''')
コード例 #4
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1280, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        self.menu_File = QtWidgets.QMenu(self.menubar)
        self.menu_File.setObjectName("menu_File")

        MainWindow.setMenuBar(self.menubar)

        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.action_Exit = QtWidgets.QAction(MainWindow)
        self.action_Exit.setObjectName("action_Exit")
        self.action_Exit.setStatusTip('Exit')
        self.actionOpenFile = QtWidgets.QAction(MainWindow)
        self.actionOpenFile.setObjectName("actionOpenFile")
        self.actionOpenFile.setStatusTip('Open new File')
        self.actionOpenDir = QtWidgets.QAction(MainWindow)
        self.actionOpenDir.setObjectName("actionOpenDir")
        self.actionOpenDir.setStatusTip('Open Directory')
        self.menu_File.addAction(self.actionOpenFile)
        self.menu_File.addAction(self.actionOpenDir)
        self.menu_File.addSeparator()
        self.menu_File.addAction(self.action_Exit)
        self.menubar.addAction(self.menu_File.menuAction())

        self.contentsWidget = QListWidget()
        self.contentsWidget.setViewMode(QListView.ViewMode.IconMode)
        self.contentsWidget.setIconSize(QSize(140, 140))  # add icon 2/6
        self.contentsWidget.setMovement(QListView.Movement.Static)  # add icon
        # self.contentsWidget.insertItem(0, 'Linked/Unlinked Bags')		# add icon
        # self.contentsWidget.insertItem(1, 'Simulation Tools')			# add icon
        self.contentsWidget.setMinimumWidth(160)
        self.contentsWidget.setMaximumWidth(160)
        self.contentsWidget.setSpacing(6)  # add icon
        # self.contentsWidget.setMaximumWidth(480)

        self.createIcons()  # add icon

        self.stack1 = QWidget()
        self.stack2 = QWidget()

        self.stack1UI()
        self.stack2UI()

        self.st = QStackedWidget(self.centralwidget)
        self.st.addWidget(self.stack1)
        self.st.addWidget(self.stack2)
        self.st.setMinimumWidth(640)
        self.st.setMinimumHeight(480)

        # print(self.size().width())  # tried to get mainwindow size

        hbox = QHBoxLayout(self.centralwidget)
        hbox.addWidget(self.contentsWidget)
        hbox.addWidget(self.st)
        hbox.setStretch(1, 100)

        self.centralwidget.setLayout(hbox)
        # self.statusbar = QMainWindow.statusBar(MainWindow)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.contentsWidget.currentRowChanged.connect(self.display)
        self.actionOpenFile.triggered.connect(self.openFile)
        self.actionOpenDir.triggered.connect(self.openDir)
        self.action_Exit.triggered.connect(self.exit)

        # self.createBar()

    def createIcons(self):  # add icon
        histIcon = QListWidgetItem(self.contentsWidget)
        histIcon.setIcon(QIcon("icon/hist-icon.jpg"))
        histIcon.setText("Histogram")
        histIcon.setTextAlignment(Qt.AlignHCenter)
        histIcon.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        simuIcon = QListWidgetItem(self.contentsWidget)
        simuIcon.setIcon(QIcon("icon/simul-icon.png"))
        simuIcon.setText("Simulation")
        simuIcon.setTextAlignment(Qt.AlignHCenter)
        simuIcon.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

    def createUnlinkedBar(self):
        max_count = 0
        unlinked_bag_list = []
        try:
            df = self.unlinked['Beam Diff'].dropna()
            # unlinked_bag_list = [-144, -12, 179, 322, 312]
            unlinked_bag_list = df.values.tolist()
        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        count = [0] * 4
        for num in unlinked_bag_list:
            if -1000 <= num and num <= -51:
                count[0] += 1
            elif -50 <= num and num <= -1:
                count[1] += 1
            elif 151 <= num and num <= 200:
                count[2] += 1
            elif 201 <= num:
                count[3] += 1

        # print(count)
        max_count = max(count)

        setBar = QBarSet('Beam Difference')
        setBar.append(count)

        series = QBarSeries()
        series.append(setBar)

        brush = QBrush(QColor(0xfdb157))
        pen = QPen(QColor(0xfdb157))
        pen.setWidth(2)
        setBar.setPen(pen)
        setBar.setBrush(brush)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.setTitle('Unlinked Bags Histogram')
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        labels = [
            'Not useful(-50 ~ -1000)', 'Pushed by operator',
            'Slipping on belt', 'Not useful >201'
        ]
        axisX = QBarCategoryAxis()
        axisX.append(labels)
        # chart.setAxisX(axisX, series)
        chart.addAxis(axisX, Qt.AlignBottom)
        # chart.ChartAreas[0].AxisX.LabelAutoFitStyle = LabelAutoFitStyle.WrodWrap
        series.attachAxis(axisX)

        axisY = QValueAxis()
        axisY.setRange(0, max_count + 1)
        # chart.setAxisY(axisY, series)
        chart.addAxis(axisY, Qt.AlignLeft)
        series.attachAxis(axisY)

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        # MainWindow.setCentralWidget(chartView)
        return chartView

    def createBar(self):
        print("in create bar")
        min_num, max_num = 0, 100
        max_count = 0
        linked_bag_list = []
        try:
            df = self.linked['Beam Diff'].dropna()
            # df = self.dp.linked['Beam Diff'].dropna()
            # print(df)
            linked_bag_list = df.values.tolist()
            min_num = int(min(linked_bag_list))
            # print(min_num)
            if min_num > 0:  # check if greater than 0, set to 0
                min_num = 0
            max_num = int(max(linked_bag_list))

            # print(max_count)
        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        count = linked_bag_list
        count = [0] * (max_num + 1
                       )  # choose the largest num as length of count

        for num in linked_bag_list:
            count[int(num)] += 1  # update every number's count

        max_count = max(count)

        setBar = QBarSet('Beam Difference')
        setBar.append(count)
        brush = QBrush(QColor(0x57B1FD))
        pen = QPen(QColor(0x57B1FD))
        pen.setWidth(2)
        setBar.setPen(pen)
        setBar.setBrush(brush)

        series = QBarSeries()
        series.append(setBar)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.setTitle('Linked Bags Histogram')
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        axisX = QValueAxis()
        axisX.setRange(min_num, max_num + 20)
        chart.setAxisX(axisX, series)

        axisY = QValueAxis()
        axisY.setRange(0, max_count + 20)
        chart.setAxisY(axisY, series)

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        # MainWindow.setCentralWidget(chartView)
        return chartView

    def createSummaryBar(self):
        # self.dp.dfinal

        series = QPieSeries()
        labelfont = QFont()
        labelfont.setPixelSize(11)
        try:
            series.append("Linked", len(self.linked.index))
            series.append("Unlinked", len(self.unlinked.index))
            # slices = QPieSlice()
            slices1 = series.slices()[1]
            slices1.setExploded()
            slices1.setLabelVisible()
            slices1.setPen(QPen(QColor(0x57B1FD), 2))
            slices1.setBrush(QBrush(QColor(0xfdb157)))
            slices1.setLabelPosition(QPieSlice.LabelOutside)
            slices1.setLabel(
                ("{0} {1:.2f}%").format("Unlinked",
                                        100 * slices1.percentage()))
            slices1.setLabelFont(labelfont)

            # slices.setPen(QPen(Qt.darkGreen, 2))
            # slices.setBrush(QBrush(QColor(0xfdb157)))
        except AttributeError:
            self.statusbar.showMessage('Data not ready')
            series.append("Total", 1)

        slices = series.slices()[0]

        slices.setBrush(QBrush(QColor(0x57B1FD)))
        # slices.setLabel(("%1%").format(100*slices.percentage(), 0, 'f', 1))
        # slices.setLabelPosition(QPieSlice.LabelInsideHorizontal)
        if len(series.slices()
               ) == 2:  # display "linked" label only at data was processed
            slices.setLabelVisible()
            slices.setLabel(("{0} {1:.2f}%").format("Linked",
                                                    100 * slices.percentage()))
            slices.setLabelFont(labelfont)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("Total")
        chart.legend().hide()

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        return chartView

    def getCertainRangeList(self, total_time_lst):
        self.ready_to_plot_lst = []
        self.range0To2 = []
        self.range2To3 = []
        self.range3To6 = []
        self.range6To9 = []
        self.range9To20 = []
        for item in total_time_lst:
            if 0 < item and item <= 2:
                # print("in 0-3: ", item)
                self.ready_to_plot_lst.append(int(item))
                self.range0To2.append(item)
            elif 2 < item and item <= 3:
                self.ready_to_plot_lst.append(int(item))
                self.range2To3.append(item)
            elif 3 < item and item <= 6:
                # print("in 3-6: ", item)
                self.ready_to_plot_lst.append(int(item))
                self.range3To6.append(item)
            elif 6 < item and item <= 9:
                # print("in 6-9: ", item)
                self.range6To9.append(item)
                self.ready_to_plot_lst.append(int(item))
            elif 9 < item and item <= 20:
                self.range9To20.append(item)

    def onClicked(self, b):  # try to add histogram radio button 2/11 12:02
        # self.removeWidgets()
        # self.layout.addWidget(self.createBar())
        if b.text() == "Histogram":
            print("histogram checkd!")
        elif b.text() == "RangeHist":
            print("range histogram")
        elif b.text() == "Pie Chart":
            print("pie chart")

    def stack1UI(self):
        self.layout = QVBoxLayout()
        combo = QComboBox(self.stack1)
        combo.addItem("Linked Bags")
        combo.addItem("Unlinked Bags")
        combo.addItem("Summary")

        radio = QRadioButton(
            "Histogram")  # try to add histogram radio button 2/11 12:02
        radio.setChecked(True)  # try to add histogram radio button 2/11 12:02
        radio.toggled.connect(lambda: self.onClicked(radio)
                              )  # try to add histogram radio button 2/11 12:02

        self.image = QtWidgets.QLabel(
            self.stack1)  # try to do stackwidget here 2/10 10:52
        self.image.setObjectName(
            "imageLabel")  # try to do stackwidget here 2/10 10:52
        # self.displaywidget = QtWidgets.QWidget(self.stack1)			# try to do stackwidget here 2/10 10:52
        # self.displaywidget.setObjectName("displaywidget")				# try to do stackwidget here 2/10 10:52

        # self.image.setText("image")
        # self.st1 = QStackedWidget(self.stack1)							# add stackwidget 2/10 10:52
        # self.st1.addWidget(self.createBar())
        # self.st1.addWidget(self.createUnlinkedBar())
        # self.st1.addWidget(self.createSummaryBar())

        self.layout.addWidget(combo)
        self.layout.addWidget(
            radio)  # add radio button to choose various charts 2/11 12:02
        self.layout.addWidget(self.image)  # add stackwidget 2/10 10:52
        # self.layout.addWidget(self.st1)									# add stackwidget 2/10 10:52
        # self.layout.addWidget(self.displaywidget)
        # self.layout.addWidget(self.createBar())

        self.stack1.setLayout(self.layout)

        combo.activated[str].connect(self.onActivated)

    def stack2UI(self):
        self.vlayout = QVBoxLayout()
        hlayout = QHBoxLayout()

        combo1 = QComboBox(self.stack2)
        combo1.addItem("Distribution")
        combo1.addItem("Occurrence")
        combo1.addItem("Summary")

        label = QLabel()
        label.setText("Delay: ")
        self.text = QLineEdit()
        button = QPushButton("Go")

        hlayout.addWidget(combo1)
        hlayout.addWidget(label)
        hlayout.addWidget(self.text)
        hlayout.addWidget(button)

        self.slayout = QHBoxLayout()

        self.labelDelay = QtWidgets.QWidget(self.stack2)
        self.labelafterDelay = QtWidgets.QWidget(
            self.stack2)  # try to add a paralel widget (before / after)
        self.labelDelay.setObjectName("result")

        self.labelafterDelay.setObjectName(
            "delayResult")  # try to add a paralel widget (before / after)
        # self.labelDelay.setText("before")
        # self.labelafterDelay.setText("after")						# try to add a paralel widget (before / after)

        self.slayout.addWidget(self.labelDelay)
        self.slayout.addWidget(self.labelafterDelay)

        self.vlayout.addLayout(hlayout)
        # self.vlayout.addWidget(self.labelDelay)
        # self.vlayout.addWidget(self.labelafterDelay)
        self.vlayout.addLayout(self.slayout)
        # vlayout.addWidget(self.beforeDelay())
        self.stack2.setLayout(self.vlayout)

        button.clicked.connect(self.simulate)
        combo1.activated[str].connect(self.onActivated1)

    def afterDelayPieChart(self):
        series = QPieSeries()
        labelfont = QFont()
        labelfont.setPixelSize(11)
        try:
            series.append("Run", sum(self.tm.total_running_after_delay))
            series.append("Stop", sum(self.tm.total_stopped_after_delay))
            # slices = QPieSlice()
            slices1 = series.slices()[1]
            slices1.setExploded()
            slices1.setLabelVisible()
            slices1.setPen(QPen(QColor(0x57B1FD), 2))
            slices1.setBrush(QBrush(QColor(0xfdb157)))
            slices1.setLabelPosition(QPieSlice.LabelOutside)
            slices1.setLabel(
                ("{0} {1:.2f}%").format("Stop", 100 * slices1.percentage()))
            slices1.setLabelFont(labelfont)

            # slices.setPen(QPen(Qt.darkGreen, 2))
            # slices.setBrush(QBrush(QColor(0xfdb157)))
        except AttributeError:
            self.statusbar.showMessage('Data not ready')
            series.append("Total", 1)

        slices = series.slices()[0]

        slices.setBrush(QBrush(QColor(0x57B1FD)))
        # slices.setLabel(("%1%").format(100*slices.percentage(), 0, 'f', 1))
        # slices.setLabelPosition(QPieSlice.LabelInsideHorizontal)
        if len(series.slices()
               ) == 2:  # display "linked" label only at data was processed
            slices.setLabelVisible()
            slices.setLabel(("{0} {1:.2f}%").format("Run",
                                                    100 * slices.percentage()))
            slices.setLabelFont(labelfont)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("Total")
        chart.legend().hide()

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        return chartView

    def afterDelay(self):
        print("in after delay bar")
        min_num, max_num = 0, 100
        max_count = 0
        total_stopped_after_delay = []
        try:
            total_stopped_after_delay = self.tm.total_stopped_after_delay
            max_num = max(total_stopped_after_delay)
        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        count = total_stopped_after_delay
        count = [0] * (int(max_num) + 1
                       )  # choose the largest num as length of count

        for num in total_stopped_after_delay:
            count[int(num)] += 1  # update every number's count

        max_count = max(count)
        print(len(total_stopped_after_delay), max_count)
        setBar = QBarSet('stop time')
        setBar.append(count)
        brush = QBrush(QColor(0x57B1FD))
        pen = QPen(QColor(0x57B1FD))
        pen.setWidth(2)
        setBar.setPen(pen)
        setBar.setBrush(brush)

        series = QBarSeries()
        series.append(setBar)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.setTitle('Stop time Histogram (after)')
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        axisX = QValueAxis()
        axisX.setRange(min_num, max_num + 20)
        chart.setAxisX(axisX, series)

        axisY = QValueAxis()
        axisY.setRange(0, max_count + 20)
        chart.setAxisY(axisY, series)

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        # MainWindow.setCentralWidget(chartView)
        return chartView

    def afterDelayDistribution(self):
        min_num, max_num = 0, 100
        max_count = 0
        total_stopped_after_delay = []
        try:
            total_stopped_after_delay = self.tm.total_stopped_after_delay
            max_num = max(total_stopped_after_delay)
        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        count = total_stopped_after_delay
        # count = [0] * (int(max_num) + 1)        # choose the largest num as length of count

        # for num in total_stopped_after_delay:
        #     count[int(num)] += 1            # update every number's count

        max_count = max(count)
        # print(len(total_stopped_after_delay), max_count)
        setBar = QBarSet('stop time')
        setBar.append(count)
        brush = QBrush(QColor(0x57B1FD))
        pen = QPen(QColor(0x57B1FD))
        pen.setWidth(2)
        setBar.setPen(pen)
        setBar.setBrush(brush)

        series = QBarSeries()
        series.append(setBar)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.setTitle('Stop time Distribution (after)')
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        axisX = QValueAxis()
        axisX.setRange(min_num, max_num + 20)
        chart.setAxisX(axisX, series)

        axisY = QValueAxis()
        axisY.setRange(0, max_count + 20)
        chart.setAxisY(axisY, series)

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        # MainWindow.setCentralWidget(chartView)
        return chartView

    def beforeDelayPieChart(self):
        series = QPieSeries()
        labelfont = QFont()
        labelfont.setPixelSize(11)
        try:
            series.append("Run", sum(self.tm.total_running_time))
            series.append("Stop", sum(self.tm.total_stopped_time))
            # slices = QPieSlice()
            slices1 = series.slices()[1]
            slices1.setExploded()
            slices1.setLabelVisible()
            slices1.setPen(QPen(QColor(0x57B1FD), 2))
            slices1.setBrush(QBrush(QColor(0xfdb157)))
            slices1.setLabelPosition(QPieSlice.LabelOutside)
            slices1.setLabel(
                ("{0} {1:.2f}%").format("Stop", 100 * slices1.percentage()))
            slices1.setLabelFont(labelfont)

            # slices.setPen(QPen(Qt.darkGreen, 2))
            # slices.setBrush(QBrush(QColor(0xfdb157)))
        except AttributeError:
            self.statusbar.showMessage('Data not ready')
            series.append("Total", 1)

        slices = series.slices()[0]

        slices.setBrush(QBrush(QColor(0x57B1FD)))
        # slices.setLabel(("%1%").format(100*slices.percentage(), 0, 'f', 1))
        # slices.setLabelPosition(QPieSlice.LabelInsideHorizontal)
        if len(series.slices()
               ) == 2:  # display "linked" label only at data was processed
            slices.setLabelVisible()
            slices.setLabel(("{0} {1:.2f}%").format("Run",
                                                    100 * slices.percentage()))
            slices.setLabelFont(labelfont)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("Total")
        chart.legend().hide()

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        return chartView

    def beforeDelay(self):
        print("in before delay bar")
        min_num, max_num = 0, 100
        max_count = 0
        total_stopped_time = []
        try:
            total_stopped_time = self.tm.total_stopped_time
            max_num = max(total_stopped_time)
        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        count = total_stopped_time
        count = [0] * (int(max_num) + 1
                       )  # choose the largest num as length of count

        for num in total_stopped_time:
            count[int(num)] += 1  # update every number's count

        max_count = max(count)
        print(len(total_stopped_time), max_count)
        setBar = QBarSet('stop time')
        setBar.append(count)
        brush = QBrush(QColor(0x57B1FD))
        pen = QPen(QColor(0x57B1FD))
        pen.setWidth(2)
        setBar.setPen(pen)
        setBar.setBrush(brush)

        series = QBarSeries()
        series.append(setBar)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.setTitle('Stop time Histogram (before)')
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        axisX = QValueAxis()
        axisX.setRange(min_num, max_num + 20)
        chart.setAxisX(axisX, series)

        axisY = QValueAxis()
        axisY.setRange(0, max_count + 20)
        chart.setAxisY(axisY, series)

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        # MainWindow.setCentralWidget(chartView)
        return chartView

    def beforeDelayDistribution(self):
        min_num, max_num = 0, 100
        max_count = 0
        total_stopped_time = []
        try:
            total_stopped_time = self.tm.total_stopped_time
            max_num = max(total_stopped_time)
        except AttributeError:
            self.statusbar.showMessage('Data not ready')

        count = total_stopped_time
        # count = [0] * (int(max_num) + 1)        # choose the largest num as length of count

        # for num in total_stopped_time:
        #     count[int(num)] += 1            # update every number's count

        max_count = max(count)
        setBar = QBarSet('stop time')
        setBar.append(count)
        brush = QBrush(QColor(0x57B1FD))
        pen = QPen(QColor(0x57B1FD))
        pen.setWidth(2)
        setBar.setPen(pen)
        setBar.setBrush(brush)

        series = QBarSeries()
        series.append(setBar)

        chart = QChart()
        font = QFont()
        font.setPixelSize(18)
        chart.setTitleFont(font)

        chart.setTitle('Stop time Distribution (before)')
        chart.addSeries(series)
        chart.setAnimationOptions(QChart.SeriesAnimations)

        axisX = QValueAxis()
        axisX.setRange(min_num, max_num + 20)
        chart.setAxisX(axisX, series)

        axisY = QValueAxis()
        axisY.setRange(0, max_count + 20)
        chart.setAxisY(axisY, series)

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartView = QChartView(chart)
        chartView.setRenderHint(QPainter.Antialiasing)

        # MainWindow.setCentralWidget(chartView)
        return chartView

    def display(self, i):
        self.st.setCurrentIndex(i)

    # mainMenu components
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        # self.getSummaryBtn.setText(_translate("MainWindow", "Push for Summary"))
        # self.image.setText(_translate("MainWindow", "ImageLabel"))
        # self.labelDelay.setText(_translate("MainWindow", "DelayLabel"))
        self.menu_File.setTitle(_translate("MainWindow", "&File"))
        self.action_Exit.setText(_translate("MainWindow", "&Exit"))
        self.actionOpenFile.setText(
            _translate("MainWindow", "&Open File/Files"))
        self.actionOpenDir.setText(_translate("MainWindow", "&Open Folder"))

    def removeWidgets(self):
        for i in reversed(range(3, self.layout.count())
                          ):  # change 2 to 3 if add another widget(radio)
            self.layout.itemAt(i).widget().setParent(None)

    def onActivated1(self, text):
        if text == 'Distribution':
            self.removeWidgets1()
            self.slayout.addWidget(self.beforeDelayDistribution(),
                                   QtCore.Qt.AlignLeft)
            self.slayout.addWidget(self.afterDelayDistribution(),
                                   QtCore.Qt.AlignLeft)
        elif text == 'Occurrence':
            self.removeWidgets1()
            self.slayout.addWidget(self.beforeDelay(), QtCore.Qt.AlignLeft)
            self.slayout.addWidget(self.afterDelay(), QtCore.Qt.AlignLeft)
        elif text == 'Summary':
            self.removeWidgets1()
            self.slayout.addWidget(self.beforeDelayPieChart(),
                                   QtCore.Qt.AlignLeft)
            self.slayout.addWidget(self.afterDelayPieChart(),
                                   QtCore.Qt.AlignLeft)

    # combo box items
    def onActivated(self, text):
        print(text)
        if text == 'Linked Bags':
            # self.image.setPixmap(QtGui.QPixmap('link.png'))
            # self.createBar()
            # self.st1.setCurrentIndex(0)
            # self.st1.removeWidget(self.createBar())
            # self.st1.insertWidget(0, self.createBar())
            self.removeWidgets()
            self.layout.addWidget(self.createBar())
        elif text == 'Unlinked Bags':
            # self.image.setPixmap(QtGui.QPixmap('unlink.png'))
            # self.st1.setCurrentIndex(1)
            self.removeWidgets()
            self.layout.addWidget(self.createUnlinkedBar())
        elif text == 'Summary':
            # self.image.setPixmap(QtGui.QPixmap('his.png'))
            # self.st1.setCurrentIndex(2)
            self.removeWidgets()
            self.layout.addWidget(self.createSummaryBar())

    def simulate(self):
        print(self.text.text())
        if bool(re.match('^[0-9]+$', self.text.text())):
            self.tm = TimeMeasure('runtime_.txt', int(self.text.text(
            )))  # change variables to global value 2/11 2:06
            self.tm.getDuration()
            self.tm.runList("")
            self.tm.stopList("")
            self.total_time = self.tm.org_finish_time - self.tm.org_start_time

            # self.labelDelay.setText("Simulation Result:\n")
            # self.labelDelay.setText(self.labelDelay.text() + "\n---------------Before delay---------------\n\n")
            # self.labelDelay.setText(self.labelDelay.text() + "Run Time total: {0:d} Sum: {1:f} seconds Percentage: {2:.2f}%\n".format(len(self.tm.total_running_time), sum(self.tm.total_running_time), sum(self.tm.total_running_time)/self.total_time * 100))
            # self.labelDelay.setText(self.labelDelay.text() + "Stop Time total: {0:d} Sum: {1:f} seconds Percentage: {2:.2f}%\n".format(len(self.tm.total_stopped_time), sum(self.tm.total_stopped_time), sum(self.tm.total_stopped_time)/self.total_time * 100))
            # self.labelDelay.setText(self.labelDelay.text() + "Total: {0:f} seconds Percentage: {1:.2f}%\n".format(self.total_time, sum(self.tm.total_running_time)/self.total_time * 100 + sum(self.tm.total_stopped_time)/self.total_time * 100))
            # # print("run:",len(tm.total_running_time), "sum:", sum(tm.total_running_time),"percentage:",sum(tm.total_running_time)/total_time * 100)
            # # print("stop:",len(tm.total_stopped_time), "sum:", sum(tm.total_stopped_time),"percentage:",sum(tm.total_stopped_time)/total_time * 100)
            # # print("total:",total_time, sum(tm.total_running_time)/total_time * 100 + sum(tm.total_stopped_time)/total_time * 100)
            # # print("\n---------------Add delay 2 seconds---------------\n")
            # self.labelDelay.setText(self.labelDelay.text() + "\n---------------Add delay 2 seconds---------------\n\n")
            self.tm.runListDelay("")
            self.tm.stopListDelay("")
            # self.total_time_after_delay = self.tm.delay_finish_time - self.tm.delay_start_time
            # self.labelDelay.setText(self.labelDelay.text() + "Run time after delay: {0:d} Sum: {1:f} seconds Percentage: {2:.2f}%\n".format(len(self.tm.total_running_after_delay), sum(self.tm.total_running_after_delay), sum(self.tm.total_running_after_delay) / self.total_time_after_delay * 100))
            # self.labelDelay.setText(self.labelDelay.text() + "Stop time after delay: {0:d} Sum: {1:f} seconds Percentage: {2:.2f}%\n".format(len(self.tm.total_stopped_after_delay), sum(self.tm.total_stopped_after_delay), sum(self.tm.total_stopped_after_delay) / self.total_time_after_delay * 100))
            # self.labelDelay.setText(self.labelDelay.text() + "Total: {0:f} seconds Percentage: {1:.2f}%\n".format(self.total_time_after_delay, sum(self.tm.total_running_after_delay) / self.total_time_after_delay * 100 + sum(self.tm.total_stopped_after_delay) / self.total_time_after_delay * 100))
            # # print("run after delay:", len(tm.total_running_after_delay), "sum:", sum(tm.total_running_after_delay), "percentage:",sum(tm.total_running_after_delay) / total_time_after_delay * 100)
            # # print("stop after delay:",len(tm.total_stopped_after_delay), "sum:", sum(tm.total_stopped_after_delay), "percentage:",sum(tm.total_stopped_after_delay) / total_time_after_delay * 100)
            # # print("total:",total_time_after_delay, sum(tm.total_running_after_delay) / total_time_after_delay * 100 + sum(tm.total_stopped_after_delay) / total_time_after_delay * 100)

            # self.tm.fakestopList()
            # self.delaylist = self.tm.getCertainRangeList(self.tm.fake_total_stopped_time)
            # # print("\nSummary:")
            # # print("Before delay XRAY_MIN / total: 100% ----> After delay XRAY_MIN / total: {0:.2f}%".format((len(tm.fake_total_stopped_time)-len(delaylist))/len(tm.fake_total_stopped_time)*100))
            # # print("Before delay total time: 100% ----> After delay total time: {0:.2f}%".format(total_time_after_delay/total_time*100))
            # self.labelDelay.setText(self.labelDelay.text() + "\nSummary:")
            # self.labelDelay.setText(self.labelDelay.text() + "Before delay total time: 100% ----> After delay total time: {0:.2f}%\n".format(self.total_time_after_delay/self.total_time*100))
            # self.labelDelay.setText(self.labelDelay.text() + "Before delay XRAY_MIN / total: 100% ----> After delay XRAY_MIN / total: {0:.2f}%".format((len(self.tm.fake_total_stopped_time)-len(self.delaylist))/len(self.tm.fake_total_stopped_time)*100))
            # self.labelDelay.setFont(QtGui.QFont("Times", 12, QtGui.QFont.Bold))
            # self.labelDelay.setAlignment(Qt.AlignTop)#HCenter)

            self.removeWidgets1()
            # self.vlayout.addWidget(self.beforeDelay())
            self.slayout.addWidget(self.beforeDelay(), QtCore.Qt.AlignLeft)
            # self.vlayout.addWidget(self.afterDelayPieChart())
            # self.vlayout.addWidget(self.afterDelay())
            self.slayout.addWidget(self.afterDelay(), QtCore.Qt.AlignLeft)

    def removeWidgets1(self):
        for i in reversed(range(2, self.slayout.count())
                          ):  # change 2 to 3 if add another widget(radio)
            self.slayout.itemAt(i).widget().setParent(None)

    # display summary label
    def setSummary(self):
        self.image.setPixmap(QtGui.QPixmap('his.png'))

    # display linked bags histogram
    def setLinkedHistogram(self):
        # pixmap = pixmap.tmaled(self.label.width(), self.label.height(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)	# make image unclear
        self.image.setPixmap(QtGui.QPixmap('link.png'))

    # display unlinked bags histogram
    def setUnlinkedHistogram(self):
        self.image.setPixmap(QtGui.QPixmap('unlink.png'))

    # display time stopped histogram
    def setTimeStoppedHistogram(self):
        self.image.setPixmap(QtGui.QPixmap('stop_time_distribution.png'))

    # display time running histogram
    def setTimeRunningHistogram(self):
        self.image.setPixmap(QtGui.QPixmap('running_time_distribution'))

    # open file dialog
    def openFile(self):
        filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(
            None, "QFileDialog.getOpenFileNames()", "",
            "All Files (*);;Log Files (*.log);;")
        if filenames:
            print("inside:", filenames)
        print("fdsfs", filenames)

        illegal = False
        suf = 'log'  # test for single .txt first, need to modify for final version
        if len(filenames) != 0:
            for f in filenames:  # check all files are illegal in here
                suffix = f[f.rfind('.') + 1:]
                if suffix != suf:
                    print("Illegal selection")
                    illegal = True
            print(illegal)
            if illegal:
                self.showdialog(illegal, True)
            else:
                # self.statusbar.showMessage('Processing Files...')
                pp = PreProc(filenames)  # pass files into PreProc class
                # self.statusbar.showMessage('Analyzing datas...')
                dp = DataProc()  # pass the prepared data into DataProc class
                self.linked = dp.linked
                self.unlinked = dp.unlinked
                self.statusbar.showMessage('Done')
                self.removeWidgets()
                self.layout.addWidget(self.createBar())
                # dp.getDiffHistogram(dp.linked)
                # self.image.setPixmap(QtGui.QPixmap('his.png'))

    # open directory dialog
    def openDir(self):
        dialog = QtWidgets.QFileDialog()
        dialog.setFileMode(QFileDialog.DirectoryOnly)

        dic_file = []
        if dialog.exec_():  # == QtGui.QDialog.Accepted:
            dic_file = dialog.selectedFiles()
        print("openDir: (dic_file) ", dic_file)

        log_file = []
        has_log = False
        suf = 'log'
        if dic_file:
            for f in os.listdir(dic_file[0]):
                #         print(f)
                suffix = f[f.rfind('.') + 1:]
                name = f[:f.rfind('.')]
                print(name)
                if suffix == suf:
                    has_log = True
                    if "AnalogicStandaloneType" in name:  # if match AnalogicStandaloneType*.log, append to log_file
                        log_file += dic_file[0] + "/" + f,
            print(has_log, log_file)
            if not has_log:
                self.showdialog(False, has_log)
            if len(log_file) == 0 and has_log:
                self.showdialog(False, False)
            if len(log_file) != 0:
                pp = PreProc(log_file)  # pass files into PreProc class
                self.dp = DataProc(
                )  # pass the prepared data into DataProc class
                self.statusbar.showMessage('Done')
                # dp.getDiffHistogram(dp.linked)
                # self.image.setPixmap(QtGui.QPixmap('his.png'))

    # pop up warning window
    def showdialog(self, illegal_file, has_log):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        if not has_log:
            msg.setText("No log files found.")
        if illegal_file:
            print("in illegal")
            msg.setText("Invalid log files detected.")

        msg.setWindowTitle("Something's wrong")
        # msg.setGeometry(200, 200, 300, 400) # need to change if need this line
        msg.setStandardButtons(QMessageBox.Ok)

        retval = msg.exec_()

    def exit(self):
        sys.exit(app.exec_())
コード例 #5
0
ファイル: menuview.py プロジェクト: canard0328/malss
class MenuView(QScrollArea):

    def __init__(self, parent=None, update_func=None, params=None):
        super().__init__(parent)

        self.setMaximumWidth(200)

        self.params = params

        self.H1_HEIGHT = 50
        self.H2_HEIGHT = 50
        self.SIDE_MARGIN = 5
        self.H1_FONT_SIZE = 18
        self.H2_FONT_SIZE = 18
        self.H3_FONT_SIZE = 16
        self.TEXT_FONT_SIZE = 14

        style = '''
            QPushButton:flat{
                text-align: left;
                padding: 1ex;
            }
            QPushButton:pressed{
                background-color: silver;
            }
            QPushButton:hover:!pressed{
                font: bold;
            }
            '''
        self.setStyleSheet(style)

        self.update_func = update_func

        self.inner = QWidget(self)

        self.vbox = QVBoxLayout(self.inner)
        self.vbox.setSpacing(0)
        self.vbox.setContentsMargins(0, 0, 0, 0)
        self.vbox.setAlignment(Qt.AlignTop)

        topframe = QFrame()
        topframe.setStyleSheet('background-color: white')
        topframe.setFixedHeight(self.H1_HEIGHT)

        lbl_h1 = QLabel('Contents', topframe)
        fnt = lbl_h1.font()
        fnt.setPointSize(self.H1_FONT_SIZE)
        lbl_h1.setFont(fnt)
        lbl_h1.setFixedHeight(self.H1_HEIGHT)
        lbl_h1.setMargin(self.SIDE_MARGIN)

        self.vbox.addWidget(topframe)

        self.list_button = []
        if self.params.lang == 'en':
            self.edit_button('Introduction')
        else:
            self.edit_button('はじめに')

        self.inner.setLayout(self.vbox)

        self.setWidget(self.inner)

    def buttonClicked(self, text):
        if self.update_func is not None:
            self.update_func(text)

    def edit_button(self, text, delete=False):
        if delete:
            for i in range(self.vbox.count()):
                widget = self.vbox.itemAt(i).widget()
                if type(widget) == QPushButton:
                    if widget.text() == '-' + text:
                        self.vbox.removeWidget(widget)
                        widget.deleteLater()
                        widget = None
            return

        if text not in self.list_button:
            self.list_button.append(text)
            btn = QPushButton('-' + text, self.inner)
            btn.setFlat(True)
            fnt = btn.font()
            fnt.setPointSize(self.TEXT_FONT_SIZE)
            btn.setFont(fnt)
            btn.clicked.connect(lambda: self.buttonClicked(text))
            self.vbox.addWidget(btn)

        self.buttonClicked(text)
コード例 #6
0
class PageEditor(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.placeholder = QWidget()
        hbox = QHBoxLayout()
        hbox.setAlignment(Qt.AlignLeft)
        hbox.setSpacing(10)
        addSection = HyperLink(
            QCoreApplication.translate("PageEditor", "(+) Add Section"))
        addFullSection = HyperLink(
            QCoreApplication.translate("PageEditor",
                                       "(+) Add Full Width Section"))
        l = QVBoxLayout()
        self.layout = QVBoxLayout()
        l.addLayout(self.layout)
        l.addWidget(self.placeholder)
        hbox.addWidget(addSection)
        hbox.addWidget(addFullSection)
        self.layout.addLayout(hbox)
        self.layout.addStretch()
        self.setLayout(l)
        self.setAcceptDrops(True)
        addSection.clicked.connect(self.addNormalSection)
        addFullSection.clicked.connect(self.addFullSection)

    def enableColumnAcceptDrop(self, mode):
        for i in range(self.layout.count()):
            ce = self.layout.itemAt(i).widget()
            if isinstance(ce, ColumnEditor):
                ce.enableColumnAcceptDrop(mode)

    def enableSectionAcceptDrop(self, mode):
        for i in range(self.layout.count()):
            se = self.layout.itemAt(i).widget()
            if isinstance(se, SectionEditor):
                se.enableColumnAcceptDrop(mode)

    def addFullSection(self):
        se = SectionEditor(True)
        self.addSection(se)
        ce = self.getContentEditor()
        if ce:
            sec = Section()
            sec.fullwidth = True
            se.load(sec)
            ce.content.appendSection(sec)
            ce.editChanged("Add Section")

    def addNormalSection(self):
        se = SectionEditor(False)
        self.addSection(se)
        ce = self.getContentEditor()
        if ce:
            sec = Section()
            sec.fullwidth = False
            se.load(sec)
            ce.content.appendSection(sec)
            ce.editChanged("Add Section")

    def addSection(self, se):
        se.sectionEditorCopied.connect(self.copySection)
        self.layout.insertWidget(self.layout.count() - 2, se)

    def sections(self):
        list = []
        for i in range(self.layout.count()):
            se = self.layout.itemAt(i).widget()
            if isinstance(se, SectionEditor):
                list.append(se)
        return list

    def removeSectionEditor(self, se):
        self.layout.removeWidget(se)

    def removeSection(self, se):
        sec = se.section
        se.hide()
        self.layout.removeWidget(se)
        del se
        ce = self.getContentEditor()
        if ce:
            ce.content.removeSection(sec)
            ce.editChanged("Delete Section")

    def copySection(self, se):
        see = SectionEditor(se.fullwidth)
        self.addSection(see)
        ce = self.getContentEditor()
        if ce:
            sec = se.section.clone()
            see.load(sec)
            ce.content.appendSection(sec)
            ce.editChanged("Copy Section")

    def getContentEditor(self):
        sa = self.parentWidget()
        if sa:
            vp = sa.parentWidget()
            if vp:
                cee = vp.parentWidget()
                if cee:
                    return cee
        return None

    def dragEnterEvent(self, event):
        myData = event.mimeData()
        if myData:
            se = myData.getData()
            if isinstance(se, SectionEditor):
                # insert a dropzone at the end
                self.layout.addWidget(DropZone(myData.width, myData.height))
                event.accept()
            else:
                event.ignore()
        else:
            event.ignore()

    def dragLeaveEvent(self, event):
        # remove dropzones
        for i in range(self.layout.count()):
            dz = self.layout.itemAt(i).widget()
            if isinstance(dz, DropZone):
                dz.hide()
                self.layout.removeWidget(dz)
                del dz
                break
        event.accept()

    def dragMoveEvent(self, event):
        myData = event.mimeData()
        if myData:
            se = myData.getData()
            if isinstance(se, SectionEditor):
                height = 0
                row = 0

                # evaluate position for the dropzone to be placed
                for i in range(self.layout.count()):
                    editor = self.layout.itemAt(i).widget()
                    if isinstance(editor, SectionEditor):
                        if event.pos().y() > height and event.pos().y(
                        ) < height + editor.height():
                            break
                        height += editor.height()
                        row = row + 1

                # find dropzone and replace it to new location
                for i in range(self.layout.count()):
                    dz = self.layout.itemAt(i).widget()
                    if isinstance(dz, DropZone):
                        if i != row:
                            self.layout.insertWidget(row, dz)
                        break
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.ignore()
        else:
            event.ignore()

    def dropEvent(self, event):
        myData = event.mimeData()
        if myData:
            se = myData.getData()
            if isinstance(se, SectionEditor):
                # place the dragged SectionEditor to the place where DropZone is now
                for i in range(self.layout.count()):
                    dz = self.layout.itemAt(i).widget()
                    if isinstance(dz, DropZone):
                        dz.hide()
                        self.layout.replaceWidget(dz, se)
                        new_pos = i
                        se.show()
                        del dz
                        break
                ce = self.getContentEditor()
                if ce:
                    ce.content.changeSectionPos(se.section, new_pos)
                    ce.editChanged("Move Section")
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.ignore()
        else:
            event.ignore()
コード例 #7
0
class App(QWidget):
    keys = []
    
    def __init__(self):
        super().__init__()
        self.title = 'ganBreeder - ganTool'
        self.left = 10
        self.top = 10
        self.width = 500
        self.height = 400
        self.outputFolder = os.path.dirname(os.path.realpath(__file__))+'/output/'
        self.initUI()
        
    
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        
        self.hboxTotal = QHBoxLayout()
        self.vboxLeft = QVBoxLayout()
        self.vboxRight = QVBoxLayout()

        # LOGGING #############################################################
        self.logLabel = QLabel()
        self.logLabel.setAlignment(Qt.AlignCenter)
        self.logLabel.setStyleSheet('color: green')
        self.pushLog('__ ready for input __')
        self.vboxLeft.addWidget(self.logLabel)

        # LOGIN ###############################################################
        # Username
        usernameLabel = QLabel()
        usernameLabel.setText('username')
        self.usernameLE = QLineEdit(self)
        # Password
        passwordLabel = QLabel()
        passwordLabel.setText('password')
        self.passwordLE = QLineEdit(self)
        self.passwordLE.setEchoMode(QLineEdit.Password)
                
        hboxLogin = QHBoxLayout()
        hboxLogin.addWidget(usernameLabel)
        hboxLogin.addWidget(self.usernameLE)
        hboxLogin.addWidget(passwordLabel)
        hboxLogin.addWidget(self.passwordLE)
        self.passwordLE.setEchoMode(QLineEdit.Password)
                
        self.vboxLeft.addLayout(hboxLogin)
        
        # FRAMES ##############################################################
        # Number of frames
        hboxNFrames = QHBoxLayout()      
        nFramesLabel = QLabel()
        nFramesLabel.setText('nFrames')
        self.nFramesSB = QSpinBox()
        self.nFramesSB.setMinimum(0)
        self.nFramesSB.setMaximum(999)
        self.nFramesSB.setValue(10)
        
        hboxNFrames.addWidget(nFramesLabel)   
        hboxNFrames.addWidget(self.nFramesSB)  
        
        self.vboxLeft.addLayout(hboxNFrames)
        
        # OUTPUT FOLDER #######################################################
        hboxOutput = QHBoxLayout()      
        outputLabel = QLabel()
        outputLabel.setText('outputFolder')
        self.outputLE = QLineEdit(self)
        self.outputLE.setText(self.outputFolder)
        
        hboxOutput.addWidget(outputLabel)   
        hboxOutput.addWidget(self.outputLE)  
        
        self.vboxLeft.addLayout(hboxOutput)        
        
        # KEYS ################################################################
        hboxNKeys = QHBoxLayout()      
        nKeysLabel = QLabel()
        nKeysLabel.setText('nKeys')
        self.nKeysSB = QSpinBox()
        self.nKeysSB.setMinimum(3)
        self.nKeysSB.setMaximum(10)
        self.nKeysSB.setValue(3)
        self.nKeysSB.valueChanged.connect(self.keyValueChange)
        
        hboxNKeys.addWidget(nKeysLabel)   
        hboxNKeys.addWidget(self.nKeysSB)
        self.vboxLeft.addLayout(hboxNKeys)

        self.initKeys()
        self.vboxKeys = QVBoxLayout()
        self.setKeysWidgets() #puts keys in self.vboxKeys
        self.vboxLeft.addLayout(self.vboxKeys)
        self.vboxLeft.addStretch(1)
        
        # RIGHT VBOX ##########################################################
        runButton = QPushButton('run', self)
        runButton.clicked.connect(self.run)
        self.vboxRight.addWidget(runButton)
        
        viewButton = QPushButton('view', self)
        viewButton.clicked.connect(self.view)
        self.vboxRight.addWidget(viewButton)
        self.vboxRight.addStretch(1)
        
        # compiling total layout
        self.hboxTotal.addLayout(self.vboxLeft)
        self.hboxTotal.addLayout(self.vboxRight)
        self.setLayout(self.hboxTotal)
        
        self.setUserSettings()
        
        self.show()

    def pushLog(self,msg):
        self.logLabel.setText(msg)
        self.logLabel.update()
        
    def setUserSettings(self):
        #Fill here for auto-fill
        self.usernameLE.setText('') #<--- username
        self.passwordLE.setText('') #<--- passw
        self.keys[0].setText('b7be350699c9eef42f5e4c6a')
        self.keys[1].setText('b5c06f29c1b15039812bf45a')
        self.keys[2].setText('54fc255ae27d61ad87f34687')

    def initKeys(self):
        for i in range(self.nKeysSB.value()):
            self.addNewKey()

    def setKeysWidgets(self):
        for i in reversed(range(self.vboxKeys.count())): 
            self.vboxKeys.itemAt(i).widget().setParent(None)
        for k in self.keys:
            self.vboxKeys.addWidget(k)
        self.vboxKeys.update()

    def addNewKey(self):
        keyVal = QLineEdit(self)
        keyVal.setText('')
        self.keys.append(keyVal)

    @pyqtSlot()
    def keyValueChange(self):
        newVal = self.nKeysSB.value()
        oldVal = len(self.keys)
        delta = newVal-oldVal

        if delta > 0:
            for i in range(delta):
                self.addNewKey()
                self.pushLog('__ added key __')
        elif delta < 0:
            for i in range(-delta):
                self.keys.pop()
                self.pushLog('__ removed key __')
        self.setKeysWidgets()
        print('change')

    @pyqtSlot()
    def run(self):
        self.pushLog('__ running : might take a while to load bigGAN __')
        self.logLabel.update()
        self.randHex = '%06x' % random.randint(0, 0xFFFFFF)
        outputDir = self.outputLE.text()+self.randHex
        print('calling command inside conda environment')
        print('bash command:')
        cmd = ['gantools']
        cmd.append('--username')
        cmd.append(self.usernameLE.text())
        cmd.append('--password')
        cmd.append(self.passwordLE.text())
        cmd.append('--nframes')
        cmd.append(str(self.nFramesSB.value()))
        cmd.append('--output-dir')
        cmd.append(outputDir)
        cmd.append('--keys')
        for k in self.keys:
            if k.text() != '':
                cmd.append(k.text())

        # create output folder if it doesn't exist
        try:
            os.mkdir(outputDir)
        except OSError:
            print ("%s Already exists" % outputDir)
        else:
            print ("Successfully created the directory %s " % outputDir)
        
        # run ganTools
        print(cmd)
        MyOut = subprocess.Popen(cmd, 
            stdout=subprocess.PIPE, 
            stderr=subprocess.STDOUT)
        stdout,stderr = MyOut.communicate()
        print(stdout)
        print(stderr)
        self.pushLog('__ running : complete __')
        
    @pyqtSlot()
    def view(self):
        self.pushLog('__ viewing : %s.mp4 __' % self.randHex)
        print('calling command inside conda environment')
        print('bash command:')
        
        cmd = ['ffmpeg']
        cmd.append('-f')
        cmd.append('image2')
        cmd.append('-i')
        cmd.append('output/'+self.randHex+'/%04d.jpeg')
        cmd.append('-crf')
        cmd.append('18')
        cmd.append('output/'+self.randHex+'.mp4')
        print(cmd)
        subprocess.run(cmd)
        
        #Play the file        
        cmd = ['mpv','output/'+self.randHex+'.mp4','--loop']
        print(cmd)
        subprocess.run(cmd)
        self.pushLog('__ viewing : done __')
コード例 #8
0
class MainWindow(base_1, form_1):
    def __init__(self):
        print("__init__")
        lists.create()
        favorites.create()

        widget_list = []
        favorites_list = []
        self.lock = passs.update("false", "true")
        check1 = lists.viewall()
        check2 = favorites.viewall()
        password = (passs.viewall())[0][1]
        for i in check1:
            a = []
            for j in i:
                if (isinstance(j, str)):
                    a.append(j)
            widget_list.append(a)

        for i in check2:
            a = []
            for j in i:
                if (isinstance(j, str)):
                    a.append(j)
            favorites_list.append(a)

        for i in widget_list:
            if (i[4] not in tag_list):
                tag_list.append(i[4])

        super(base_1, self).__init__()
        self.setupUi(self)
        self.account = QWidget()
        self.accountLayout = QVBoxLayout()
        for i in reversed(range(self.accountLayout.count())):
            self.accountLayout.itemAt(i).widget().setParent(None)
        self.widgets = []
        for info in widget_list:
            item = AccountWidget(info[0], info[1], info[2], info[3], info[4],
                                 info[5])
            self.accountLayout.addWidget(item)
            self.widgets.append(item)
        self.account.setLayout(self.accountLayout)

        self.scroll = QScrollArea()
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.account)

        self.scroll2 = QScrollArea()
        self.scroll2.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll2.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll2.setWidgetResizable(True)

        self.scroll3 = QScrollArea()
        self.scroll3.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll3.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll3.setWidgetResizable(True)

        self.searchbar = self.SearchLine
        self.searchbar.textChanged.connect(self.update)

        container = self.SearchReturn
        containerLayout = QVBoxLayout()
        containerLayout.addWidget(self.scroll)

        container.setLayout(containerLayout)
        site_names = []
        for i in widget_list:
            site_names.append(i[0])

        self.completer = QCompleter(site_names)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.searchbar.setCompleter(self.completer)

        self.AddButton.clicked.connect(self.AddButtonClicked)
        self.favorites = QWidget()
        self.favoritesLayout = QVBoxLayout()
        for i in reversed(range(self.favoritesLayout.count())):
            self.favoritesLayout.itemAt(i).widget().setParent(None)
        self.favorites_widget = []
        for info in favorites_list:
            item = FavoritesWidget(info[0], info[1], info[2], info[3], info[4],
                                   info[5])
            self.favoritesLayout.addWidget(item)
            self.favorites_widget.append(item)

        self.favorites.setLayout(self.favoritesLayout)
        self.scroll2.setWidget(self.favorites)
        container2 = self.Favorites
        container2Layout = QVBoxLayout()
        container2Layout.addWidget(self.scroll2)

        container2.setLayout(container2Layout)

        self.HelpButton.clicked.connect(self.HelpButtonClicked)

        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.style().standardIcon(
            QStyle.SP_ComputerIcon))
        self.tray_icon.activated.connect(self.showing)
        '''
            Define and add steps to work with the system tray icon
            show - show window
            hide - hide window
            exit - exit from application
        '''
        show_action = QAction("창 보이기", self)
        quit_action = QAction("프로그램 종료", self)
        hide_action = QAction("창 숨기기", self)
        show_action.triggered.connect(self.show)
        hide_action.triggered.connect(self.hide)
        quit_action.triggered.connect(self.quiting)
        tray_menu = QMenu()
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addAction(quit_action)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()
        self.resetButton.clicked.connect(self.reset)

        self.tags = QWidget()
        self.tagsLayout = QVBoxLayout()
        for i in reversed(range(self.tagsLayout.count())):
            self.tagsLayout.itemAt(i).widget().setParent(None)
        self.tags_widget = []
        for info in tag_list:
            item = Tag(info)
            self.tagsLayout.addWidget(item)
            self.tags_widget.append(item)
        self.tags.setLayout(self.tagsLayout)
        self.scroll3.setWidget(self.tags)
        container3 = self.TagWidget
        container3Layout = QVBoxLayout()
        container3Layout.addWidget(self.scroll3)

        container3.setLayout(container3Layout)

        self.lockButton.clicked.connect(self.LockButtonClicked)
        self.changePassword.clicked.connect(self.ChangeButtonClicked)
        self.setFixedSize(1000, 650)

    def ChangeButtonClicked(self):
        self.change = ChangeUi()

        check = self.change.showModal()

    def LockButtonClicked(self):
        self.lock = (passs.viewall())[1][1]
        print(self.lock)
        if self.lock == "true":
            self.test = VerifyUi()

            check = self.test.showModal()

            if check:
                self.lockButton.setText("잠금 설정")
                self.StatusLabel.setText("잠금 해제 상태입니다.")
                passs.update("true", "false")

        else:
            reply = QMessageBox.question(self, '확인', '잠금을 적용합니다.',
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.No)
            if (reply == QMessageBox.Yes):
                self.lockButton.setText("잠금 해제")
                self.StatusLabel.setText("잠금 상태입니다.")
                QMessageBox.about(self, "확인", "잠금이 적용되었습니다.")
                passs.update("false", "true")

    def ChangePassword(self):
        ori = "000000"
        new = "000000"
        passs.update(ori, new)
        print(passs.viewall())

    def clearLayout(self, layout):
        while layout.count():
            child = layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()

    def reset(self):
        self.clearLayout(self.accountLayout)
        self.clearLayout(self.favoritesLayout)
        self.clearLayout(self.tagsLayout)

        print("reset")
        lists.create()
        favorites.create()

        widget_list = []
        favorites_list = []
        tag_list = []

        check1 = lists.viewall()
        check2 = favorites.viewall()

        for i in check1:
            a = []
            for j in i:
                if (isinstance(j, str)):
                    a.append(j)
            widget_list.append(a)

        for i in check2:
            a = []
            for j in i:
                if (isinstance(j, str)):
                    a.append(j)
            favorites_list.append(a)

        for i in widget_list:
            if (i[4] not in tag_list):
                tag_list.append(i[4])

        self.widgets = []
        for info in widget_list:
            item = AccountWidget(info[0], info[1], info[2], info[3], info[4],
                                 info[5])
            self.accountLayout.addWidget(item)
            self.widgets.append(item)

        self.scroll = QScrollArea()
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)

        self.scroll2 = QScrollArea()
        self.scroll2.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll2.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll2.setWidgetResizable(True)

        self.scroll3 = QScrollArea()
        self.scroll3.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll3.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll3.setWidgetResizable(True)

        self.searchbar = self.SearchLine
        self.searchbar.textChanged.connect(self.update)

        site_names = []
        for i in widget_list:
            site_names.append(i[0])
        self.completer = QCompleter(site_names)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.searchbar.setCompleter(self.completer)

        self.favorites_widget = []
        for info in favorites_list:
            item = FavoritesWidget(info[0], info[1], info[2], info[3], info[4],
                                   info[5])
            self.favoritesLayout.addWidget(item)
            self.favorites_widget.append(item)

        for info in tag_list:
            item = Tag(info)
            self.tagsLayout.addWidget(item)
            self.tags_widget.append(item)

    def quiting(self):
        self.tray_icon.hide()
        self.close()
        qApp.quit()

    def printing(self):
        self.HelpButtonClicked(self)

    def HelpButtonClicked(self):
        self.help = HelpUi()
        self.help.setWindowModality(Qt.ApplicationModal)
        self.help.show()

    def showing(self, reason):
        if (reason == QSystemTrayIcon.DoubleClick):
            self.show()

    def update(self, text):
        #self.__init__()
        for widget in self.widgets:
            if text.lower() in widget.name.lower() or text.lower(
            ) in widget.link.lower():
                widget.show()
            else:
                widget.hide()

    def AddButtonClicked(self):
        self.AddDialog = SaveUi()
        check = self.AddDialog.showModal()

        if check:
            item = AccountWidget(self.AddDialog.SaveName.text(),
                                 self.AddDialog.SiteLink.text(),
                                 self.AddDialog.ID.text(),
                                 self.AddDialog.Password.text(),
                                 self.AddDialog.Tag.text(),
                                 self.AddDialog.Memo.text())
            self.accountLayout.addWidget(item, -2)
            self.widgets.append(item)
            widget_list.append([
                self.AddDialog.SaveName.text(),
                self.AddDialog.SiteLink.text(),
                self.AddDialog.ID.text(),
                self.AddDialog.Password.text(),
                self.AddDialog.Tag.text(),
                self.AddDialog.Memo.text()
            ])
            site_names.append(widget_list[-1][0])
            self.completer = QCompleter(site_names)
            self.searchbar.setCompleter(self.completer)
            self.account.setLayout(self.accountLayout)
            lists.add(self.AddDialog.SaveName.text(),
                      self.AddDialog.SiteLink.text(), self.AddDialog.ID.text(),
                      self.AddDialog.Password.text(),
                      self.AddDialog.Tag.text(), self.AddDialog.Memo.text())
            check2 = self.AddDialog.FavoriteCheck.isChecked()

            if check2:
                print("check2")
                item = FavoritesWidget(self.AddDialog.SaveName.text(),
                                       self.AddDialog.SiteLink.text(),
                                       self.AddDialog.ID.text(),
                                       self.AddDialog.Password.text(),
                                       self.AddDialog.Tag.text(),
                                       self.AddDialog.Memo.text())
                self.favoritesLayout.addWidget(item, -2)
                favorites_list.append([
                    self.AddDialog.SaveName.text(),
                    self.AddDialog.SiteLink.text(),
                    self.AddDialog.ID.text(),
                    self.AddDialog.Password.text(),
                    self.AddDialog.Tag.text(),
                    self.AddDialog.Memo.text()
                ])
                self.favorites.setLayout(self.favoritesLayout)
                favorites.add(self.AddDialog.SaveName.text(),
                              self.AddDialog.SiteLink.text(),
                              self.AddDialog.ID.text(),
                              self.AddDialog.Password.text(),
                              self.AddDialog.Tag.text(),
                              self.AddDialog.Memo.text())
コード例 #9
0
ファイル: ccxt.py プロジェクト: w1r2p1/Pythonic
class CCXT(ElementMaster):

    pixmap_path = 'images/CCXT.png'
    child_pos = (True, False)

    def __init__(self, row, column):
        self.row = row
        self.column = column

        self.current_exchangeObj = None
        self.current_exchange = 'kraken'
        api_key = ''
        sec_key = ''
        #current_method      = 'fetchOHLCV'
        self.current_method = 'create_limit_order'
        self.current_params = {}  # actual parameter values, saved to config
        self.positional_params = [
        ]  # list of object references of parameter input
        log_state = False

        # exchange, api_key, sec_key, method, params, log_state
        self.config = (self.current_exchange, api_key, sec_key,
                       self.current_method, self.current_params, log_state)
        #new
        # exchange_index,

        super().__init__(self.row, self.column, self.pixmap_path, True,
                         self.config)
        super().edit_sig.connect(self.edit)
        logging.debug('CCXT called at row {}, column {}'.format(row, column))
        self.addFunction(CCXTFunction)

    def __setstate__(self, state):
        logging.debug('__setstate__() called CCXT')
        self.row, self.column, self.config = state
        super().__init__(self.row, self.column, self.pixmap_path, True,
                         self.config)
        super().edit_sig.connect(self.edit)
        self.addFunction(CCXTFunction)

    def __getstate__(self):
        logging.debug('__getstate__() called CCXT')
        return (self.row, self.column, self.config)

    def openEditor(self):
        logging.debug('openEditor() called CCXT')

    def edit(self):

        logging.debug('edit() called CCXT')

        # exchange, api_key, sec_key, method, params, log_state
        self.current_exchange, api_key, sec_key, \
             self.current_method, self.current_params, log_state = self.config

        self.ccxt_layout = QVBoxLayout()
        self.confirm_button = QPushButton(QC.translate('', 'Ok'))

        self.exchange_txt = QLabel()
        self.exchange_txt.setText(QC.translate('', 'Choose Exchange'))

        # create list of exchanges
        self.selectExchange = QComboBox()

        for exchange_id in ccxt.exchanges:
            try:
                exchange = getattr(ccxt, exchange_id)()
                self.selectExchange.addItem(exchange.name,
                                            QVariant(exchange_id))
            except Exception as e:
                print(e)

        # load current exchange object
        self.current_exchangeObj = getattr(ccxt,
                                           self.selectExchange.currentData())()

        # select saved exchange from config

        index = ccxt.exchanges.index(self.current_exchange)
        self.selectExchange.setCurrentIndex(index)

        self.pub_key_txt = QLabel()
        self.pub_key_txt.setText(QC.translate('', 'Enter API key:'))
        self.pub_key_input = QLineEdit()
        self.pub_key_input.setText(api_key)

        self.prv_key_txt = QLabel()
        self.prv_key_txt.setText(QC.translate('', 'Enter secret key:'))
        self.prv_key_input = QLineEdit()
        self.prv_key_input.setText(sec_key)

        # List all available methods

        self.method_txt = QLabel()
        self.method_txt.setText(QC.translate('', 'Select method'))

        self.selectMethod = QComboBox()
        self.updateMethods()

        # List method parameters

        self.method_params = QWidget()
        self.method_params_layout = QVBoxLayout(self.method_params)

        self.updateParams()  # brauche ich das noch?

        # hier logging option einfügen
        #??????
        self.log_line = QWidget()
        self.ask_for_logging = QLabel()
        self.ask_for_logging.setText(QC.translate('', 'Log output?'))
        self.log_checkbox = QCheckBox()
        self.log_line_layout = QHBoxLayout(self.log_line)
        self.log_line_layout.addWidget(self.ask_for_logging)
        self.log_line_layout.addWidget(self.log_checkbox)
        self.log_line_layout.addStretch(1)

        if log_state:
            self.log_checkbox.setChecked(True)

        self.ccxt_edit = ElementEditor(self)
        self.ccxt_edit.setWindowTitle(QC.translate('', 'CCXT'))

        # signals and slots
        self.confirm_button.clicked.connect(self.ccxt_edit.closeEvent)
        self.ccxt_edit.window_closed.connect(self.edit_done)
        self.selectExchange.currentIndexChanged.connect(self.exchangeChanged)
        self.selectMethod.currentIndexChanged.connect(self.methodChanged)

        self.ccxt_layout.addWidget(self.exchange_txt)
        self.ccxt_layout.addWidget(self.selectExchange)
        self.ccxt_layout.addWidget(self.pub_key_txt)
        self.ccxt_layout.addWidget(self.pub_key_input)
        self.ccxt_layout.addWidget(self.prv_key_txt)
        self.ccxt_layout.addWidget(self.prv_key_input)
        self.ccxt_layout.addWidget(self.selectMethod)
        self.ccxt_layout.addWidget(self.method_params)
        self.ccxt_layout.addWidget(self.log_line)
        self.ccxt_layout.addStretch(1)

        self.ccxt_layout.addWidget(self.confirm_button)
        self.ccxt_edit.setLayout(self.ccxt_layout)

        # select saved method from config

        methodsList = [
            m[0] for m in inspect.getmembers(self.current_exchangeObj,
                                             predicate=inspect.ismethod)
            if m[0][:2] != '__'
        ]

        index = methodsList.index(self.current_method)
        self.selectMethod.setCurrentIndex(index)

        # load saved parameter values

        self.loadSavedParams()

        # display element editor

        self.ccxt_edit.show()

    def exchangeChanged(self, event):

        logging.debug('CCXT::exchangeChanged() called {}'.format(event))

        self.current_exchange = self.selectExchange.currentData()
        self.current_exchangeObj = getattr(ccxt, self.current_exchange)()
        self.updateMethods()

    def methodChanged(self, event):

        logging.debug('updateSignature() called CCXT')
        method_name = self.selectMethod.currentData()
        if method_name:
            self.current_method = method_name
            self.updateParams()

    def updateMethods(self):

        logging.debug('CCXT::updateMethods() called')
        self.selectMethod.clear()

        for method in inspect.getmembers(self.current_exchangeObj,
                                         predicate=inspect.ismethod):
            if method[0][:2] != '__':
                # mit getattr lässt sich die methode dann wieder aufrufen

                self.selectMethod.addItem(method[0], QVariant(method[0]))

    def updateParams(self):

        logging.debug('CCXT::updateParams() called')

        method = getattr(self.current_exchangeObj, self.current_method)
        signature = inspect.signature(method)

        # remove widgets from layout

        for i in reversed(range(self.method_params_layout.count())):
            self.method_params_layout.itemAt(i).widget().setParent(None)

        # remove params from list

        self.positional_params.clear()

        for param in signature.parameters.values():
            if param.kind == param.POSITIONAL_OR_KEYWORD:
                paramLabel = QLabel('{}:'.format(param.name.capitalize()))
                self.method_params_layout.addWidget(paramLabel)

                paramInput = QLineEdit()
                paramInput.setObjectName(param.name)
                self.positional_params.append(paramInput)
                self.method_params_layout.addWidget(paramInput)

            if param.kind == param.VAR_POSITIONAL:
                # e.g. createLimitOrder
                varArgs = VarPositionalParser()
                self.positional_params.append(varArgs)
                self.method_params_layout.addWidget(varArgs)

    def loadSavedParams(self):

        for param in self.positional_params:
            if (isinstance(param, VarPositionalParser)
                    and 'args' in self.current_params):

                for argName, argVal in self.current_params['args'].items():
                    param.addArgument(argName, argVal)
            else:
                key = param.objectName()
                if key in self.current_params:
                    param.setText(self.current_params[key])

    def edit_done(self):

        logging.debug('edit_done() called CCXT')

        varArgs = {}  # only used in case of variable length argument list

        self.current_params.clear()

        for param in self.positional_params:
            if isinstance(param, VarPositionalParser):
                for arg in param.arg_list:

                    varArgs[arg.s_arg_name] = arg.s_arg_val

                self.current_params['args'] = varArgs

            else:
                name = param.objectName()
                self.current_params[name] = param.text()

        log_state = self.log_checkbox.isChecked()
        api_key = self.pub_key_input.text()
        sec_key = self.prv_key_input.text()

        # exchange, api_key, sec_key, method, params, log_state

        self.config = (self.current_exchange, api_key, sec_key,
                       self.current_method, self.current_params, log_state)

        self.addFunction(CCXTFunction)
コード例 #10
0
class PlotConfig(QFrame):
    """
    This widget provides a configuration panel for manipulating plot widgets
    """

    def __init__(self, plot_widget: PlotWidget, *args, **kwargs):
        """
        Initialize plot config
        :param plot_widget: plot widget to access
        """
        super().__init__(*args, **kwargs)
        self._plot_widget = plot_widget
        self._ax = self._plot_widget.add_subplot(111)
        self.plot_items = list()

        self._layout = QGridLayout()
        self.scroll_layout = QVBoxLayout()
        self.setLayout(self._layout)
        self._setup_()

    def set_title(self, title):
        """
        Set plot title
        :param title: plot title
        """
        self._ax.set_title(title)
        self._plot_widget.update()

    def set_xlabel(self, value):
        """
        Set x-axis label of the plot
        :param value: x-axis label
        """
        self._ax.set_xlabel(value)
        self._plot_widget.update()

    def set_ylabel(self, value):
        """
        Set y-axis label of the plot
        :param value: y-axis label
        """
        self._ax.set_ylabel(value)
        self._plot_widget.update()

    def set_xrange(self, lower, upper):
        """
        Set x-axis range
        :param lower: left boundary
        :param upper: right boundary
        """
        self._ax.set_xlim(lower, upper)
        self._plot_widget.update()

    def set_yrange(self, lower, upper):
        """
        Set y-axis range
        :param lower: lower boundary
        :param upper: upper boundary
        """
        self._ax.set_ylim(lower, upper)
        self._plot_widget.update()

    def set_range(self, xl, xu, yl, yu):
        """
        Set plot range
        :param xl: left boundary
        :param xu: right boundary
        :param yl: lower boundary
        :param yu: upper boundary
        """
        self.set_xrange(xl, xu)
        self.set_yrange(yl, yu)

    def set_visibility(self, plot_item, visible):
        """
        Set visibility of the plot item
        :param plot_item: plot item
        :param visible: True for visible
        """
        plot_item.line_object._visible = visible
        self._plot_widget.update()

    def remove(self, plot_item):
        """
        Remove plot item
        :param plot_item: plot item to remove
        """
        plot_item.line_object.remove()
        self.plot_items.remove(plot_item)
        self._fill_plot_list_()
        self._plot_widget.update()

    def update_legend(self):
        """
        Update legend according to plot items
        """
        self._ax.legend([item.name for item in self.plot_items])

    def plot(self, *args, name=None, allow_remove=True, **kwargs):
        """
        Plot data
        :param args: x and y data (as well as more matplotlib compatible arguments)
        :param name: name of the plot
        :param allow_remove: True or false
        :param kwargs: keyword arguments
        """
        if name is None:
            name = 'plot item {}'.format(len(self.plot_items))

        line, = self._ax.plot(*args, **kwargs)
        plot_item = PlotWidgetItem(line, name, self._plot_widget, allow_remove, args, kwargs)
        self.plot_items.append(plot_item)

        self._fill_plot_list_()
        return plot_item

    def _fill_plot_list_(self):
        """
        Fill plot configuration list
        """
        # remove existing items
        for i in reversed(range(self.scroll_layout.count())):
            self.scroll_layout.itemAt(i).widget().setParent(None)

        # fill list
        for item in self.plot_items:
            item_widget = EnableDisableWidget(item, self)
            self.scroll_layout.addWidget(item_widget)
        self.update_legend()

    def _setup_(self):
        self._layout.addWidget(QLabel('Plot Settings:'), 0, 0)

        scroll_area = QScrollArea()
        group_box = QGroupBox()
        group_box.setLayout(self.scroll_layout)
        self.scroll_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        scroll_area.setWidget(group_box)
        scroll_area.setWidgetResizable(True)
        self._layout.addWidget(scroll_area, 1, 0)
コード例 #11
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.top_window = None

        ConfigurationManager.load_configuration()
        self.initUI()

    def initUI(self):
        center_point = QDesktopWidget().availableGeometry().center()
        window_size = (300, 600)
        self.setGeometry(center_point.x() - window_size[0] // 2,
                         center_point.y() - window_size[1] // 2,
                         window_size[0],
                         window_size[1])
        self.setWindowTitle(QtWidgets.QApplication.instance().applicationName())

        scroll = QScrollArea(self)
        scroll.setWidgetResizable(True)

        scrollContent = QWidget()
        scrollContent.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
        scroll.setWidget(scrollContent)

        self.scrollLayout = QVBoxLayout(scrollContent)
        self.scrollLayout.setSpacing(0)
        scrollContent.setLayout(self.scrollLayout)

        self.create_apps_list()

        self.setCentralWidget(scroll)

        self.create_menubar()

        self.show()

    def create_apps_list(self):
        # clear
        for i in range(self.scrollLayout.count()):
            self.scrollLayout.itemAt(0).widget().setParent(None)

        for item in ConfigurationManager.get_configuration().applications_list:
            widget = ApplicationWidget(item, self)
            widget.setMaximumHeight(widget.minimumHeight())
            self.scrollLayout.addWidget(widget, 0)

    def create_menubar(self):
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')

        newAct = QAction('New', self)
        newAct.setIcon(QIcon('icons/plus.png'))
        newAct.triggered.connect(self.add_new_launcher)

        toolsMenu = menubar.addMenu('Tools')

        topAct = QAction('Top', self)
        topAct.triggered.connect(self.show_top_window)

        fileMenu.addAction(newAct)
        toolsMenu.addAction(topAct)

    def closeEvent(self, event):
        ConfigurationManager.save_configuration()
        event.accept()

    def add_new_launcher(self):
        app_data = ApplicationData()
        settings_window = ApplicationSettingsWidget(app_data)

        if settings_window.exec_():
            app_data = settings_window.app_data
            ConfigurationManager.get_configuration().applications_list.append(app_data)
            self.create_apps_list()

    def show_top_window(self):
        if self.top_window is None:
            self.top_window = TopViewWindow()
            self.top_window.closed.connect(self.top_window_closed)
        else:
            self.top_window.focusWidget()

    def top_window_closed(self):
        self.top_window = None
コード例 #12
0
class FilterModal(QWidget):
    WANT_TO_CLOSE_SIGNAL = pyqtSignal()

    def __init__(self,
                 pos,
                 width,
                 title,
                 sort_mode,
                 filter_mode,
                 name_filter,
                 parent=None):
        super(FilterModal, self).__init__(parent=parent)
        self.setWindowFlags(Qt.SplashScreen)
        self.setFocusPolicy(Qt.ClickFocus)
        self.setFocus()
        self.vbox = QVBoxLayout()
        self.bt_sorted_asc = QPushButton("Trier A -> Z")
        self.bt_sorted_dsc = QPushButton("Trier Z -> A")
        self.title = title
        self.name_filter = name_filter
        self.sort_mode = sort_mode
        self.filter_mode = filter_mode
        self.list_fiter = filter_store.dicts_filter[self.name_filter]
        self.setFixedWidth(width)
        self.move(pos)
        self.init_widget()
        self.show()

    def init_widget(self):
        self.vbox.setSpacing(5)
        self.vbox.setContentsMargins(1, 5, 1, 5)
        if self.sort_mode:
            if filter_store.sort_name == self.name_filter:
                if filter_store.sort_asc:
                    self.bt_sorted_asc.setStyleSheet(
                        button_no_radius_orange_stylesheet)
                    self.bt_sorted_dsc.setStyleSheet(
                        button_no_radius_stylesheet)
                else:
                    self.bt_sorted_asc.setStyleSheet(
                        button_no_radius_stylesheet)
                    self.bt_sorted_dsc.setStyleSheet(
                        button_no_radius_orange_stylesheet)
            else:
                self.bt_sorted_asc.setStyleSheet(button_no_radius_stylesheet)
                self.bt_sorted_dsc.setStyleSheet(button_no_radius_stylesheet)
            self.bt_sorted_asc.clicked.connect(self.on_click_bt_sorted_asc)
            self.bt_sorted_dsc.clicked.connect(self.on_click_bt_sorted_dsc)
            self.vbox.addWidget(self.bt_sorted_asc)
            self.vbox.addWidget(self.bt_sorted_dsc)
        if self.sort_mode and self.filter_mode:
            hbar = MondonWidget()
            hbar.setFixedHeight(2)
            hbar.set_background_color(color_gris_moyen)
            self.vbox.addWidget(hbar)
        if self.filter_mode:
            for value in self.list_fiter.keys():
                text = value
                if self.name_filter == "code_perfo":
                    text = "Perfo. " + chr(
                        96 + value).capitalize() if value != "Tous" else value
                self.vbox.addWidget(
                    LineFilter(parent=None,
                               value=value,
                               text=text,
                               name_filter=self.name_filter))
            bt_ok = QPushButton("OK")
            bt_ok.setFixedWidth(40)
            bt_ok.setStyleSheet(button_14_stylesheet)
            bt_ok.clicked.connect(self.on_click_bt_ok)
            hbox = QHBoxLayout()
            hbox.addWidget(bt_ok)
            self.vbox.addLayout(hbox)
        self.setLayout(self.vbox)

    def update_widget(self):
        items = (self.vbox.itemAt(i) for i in range(self.vbox.count()))
        for item in items:
            if item.widget() and item.widget().objectName() == "LineFilter":
                item.widget().update_widget()

    def paintEvent(self, event):
        p = QPainter(self)
        color = color_blanc.rgb_components
        qcolor_blanc = QColor(color[0], color[1], color[2])
        color = color_gris_moyen.rgb_components
        qcolor_gris = QColor(color[0], color[1], color[2])
        pen = QPen()
        pen.setColor(qcolor_gris)
        p.setPen(pen)
        p.fillRect(0, 0, self.width(), self.height(), qcolor_blanc)
        p.drawRect(0, 0, self.width() - 1, self.height() - 1)

    def on_click_bt_ok(self):
        self.WANT_TO_CLOSE_SIGNAL.emit()

    def on_click_bt_sorted_asc(self):
        filter_store.set_sort_param(sort_name=self.name_filter, sort_asc=True)
        self.WANT_TO_CLOSE_SIGNAL.emit()

    def on_click_bt_sorted_dsc(self):
        filter_store.set_sort_param(sort_name=self.name_filter, sort_asc=False)
        self.WANT_TO_CLOSE_SIGNAL.emit()

    def focusOutEvent(self, e):
        self.WANT_TO_CLOSE_SIGNAL.emit()
コード例 #13
0
class HtmlTranslator(QtWidgets.QMainWindow, tabs_design.Ui_MainWindow):
    def initTableHeader(self):
        # Шапка таблицы
        GUI.setTableHeader(self.langs, self.tableHeaderLayout)

    ################------------------------####################
    #############**Создаем индексы переводов**##################
    ################------------------------####################
    def indexVocabulary(self):
        initData = self.initDataVocabulary
        # Инициализация списков для дальнейшего наполнения
        data = {}
        for lang in self.langs:
            data[lang] = {}
        # Формируем необходимую структуру данных для записи в индексные файлы
        for key in initData:
            for lang in self.langs:
                data[lang].update({initData[key][lang]: key})
        # Пишем в файл json данные формата "значение : ключ" (с учетом локализации)
        for lng in data:
            self.writeJson(self.vocabularyFileName + '_' + lng, data[lng])

    ################------------------------####################
    #############*****Заппись json в файл*****##################
    ################------------------------####################
    def writeJson(self, fileName, data):
        with open(fileName + '.json', 'w', encoding='utf8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)

    ################------------------------####################
    #############****Инициализация словаря****##################
    ################------------------------####################
    def initVocabulary(self):
        layout = QGridLayout()
        initData = self.initDataVocabulary
        widget = QWidget()
        # Виджет в скролл области
        self.scrollArea.setWidget(widget)
        self.vocabularyLayout = QVBoxLayout(widget)

        # Рендер переводов
        for key in initData:
            horizontal = GUI.setRow(self, self.langs, initData[key], key,
                                    self.vocabularyLayout)
            # Установка обработчиков нажатия кнопок
            for itemInRow in range(horizontal.itemAt(0).count()):
                widgetType = horizontal.itemAt(0).itemAt(
                    itemInRow).widget().property('type')
                if (widgetType == 'edit'):
                    horizontal.itemAt(0).itemAt(
                        itemInRow).widget().clicked.connect(self.editClick)
                if (widgetType == 'delete'):
                    horizontal.itemAt(0).itemAt(
                        itemInRow).widget().clicked.connect(self.deleteClick)
            self.vocabularyLayout.addLayout(horizontal)
        # Устанавливаем основной (вертикальный шаблон) в окне приложения
        self.vocabularyLayout.addStretch(1)

    def deleteClick(self):
        # Подтверждение удаления записи
        confirmDelete = QtWidgets.QMessageBox.critical(
            None, 'Подтверждение удаления',
            'Вы действительно желаете удалить данную запись?',
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        if confirmDelete == QtWidgets.QMessageBox.Yes:
            # Получаем индекс горизонтального шаблона по аттрибуту кнопки (ID)
            horizontalRowLayoutId = self.sender().property('id')
            keyAttr = self.sender().property('key')
            horizontalRowLayout = self.vocabularyLayout.itemAt(
                horizontalRowLayoutId)

            # Шаблон сетки в горизонтальном шаблоне (QGridLayoiut в шаблоне QHLayout)
            innerRowGridLayout = horizontalRowLayout.itemAt(
                0
            )  #Немного костыль, если будет боолее одного layout-та не сработает
            widgetCount = innerRowGridLayout.count()

            # Удаляем все виджеты в шаблоне (layuot-e)
            for i in reversed(range(widgetCount)):
                innerRowGridLayout.itemAt(i).widget().setParent(None)
            # Удаляем шаблон сетки (QGridLayout) из горизонтального шаблона
            horizontalRowLayout.removeItem(horizontalRowLayout.itemAt(0))
            self.vocabularyLayout.removeItem(
                self.vocabularyLayout.itemAt(horizontalRowLayoutId))

            #Обновление аттрибутов ID у кнопок редактирования и удаления (чтобы индексы слоев GUI соответствовали индексам записей из словаря)
            i = 0
            for horizontalRow in range(
                    self.vocabularyLayout.count() - 1
            ):  # count()-1 Убираем из общего количества объектов последний добавляющий растяжение макету (self.vocabularyLayout.addStretch(1))
                if (self.vocabularyLayout.itemAt(horizontalRow).itemAt(0) !=
                        None):
                    for itemInRow in range(
                            self.vocabularyLayout.itemAt(horizontalRow).itemAt(
                                0).count()):
                        #Тип элемента GUI (если это тип удалить или редактировать (кнопки), то обновляем их ID-ки после удаления перевода)
                        rowItemWidgetType = self.vocabularyLayout.itemAt(
                            horizontalRow).itemAt(0).itemAt(
                                itemInRow).widget().property('type')
                        if (rowItemWidgetType == self.editType
                                or rowItemWidgetType == self.deleteType):
                            self.vocabularyLayout.itemAt(horizontalRow).itemAt(
                                0).itemAt(itemInRow).widget().setProperty(
                                    'id', i)
                i += 1
            del self.initDataVocabulary[keyAttr]
            with open(self.vocabularyFileName + '.json', 'w') as f:
                json.dump(self.initDataVocabulary, f)
            self.indexVocabulary()

    def editClick(self):
        self.dialog = QDialog(self)
        self.dialog.ui = uic.loadUi('editTranslateDialog.ui', self.dialog)
        translateKey = self.sender().property('key')
        self.renderDialog(self.initDataVocabulary[translateKey],
                          key=translateKey,
                          type='edit')

    def clickBtnAddTranslate(self, values=None):
        #инициализация диалогового окна и установка дизайна (пустой layout)
        self.dialog = QDialog(self)
        self.dialog.ui = uic.loadUi('addTranslateDialog.ui', self.dialog)
        self.renderDialog()

    def renderDialog(self, values=None, key=None, type='save'):
        layout = QVBoxLayout()
        # Ключ перевода (добавляем на layout метку и инпут)
        keyRow = QHBoxLayout()
        keyRow.addWidget(QLabel('Ключ', objectName='textLabel'))
        if key is not None:
            keyInput = QtWidgets.QLineEdit(key, objectName='inputField')
        else:
            keyInput = QtWidgets.QLineEdit(objectName='inputField')
        keyInput.setProperty('name', 'key')
        keyRow.addWidget(keyInput)
        layout.addLayout(keyRow)
        layout.addStretch(1)
        # Локализованные значения (сами переводы)
        for lang in self.langs:
            langRowHorizontal = QHBoxLayout()
            lng = QLabel(lang, objectName='textLabel')
            if values is not None:
                lngInput = QtWidgets.QLineEdit(values[lang],
                                               objectName='inputField')
            else:
                lngInput = QtWidgets.QLineEdit(objectName='inputField')
            lngInput.setProperty('name', lang)
            langRowHorizontal.addWidget(lng)
            langRowHorizontal.addWidget(lngInput)
            layout.addLayout(langRowHorizontal)
            layout.addStretch(1)
        layout.addStretch(1)

        # Кнопки взаимодействия с диалоговым окном (сохранить и отмена - закрыть диалог)
        buttonsRow = QHBoxLayout()
        saveButton = QPushButton(
            'Сохранить',
            objectName='saveButton' if type == 'save' else 'editButton')
        cancelButton = QPushButton('Отмена', objectName='cancelButton')
        # Обработчик нажатия  кнопок (отмена и сохранить)
        cancelButton.clicked.connect(self.cancelDialogClick)
        saveButton.clicked.connect(self.saveTranslateClick if type ==
                                   'save' else self.updateTranslateClick)
        buttonsRow.addWidget(cancelButton)
        buttonsRow.addWidget(saveButton)

        # Информационный текст
        infoRow = QHBoxLayout()
        info = QLabel(
            'Внимание! При редактировании ключа будет создана новая запись в словаре!',
            objectName='dangerLabel')
        infoRow.addWidget(info)

        layout.addLayout(infoRow)
        layout.addStretch(1)
        layout.addLayout(buttonsRow)
        # Устанавливаем стили диалогового окна
        self.dialog.setStyleSheet(open("styles/qLineEdit.qss", "r").read())
        self.dialog.setLayout(layout)
        # Показываем диалоговое окно
        self.dialog.show()

    # Обновляем  перевод в файлы (словари)
    def updateTranslateClick(self):
        dialogData = {}
        # Собираем данные с формы (диалоговое окно)
        emptyInputError = False
        for dialogInput in range(self.dialog.layout().count()):
            if (self.dialog.layout().itemAt(dialogInput).__class__.__name__ ==
                    'QHBoxLayout'):
                dialogItem = self.dialog.layout().itemAt(dialogInput)
                if (dialogItem.itemAt(1) is not None
                        and dialogItem.itemAt(1).widget().property('name') !=
                        None):
                    # Ключ
                    name = self.dialog.layout().itemAt(dialogInput).itemAt(
                        1).widget().property('name')
                    # Значение
                    value = self.dialog.layout().itemAt(dialogInput).itemAt(
                        1).widget().text()
                    # Проверяем на наличие пустых полей
                    if (len(value) < 2):
                        emptyInputError = True
                    dialogData[name] = value
        # В случае пустоты хотя бы в одном из полей информируем пользователя
        if (emptyInputError):
            self.showMessage('Ошибка!', 'Не заполнены все поля', 'warning')
        else:
            newItem = {}
            langValueItem = {}
            # Записываем переводы в файлы локализаций
            for lang in self.langs:
                langValueItem[lang] = dialogData[lang]
            self.initDataVocabulary[dialogData['key']] = langValueItem
            self.writeJson(self.vocabularyFileName, self.initDataVocabulary)
            self.showMessage('Обновлено', 'Перевод успешно обновлен!', 'info')
            # Очищаем поля ввода в диалоговом окне
            for dialogInput in range(self.dialog.layout().count()):
                if (self.dialog.layout().itemAt(dialogInput).__class__.__name__
                        == 'QHBoxLayout'):
                    dialogItem = self.dialog.layout().itemAt(dialogInput)
                    if (dialogItem.itemAt(1) is not None
                            and dialogItem.itemAt(1).widget().property('name')
                            != None):
                        self.dialog.layout().itemAt(dialogInput).itemAt(
                            1).widget().setText('')
            horizontal = GUI.setRow(self, self.langs, dialogData,
                                    dialogData['key'], self.vocabularyLayout)
            self.initVocabulary()
            self.indexVocabulary()

    # Сохраняем перевод в файлы (словари)
    def saveTranslateClick(self):
        dialogData = {}
        #Собираем данные с формы (диалоговое окно)
        emptyInputError = False
        for dialogInput in range(self.dialog.layout().count()):
            if (self.dialog.layout().itemAt(dialogInput).__class__.__name__ ==
                    'QHBoxLayout'):
                dialogItem = self.dialog.layout().itemAt(dialogInput)
                if (dialogItem.itemAt(1) is not None
                        and dialogItem.itemAt(1).widget().property('name') !=
                        None):
                    #Ключ
                    name = self.dialog.layout().itemAt(dialogInput).itemAt(
                        1).widget().property('name')
                    #Значение
                    value = self.dialog.layout().itemAt(dialogInput).itemAt(
                        1).widget().text()
                    # Проверяем на наличие пустых полей
                    if (len(value) < 2):
                        emptyInputError = True
                    dialogData[name] = value
        # В случае пустоты хотя бы в одном из полей информируем пользователя
        if (emptyInputError):
            self.showMessage('Ошибка!', 'Не заполнены все поля', 'warning')
        else:
            newItem = {}
            langValueItem = {}
            #Записываем переводы в файлы локализаций
            for lang in self.langs:
                langValueItem[lang] = dialogData[lang]
            if (self.initDataVocabulary is None
                    or len(self.initDataVocabulary) < 1):
                self.initDataVocabulary = {}
                self.initDataVocabulary[dialogData['key']] = langValueItem
                self.initTableHeader()
                self.initVocabulary()
            else:
                self.initDataVocabulary[dialogData['key']] = langValueItem
            self.writeJson(self.vocabularyFileName, self.initDataVocabulary)
            self.showMessage('Сохранено', 'Перевод успешно добавлен!', 'info')
            # Очищаем поля ввода в диалоговом окне
            for dialogInput in range(self.dialog.layout().count()):
                if (self.dialog.layout().itemAt(dialogInput).__class__.__name__
                        == 'QHBoxLayout'):
                    dialogItem = self.dialog.layout().itemAt(dialogInput)
                    if (dialogItem.itemAt(1) is not None
                            and dialogItem.itemAt(1).widget().property('name')
                            != None):
                        self.dialog.layout().itemAt(dialogInput).itemAt(
                            1).widget().setText('')
            horizontal = GUI.setRow(self, self.langs, dialogData,
                                    dialogData['key'], self.vocabularyLayout)
            self.initVocabulary()
            self.indexVocabulary()

    # Закрываем диалоговое окно
    def cancelDialogClick(self):
        self.dialog.close()

    def to_json(self, inputJson):
        try:
            json_object = json.load(inputJson)
        except ValueError as e:
            return None
        return json_object

    def getInputs(self):
        return (self.first.text(), self.second.text())

    # def getFiles(self, dir = ''):
    #     if(len(dir) > 0) :
    #         return [f for f in listdir(dir) if isfile(join(dir, f))]
    #
    # def getDirs(self, dir=''):
    #         return [f for f in listdir(dir) if isdir(join(dir, f))]

    ################------------------------####################
    ########****Запускаем работу скрипта(Laravel)****################
    ################------------------------####################
    def clickBtnRunLaravel(self):
        try:
            Laravel.run(self.settingsLaravelRootDir, self.setting_main_lang)
        except FileNotFoundError as f:
            self.showMessage('Ошибка!', 'Не верно указан путь к файлу!',
                             'critical')

    def __init__(self):
        # Это здесь нужно для доступа к переменным, методам
        # и т.д. в файле html.py
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна

        # Информационное окно
        self.msg = QtWidgets.QMessageBox()

        #Инициализация входной и выходной строки
        self.input = ''
        self.output = ''

        #Загрузка настроек из файла
        self.load_settings()

        # Длина строки перевода (отоюражение в словаре)
        self.translateLen = 25

        #Языки
        self.langs = self.setting_langs.split('|')
        self.default_lang = self.setting_main_lang

        #Типы кнопок (удалить, редактировать)
        self.editType = 'edit'
        self.deleteType = 'delete'

        #Загрузка словаря
        self.vocabularyFileName = 'vocabulary'
        self.vocabularyLayout = self.scrollArea
        #Загрузка  данных словаря
        with open(self.vocabularyFileName + '.json', 'r') as inputData:
            self.initDataVocabulary = self.to_json(inputData)
        #Функции инициализации

        if (self.initDataVocabulary is not None
                and len(self.initDataVocabulary) > 0):
            self.indexVocabulary()
            self.initTableHeader()
            self.initVocabulary()

        #Обработчики нажатия кнопок
        self.btn_run.clicked.connect(self.click_btn_run)
        self.btn_save_settings.clicked.connect(self.click_btn_save_settings)
        self.btn_translate_file.clicked.connect(self.click_btn_translate_file)
        self.addTranslate.clicked.connect(self.clickBtnAddTranslate)
        #Laravel
        self.btnLaravelRoot.clicked.connect(self.clickBtnLaravelRoot)
        self.btnRunLaravel.clicked.connect(self.clickBtnRunLaravel)

        #Обработчик события изменение позиции курсора
        #self.main_input.cursorPositionChanged.connect(self.changeInput)

    def load_settings(self):
        # Читаем настройки из файла
        self.settings_path = 'settings.ini'
        if os.path.exists(self.settings_path):
            settings = configparser.ConfigParser()
            settings.read(self.settings_path)
            # GENERAL
            self.setting_langs = settings.get('GENERAL', 'LANGS')
            self.setting_main_lang = settings.get('GENERAL', 'MAIN_LANG')
            self.setting_file_translates = settings.get(
                'MODX', 'FILE_TRANSLATES')
            self.setting_l_placeholder = settings.get('MODX',
                                                      'LEFT_PLACEHOLDER')
            self.setting_r_placeholder = settings.get('MODX',
                                                      'RIGHT_PLACEHOLDER')
            #LARAVEl
            self.settingsLeftLaravelPlaceholder = settings.get(
                'LARAVEL', 'LEFT_LARAVEL_PLACEHOLDER')
            self.settingsRightLaravelPlaceholder = settings.get(
                'LARAVEL', 'RIGHT_LARAVEL_PLACEHOLDER')
            self.settingsLaravelRootDir = settings.get('LARAVEL', 'ROOT_DIR')
            # DB
            self.setting_db_user = settings.get('DB', 'DB_USER')
            self.setting_db_name = settings.get('DB', 'DB_NAME')
            self.setting_db_pass = settings.get('DB', 'DB_PASS')

            # Установка значений настроек из файла на форму
            if len(self.setting_langs) > 0:
                langs_arr = self.setting_langs.split('|')
                if 'ru' in langs_arr:
                    self.ru.setChecked(True)
                if 'en' in langs_arr:
                    self.en.setChecked(True)
                if 'uk' in langs_arr:
                    self.uk.setChecked(True)
                if 'de' in langs_arr:
                    self.de.setChecked(True)
            main_lang = self.main_lang.findText(self.setting_main_lang,
                                                QtCore.Qt.MatchFixedString)
            if main_lang >= 0:
                self.main_lang.setCurrentIndex(main_lang)
            self.file_path.setText(self.setting_file_translates)
            self.l_placeholder.setText(self.setting_l_placeholder)
            self.r_placeholder.setText(self.setting_r_placeholder)
            self.db_user.setText(self.setting_db_user)
            self.db_name.setText(self.setting_db_name)
            self.db_pass.setText(self.setting_db_pass)

            #Laravel
            self.laravelRootDir.setText(self.settingsLaravelRootDir)
            self.leftLaravelPlaceholder.setText(
                self.settingsLeftLaravelPlaceholder)
            self.rightLaravelPlaceholder.setText(
                self.settingsRightLaravelPlaceholder)

    # def changeInput (self):
    #     input = self.main_input
    #     #self.input = self.main_input.toPlainText()
    #     #str_output = self.input.replace('<div>', "[#" + str(exist_id) + "#]")
    #     input.setText("<div></div>")
    #     #print(self.input)

    ################------------------------####################
    #############****Выбор файла переводов****##################
    ################------------------------####################
    def click_btn_translate_file(self):
        fname, _filter = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Выберите файл')
        self.file_path.setText(fname)

    ################------------------------####################
    #######****Выбор корневой директории шаблонов****###########
    ################------------------------####################
    def clickBtnLaravelRoot(self):
        dirName = QtWidgets.QFileDialog.getExistingDirectory(
            self, 'Выберите директорию', '/home')
        self.laravelRootDir.setText(dirName)

    ################------------------------####################
    #############****Обновление настроек****####################
    ################------------------------####################
    def click_btn_save_settings(self):
        # языки для переводов
        langs = []
        if self.ru.isChecked():
            langs.append('ru')
        if self.en.isChecked():
            langs.append('en')
        if self.uk.isChecked():
            langs.append('uk')
        if self.de.isChecked():
            langs.append('de')
        # Основной язык
        m_lang = self.main_lang.currentText()
        #База данных
        db_user = self.db_user.text()
        db_pass = self.db_pass.text()
        db_name = self.db_name.text()

        # Путь к файлу переводов
        file_translates = self.file_path.text()

        #Корневая директория шаблонов Laravel
        laravelRootDir = self.laravelRootDir.text()

        #Плейсхолдеры
        l_placeholder = self.l_placeholder.text()
        r_placeholder = self.r_placeholder.text()
        leftLaravelPlaceholder = self.leftLaravelPlaceholder.text()
        rightLaravelPlaceholder = self.rightLaravelPlaceholder.text()

        #Подтверждение сохранения настроек
        buttonReply = QtWidgets.QMessageBox.question(
            self, 'Изменение настроек', "Сохранить выбранные настройки?",
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        if buttonReply == QtWidgets.QMessageBox.Yes:
            settings = configparser.ConfigParser()

            settings['GENERAL'] = {
                'LANGS': '|'.join(langs),
                'MAIN_LANG': m_lang,
            }

            settings['MODX'] = {
                'FILE_TRANSLATES': file_translates,
                'LEFT_PLACEHOLDER': l_placeholder,
                'RIGHT_PLACEHOLDER': r_placeholder,
            }

            settings['LARAVEL'] = {
                'LEFT_LARAVEL_PLACEHOLDER': leftLaravelPlaceholder,
                'RIGHT_LARAVEL_PLACEHOLDER': rightLaravelPlaceholder,
                'ROOT_DIR': laravelRootDir,
            }

            settings['DB'] = {
                'DB_USER': db_user,
                'DB_NAME': db_name,
                'DB_PASS': db_pass,
            }
            with open(self.settings_path, "w") as config_file:
                settings.write(config_file)
            self.load_settings()

    def filter_values(self, x):
        if (re.findall(
                r'^{{.+}}$|^{!!.+!!}$|^@|^{{\s.+}}|^:{{.+}}$|^\+{{.+}}$', x)):
            return 0
        return 1

    ################------------------------####################
    ############****Запускаем работу скрипта****################
    ################------------------------####################
    def click_btn_run(self):
        # Получаем все переводы из файла
        translate_path = Path(self.setting_file_translates)
        try:
            translate_path.owner()
            translate_file_content = check_output([
                'php', '-r', 'include "' + self.setting_file_translates +
                '"; echo json_encode($l);'
            ])
            translate_file_content = json.loads(translate_file_content)

            # Введенный фрагмент
            self.input = self.output = self.main_input.toPlainText()
            soup = BeautifulSoup(self.input, 'html.parser')
            for script in soup(["script", "style"]):
                script.extract()  # rip it out
            text = soup.get_text()
            # break into lines and remove leading and trailing space on each
            lines = (line.strip() for line in text.splitlines())
            # break multi-headlines into a line each
            chunks = [c for c in filter(None, lines)]

            chunks = filter(self.filter_values, chunks)
            for v in chunks:
                print(v)
            sys.exit(0)

            # Массив с переводами которые уже есть в БД (и которые не нужно будет переводить)
            exist_translates = DB.check_translates(self.setting_db_name,
                                                   self.setting_db_user,
                                                   self.setting_db_pass,
                                                   self.setting_main_lang,
                                                   chunks)

            # Подставляем ID существующих переводов, и удаляем эти элементы из списка (chunks)
            if (len(exist_translates) > 0):
                for translate in exist_translates:
                    self.output = self.output.replace(
                        translate[self.setting_main_lang],
                        str(self.setting_l_placeholder) +
                        str(translate['lang_id']) +
                        str(self.setting_r_placeholder))
                    chunks.pop(chunks.index(translate[self.setting_main_lang]))

            # Перебираем оставщиеся строки, требующие перевода
            translator = Translator()
            translator.session.proxies['http'] = '125.26.109.83:8141'
            translator.session.proxies['http'] = '98.221.88.193:64312'
            translator.session.proxies['http'] = '188.244.35.162:10801'
            translator.session.proxies['http'] = '185.162.0.110:10801'

            # языки
            langs = self.setting_langs.split('|')

            # Прогресс бар
            i = 0
            self.progressBar.setMaximum(len(chunks) + 1)
            # Прогресс бар

            for item in chunks:

                # Прогресс бар
                i += 1
                self.progressBar.setValue(i)
                # Прогресс бар

                translate_file_string = []
                translate_dic = {}
                translate_dic[self.setting_main_lang] = item

                # строка для файла переводов
                translate_file_string = []
                for lang in langs:
                    new_translate = translator.translate(
                        item, src=self.setting_main_lang, dest=lang).text
                    translate_dic[lang] = new_translate  # Пауза для гугла
                    sleep(3)

                # для запроса в базу (корректировка языков)
                correct_lang_sql = []
                # значения для записи в базу
                string_sql_values = []
                for item in translate_dic.items():
                    print(item[0] + '--------' + item[1])
                    correct_lang_sql.append(DB.lang_field_connector(item[0]))
                    string_sql_values.append("'" + item[1] + "'")
                    # Строка для записи в файл переводов
                    translate_file_string.append('"' + item[0] + '": "' +
                                                 item[1] + '"')
                langs_sql = ','.join(correct_lang_sql)
                string_sql_values = ','.join(string_sql_values)

                # Запись в БД
                sql = "INSERT INTO modx_a_lang (" + langs_sql + ") VALUES (" + string_sql_values + ");"
                # values = (translate_dic["uk"], translate_dic["ru"], translate_dic["en"]);
                last_id = DB.add_translate(self.setting_db_name,
                                           self.setting_db_user,
                                           self.setting_db_pass, sql)

                # Запись в файл переводов
                translate_file_string = '{' + ','.join(
                    translate_file_string) + '}'
                translate_file_string = json.loads(translate_file_string)

                # Добавление нового перевода в строку json переводов
                translate_file_content[last_id] = translate_file_string
                self.output = self.output.replace(
                    translate_dic[self.setting_main_lang],
                    "[#" + str(last_id) + "#]")

            self.write_to_file(translate_file_content,
                               self.setting_file_translates)
            # subprocess.call(['chmod', '0777', '"' + self.setting_file_translates + '"'])
            self.main_input.setPlainText(self.output)
            # Информационное сообщение о завершении работы
            self.showMessage(
                "Перевод завершен!",
                "Перевод фрагмента html выполнен. Теперь вы можете его скопировать и добавить в свой шаблон!",
                'info')
        except FileNotFoundError as f:
            self.showMessage('Ошибка!', 'Не верно указан путь к файлу!',
                             'critical')

    ################------------------------####################
    ############**********Запись в файл*********################
    ################------------------------####################
    def write_to_file(self,
                      json_string,
                      path="D:\OSPanel\domains\shop.loc\dump.php"):
        f = codecs.open(path, "w+", "utf-8")
        f.write('<?php \n $l=[')
        tr_strings = []
        for l_id, value in json_string.items():
            single_tr = str(l_id) + "=>["
            # Массив переводов одного слова(предложения)
            tr_langs = []
            for lang, v in value.items():
                tr_langs.append("'" + lang + "'=>'" + v + "'")
            # Массив переводов строк
            single_tr += ','.join(tr_langs) + "],"
            f.write(single_tr)
        f.write('];')
        f.close()
        return True

    #########****************************************###########
    #########****Показать сообщение пользователю*****###########
    #########****************************************###########
    def showMessage(self, title, message, icon):
        icons = {
            'info': QtWidgets.QMessageBox.Information,
            'warning': QtWidgets.QMessageBox.Warning,
            'critical': QtWidgets.QMessageBox.Critical,
        }
        self.msg.setIcon(icons[icon])
        self.msg.setWindowTitle(title)
        self.msg.setText(message)
        self.msg.exec_()
コード例 #14
0
ファイル: equations_solver.py プロジェクト: Ferenecruma/PyQt5
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")
        self.is_added = False

        self.main_layout = QVBoxLayout()
        first_input = QHBoxLayout()
        
        hint = create_hint("Введіть m та n:")
        self.main_layout.addWidget(hint)

        self.m_input = QSpinBox()
        self.n_input = QSpinBox()

        first_input.addWidget(self.m_input)
        first_input.addWidget(self.n_input)

        self.button_pass_args = QPushButton()
        self.button_pass_args.setText("Ввести")
        self.button_pass_args.clicked.connect(self.the_button_was_clicked)
        
        first_input.addWidget(self.button_pass_args)
        firs_input_widget = QWidget()
        firs_input_widget.setLayout(first_input)
        self.main_layout.addWidget(firs_input_widget)

        main_widget = QWidget()
        main_widget.setLayout(self.main_layout)

        self.setCentralWidget(main_widget)
    
    def the_button_was_clicked(self):
        """ 
        Slot for processing signal from
        first button, that adds input
        matrix and vector of right dimension
        to the main layout.
        """
        if self.is_added:
            self.delete_from_main_layout()
        else:
            self.is_added = True

        self.m, self.n = int(self.m_input.cleanText()), int(self.n_input.cleanText())

        self.matrix, self.matrix_layout = self.create_matrix_input(self.m, self.n)
        self.vector_b, self.vector_layout = self.create_matrix_input(self.m, 1)
        hint = create_hint("Введіть вектор b:")
        
        self.button_compute = QPushButton()
        self.button_compute.setText("Знайти розвязок")
        self.button_compute.clicked.connect(self.compute_result)

        self.main_layout.addWidget(create_hint('Введіть матрицю A:'))
        self.main_layout.addWidget(self.matrix)
        self.main_layout.addWidget(hint)
        self.main_layout.addWidget(self.vector_b)
        self.main_layout.addWidget(self.button_compute)

    def create_matrix_input(self, m, n):
        """
        Creating input matrix of 
        spinBoxes with (m, n) shape
        """

        layout = QGridLayout()

        for i in range(m):
            for j in range(n):
                spin_box = QDoubleSpinBox()
                spin_box.setMinimum(-99.99)
                layout.addWidget(spin_box, i, j)

        widget = QWidget()
        widget.setLayout(layout)
        return widget, layout

    def get_data_from_table(self, layout, m, n):
        data = np.zeros((m,n))
        for i in range(m):
            for j in range(n):
                item = layout.itemAtPosition(i, j).widget()
                data[i, j] = float(item.cleanText().replace(',','.'))
        return data
    
    def compute_result(self):
        matrix = self.get_data_from_table(self.matrix_layout, self.m, self.n)
        vector_b = self.get_data_from_table(self.vector_layout, self.m, 1)
        try:
            res = np.linalg.solve(matrix, vector_b)
            message = "Знайшовся точний розвязок!"
        except:
            try:
                inv_A = np.linalg.pinv(matrix)

                def param_funcion(v=np.zeros((self.n, 1))):
                    return inv_A.dot(vector_b) + v - inv_A.dot(matrix.dot(v))
                
                res = param_funcion
                message = "Не вдалося знайти точний розвязок.Знайшовся приблизний."
            except:
                res = None
                message = "Не вдалося знайти жодного розвязку системи."

        self.display_result(res, message)
        
    def display_result(self, result, message):
        self.result_w = ResultWindow(result=result, message=message)
        self.result_w.show()
    
    def delete_from_main_layout(self):
        """
        Clearing layout from widgets
        after updating m and n
        """
        items = []
        for i in range(2, self.main_layout.count()):
            items.append(self.main_layout.itemAt(i).widget())
        for widget in items:
            widget.hide()
            self.main_layout.removeWidget(widget)
コード例 #15
0
ファイル: MainWindow.py プロジェクト: Sikorskyyy/nice_backup
class MainWindow(QMainWindow):
    
    def __init__(self, parent=None):

        super(MainWindow, self).__init__(parent)
        centralWidget = QWidget()
        self.mainLayout = QVBoxLayout()
        buttonLayout = QHBoxLayout()
        foldersLayout = QHBoxLayout()
        backupFolderLayout = QHBoxLayout()
        self.usbDevicesChooser = QComboBox()
        
        usb_util = Utils()
        self.usbDevices = usb_util.get_storage_device()

        for device in self.usbDevices:
            self.usbDevicesChooser.addItem(device.__str__())

        self.pathToFolders = QLineEdit()
        self.pathToFolders.setPlaceholderText("Path to folders you want to backup")
        self.pathToBackupFolder = QLineEdit()
        self.pathToBackupFolder.setPlaceholderText("Path to backup destination folder")

        self.browseFoldersButton = QPushButton("Browse...")
        self.browseFoldersButton.clicked.connect(self.on_browseFolders_clicked)
        self.browseBackupFolderButton = QPushButton("Browse...")
        self.browseBackupFolderButton.clicked.connect(self.on_browseBackupFolder_clicked)

        foldersLayout.addWidget(self.pathToFolders)
        foldersLayout.addWidget(self.browseFoldersButton)
        foldersLayout.setSpacing(5)

        backupFolderLayout.addWidget(self.pathToBackupFolder)
        backupFolderLayout.addWidget(self.browseBackupFolderButton)
        backupFolderLayout.setSpacing(5)

        self.startBackupButton = QPushButton("Start Backup")
        self.startBackupButton.clicked.connect(self.on_startBackup_clicked)

        self.exitButton = QPushButton("Exit")
        self.exitButton.clicked.connect(self.on_exit_clicked)

        buttonLayout.addWidget(self.startBackupButton)
        buttonLayout.addWidget(self.exitButton)
        buttonLayout.setSpacing(10)

        self.mainLayout.addWidget(self.usbDevicesChooser)
        self.mainLayout.addLayout(backupFolderLayout)
        self.mainLayout.addLayout(foldersLayout)
        self.mainLayout.addLayout(buttonLayout)

        centralWidget.setLayout(self.mainLayout)
        self.setCentralWidget(centralWidget)
        self.setWindowTitle("Nice Backup")
        self.setMinimumSize(600, 200)

    def on_exit_clicked(self, widget):
        sys.exit()

    def on_browseFolders_clicked(self, widget):
        index = self.usbDevicesChooser.currentIndex()
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.DirectoryOnly)
        file_dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        file_view = file_dialog.findChild(QListView, 'listView')

        if file_view:
            file_view.setSelectionMode(QAbstractItemView.MultiSelection)

        ftree_view = file_dialog.findChild(QTreeView)

        if ftree_view:
            ftree_view.setSelectionMode(QAbstractItemView.MultiSelection)

        file_dialog.setDirectory(self.usbDevices[index].getPath())

        if file_dialog.exec():
            paths = file_dialog.selectedFiles()

        self.pathToFolders.setText(";".join(paths))

    def on_browseBackupFolder_clicked(self, widget):
        fname = QFileDialog.getExistingDirectory(self.window(), 'Open file', '/home/{}'.format(getpass.getuser()))
        self.pathToBackupFolder.setText(fname)

    def on_startBackup_clicked(self, widget):
        print("Starting backup")
        backuper = Backuper.Backuper()
        sources = self.pathToFolders.text().split(";")
        destination = self.pathToBackupFolder.text()

        progress = QProgressBar()
        progress.setMinimum(0)
        progress.setMaximum(len(sources))
        self.mainLayout.addWidget(progress)

        for source in sources:
            backuper.make_backup(source, destination)
            progress.setValue(sources.index(source))
            QApplication.processEvents()
        doneDialog = QMessageBox()

        doneDialog.setIcon(QMessageBox.Information)
        doneDialog.setText("Copying data is completed")
        doneDialog.setWindowTitle("Copy event")
        doneDialog.setStandardButtons(QMessageBox.Ok)

        index = self.mainLayout.indexOf(progress)
        self.mainLayout.itemAt(index).widget().setParent(None)

        doneDialog.exec()
コード例 #16
0
class Popup(QDialog):
    def __init__(self, schedule: Schedule, parent=None, data=None):
        super(Popup, self).__init__(parent)
        self.schedule = schedule
        self.data, self.class_name = data if data is not None else (None, None)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.setWindowTitle("Add New Scheduled Notes" if data is None else
                            "Edit {} Details".format(self.class_name))

        self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        self.form_layout = QFormLayout()
        self.form_layout.setContentsMargins(0, 0, 0,
                                            self.form_layout.verticalSpacing())
        self.form_layout_widget = QWidget()
        self.form_layout_widget.setLayout(self.form_layout)

        #The amount of fields in the form that come before the block section (name, #blocks, start, end date, color)
        self.rows_before_blocks = 3

        self.event_type = QPushButton()
        event_type_menu = QMenu()
        event_type_menu.addAction("Class")
        event_type_menu.addSection("Event")
        event_type_menu.addAction("One Time Event")
        event_type_menu.addAction("Recurring Event")
        event_type_menu.addAction("One Time Class Event")
        for action in event_type_menu.actions():
            if not action.isSeparator():
                action.triggered.connect(
                    lambda state, x=action.text(): self.set_type(x))
        self.event_type.setMenu(event_type_menu)
        self.form_layout.addRow("Type:", self.event_type)

        #Class Title
        self.name_edit = QLineEdit()
        self.form_layout.addRow("Name:", self.name_edit)
        #Color
        self.color_picker = QColorDialog()
        self.color_button = QPushButton("Pick Color")
        self.color_button.clicked.connect(self.color_picker.open)
        self.color_picker.currentColorChanged.connect(self.update_color)
        self.form_layout.addRow("Color Code:", self.color_button)

        # Initialize widgets to be added later
        self.start_date_model = DateTimePickerSeriesModel(self)
        self.class_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")
        self.event_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")

        self.end_date_model = DateTimePickerSeriesModel(self)
        self.class_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")
        self.event_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")

        self.event_date_model = DateTimePickerSeriesModel(self)
        self.class_event_date = DateTimePickerSeries(self.event_date_model,
                                                     "MMM d yyyy hh:mm:AP")
        self.event_date = DateTimePickerSeries(self.event_date_model,
                                               "MMM d yyyy hh:mm:AP")

        # Blocks
        self.blocks = 1
        self.spin_box = QSpinBox()
        self.spin_box.setValue(1)
        self.spin_box.setMinimum(1)
        self.spin_box.setMaximum(7)
        self.spin_box.valueChanged.connect(self.update_blocks)

        self.class_picker = QPushButton()
        class_picker_menu = QMenu()
        for class_name in self.schedule.schedule.keys():
            class_action = QAction(class_name, parent=class_picker_menu)
            class_action.triggered.connect(lambda state, x=class_action.text():
                                           self.class_picker.setText(x))
            class_picker_menu.addAction(class_action)
        class_picker_menu.aboutToShow.connect(
            lambda: class_picker_menu.setMinimumWidth(self.class_picker.width(
            )))
        self.class_picker.setMenu(class_picker_menu)

        self.stack = QStackedWidget()
        self.stack.setContentsMargins(0, 0, 0, 0)

        class_layout = QFormLayout()
        class_layout.setContentsMargins(0, 0, 0,
                                        class_layout.verticalSpacing())
        class_layout.addRow("Start Date:", self.class_start_date)
        class_layout.addRow("End Date:", self.class_end_date)
        class_layout.addRow("Weekly Blocks:", self.spin_box)
        class_layout.addRow("Block Time:", ClassTimePicker())
        self.class_options = QWidget()
        self.class_options.setSizePolicy(QSizePolicy.Ignored,
                                         QSizePolicy.Ignored)
        self.class_options.setLayout(class_layout)

        recurring_event_layout = QFormLayout()
        recurring_event_layout.setContentsMargins(
            0, 0, 0, recurring_event_layout.verticalSpacing())
        recurring_event_layout.addRow("Start Date:", self.event_start_date)
        recurring_event_layout.addRow("End Date:", self.event_end_date)
        self.recurring_event_time_picker = ClassTimePicker()
        recurring_event_layout.addRow("Event Time:",
                                      self.recurring_event_time_picker)
        self.recurring_event_options = QWidget()
        self.recurring_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                   QSizePolicy.Ignored)
        self.recurring_event_options.setLayout(recurring_event_layout)

        one_time_event_layout = QFormLayout()
        one_time_event_layout.setContentsMargins(
            0, 0, 0, one_time_event_layout.verticalSpacing())
        one_time_event_layout.addRow("Event Date:", self.event_date)
        self.one_time_event_options = QWidget()
        self.one_time_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                  QSizePolicy.Ignored)
        self.one_time_event_options.setLayout(one_time_event_layout)

        class_event_layout = QFormLayout()
        class_event_layout.setContentsMargins(
            0, 0, 0, class_event_layout.verticalSpacing())
        class_event_layout.addRow("Class:", self.class_picker)
        class_event_layout.addRow("Event Date:", self.class_event_date)
        self.class_event_options = QWidget()
        self.class_event_options.setSizePolicy(QSizePolicy.Ignored,
                                               QSizePolicy.Ignored)
        self.class_event_options.setLayout(class_event_layout)

        self.stack.addWidget(self.class_event_options)
        self.stack.addWidget(self.one_time_event_options)
        self.stack.addWidget(self.recurring_event_options)
        self.stack.addWidget(self.class_options)

        self.set_type("Class")

        self.layout.addWidget(self.form_layout_widget)
        self.layout.addWidget(self.stack)
        self.setLayout(self.layout)
        self.show_buttons()

        #Update Values if self.data is defined
        if self.data is not None:
            self.name_edit.setText(self.data["name"])
            self.start_date.setDate(to_qdate(self.data["start"]))
            self.end_date.setDate(to_qdate(self.data["end"]))
            self.color_picker.setCurrentColor(to_qcolor(self.data["color"]))
            self.spin_box.setValue(len(self.data["blocks"]))
            for i in range(0, len(self.data["blocks"])):
                w: ClassTimePicker = self.layout.itemAt(
                    self.rows_before_blocks + i,
                    QFormLayout.FieldRole).widget()
                block = self.data["blocks"][i]
                w.set_day(block["day"])
                w.set_time(block["time"])

    def show_buttons(self):
        buttonBox = QDialogButtonBox(QDialogButtonBox.Save
                                     | QDialogButtonBox.Cancel,
                                     parent=self)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        buttonBox.setOrientation(Qt.Horizontal)
        self.layout.addWidget(buttonBox)

    def set_type(self, event_type: str):
        if self.event_type.text() == event_type:
            return
        self.event_type.setText(event_type)
        self.stack.currentWidget().setSizePolicy(QSizePolicy.Ignored,
                                                 QSizePolicy.Ignored)
        if event_type == "Class":
            self.class_options.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Expanding)
            self.class_options.adjustSize()
            self.stack.setCurrentWidget(self.class_options)
        elif event_type == "Recurring Event":
            self.recurring_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                       QSizePolicy.Expanding)
            self.recurring_event_options.adjustSize()
            self.stack.setCurrentWidget(self.recurring_event_options)
        elif event_type == "One Time Event":
            self.one_time_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                      QSizePolicy.Expanding)
            self.one_time_event_options.adjustSize()
            self.stack.setCurrentWidget(self.one_time_event_options)
        elif event_type == "One Time Class Event":
            self.class_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                   QSizePolicy.Expanding)
            self.class_event_options.adjustSize()
            self.stack.setCurrentWidget(self.class_event_options)
        self.stack.adjustSize()
        max_width = 0
        for i in range(self.form_layout.rowCount()):
            widget = self.form_layout.itemAt(i, QFormLayout.LabelRole).widget()
            widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
            widget.adjustSize()
            max_width = max(widget.size().width(), max_width)
        # noinspection PyTypeChecker
        current_widget_layout: QFormLayout = self.stack.currentWidget().layout(
        )
        for i in range(current_widget_layout.rowCount()):
            widget = current_widget_layout.itemAt(
                i, QFormLayout.LabelRole).widget()
            widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
            widget.adjustSize()
            max_width = max(widget.size().width(), max_width)
        for i in range(self.form_layout.rowCount()):
            self.form_layout.itemAt(
                i, QFormLayout.LabelRole).widget().setMinimumWidth(max_width)
        for i in range(current_widget_layout.rowCount()):
            current_widget_layout.itemAt(
                i, QFormLayout.LabelRole).widget().setMinimumWidth(max_width)
        self.adjustSize()

    def update_color(self):
        self.color_button.setStyleSheet(
            "background-color: rgb({},{},{})".format(
                self.color_picker.currentColor().red(),
                self.color_picker.currentColor().green(),
                self.color_picker.currentColor().blue()))

    def update_blocks(self, value):
        if self.blocks == value:
            return
        old_blocks = self.blocks
        self.blocks = value
        class_options_layout: QFormLayout = self.class_options.layout()
        if self.blocks > old_blocks:
            #Change label of block 1
            if old_blocks == 1:
                class_options_layout.itemAt(
                    self.rows_before_blocks,
                    QFormLayout.LabelRole).widget().setText("Block 1 Time:")
            for i in range(1, self.blocks - old_blocks + 1):
                offset = self.rows_before_blocks + old_blocks + i - 1
                widget = class_options_layout.itemAt(offset,
                                                     QFormLayout.FieldRole)
                label = class_options_layout.itemAt(offset,
                                                    QFormLayout.LabelRole)
                if widget is not None and label is not None:
                    widget = widget.widget()
                    label = label.widget()
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
                    label.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
                    widget.adjustSize()
                    label.adjustSize()
                    widget.show()
                    label.show()
                else:
                    picker = ClassTimePicker()
                    picker.sizePolicy().setRetainSizeWhenHidden(False)
                    class_options_layout.addRow(
                        "Block {} Time:".format(old_blocks + i), picker)
        elif self.blocks < old_blocks:
            if self.blocks == 1:
                class_options_layout.itemAt(
                    self.rows_before_blocks,
                    QFormLayout.LabelRole).widget().setText("Block Time:")
            for i in range(old_blocks - self.blocks):
                offset = self.rows_before_blocks + old_blocks + i - 1
                widget = class_options_layout.itemAt(
                    offset, QFormLayout.FieldRole).widget()
                label = class_options_layout.itemAt(
                    offset, QFormLayout.LabelRole).widget()
                print(widget.size())
                widget.hide()
                label.hide()
                widget.adjustSize()
                label.adjustSize()
                self.class_options.adjustSize()
                self.stack.adjustSize()
                self.adjustSize()

                print(widget.size())

        # self.class_options.adjustSize()
        # self.stack.adjustSize()
        # self.adjustSize()

    def get_name(self):
        return self.name_edit.text()

    def get_data(self):
        event_type = self.event_type.text()
        data = {
            "type": event_type.lower(),
            "name": self.get_name(),
            "color": {
                "r": self.color_picker.currentColor().red(),
                "g": self.color_picker.currentColor().green(),
                "b": self.color_picker.currentColor().blue(),
            }
        }
        if event_type == "Class":
            block_data = []
            # noinspection PyTypeChecker
            class_layout: QFormLayout = self.stack.currentWidget().layout()
            for row in range(self.rows_before_blocks, class_layout.rowCount()):
                # noinspection PyTypeChecker
                block_widget: ClassTimePicker = class_layout.itemAt(
                    row, QFormLayout.FieldRole).widget()
                if block_widget.isHidden():
                    continue
                time = block_widget.get_time()
                block_data.append({
                    "day": block_widget.day_picker.get_day(),
                    "time": {
                        "hour": time.hour(),
                        "minute": time.minute()
                    }
                })
            data["blocks"] = block_data
        if event_type in ["Class", "Recurring Event"]:
            start_date = self.start_date_model.content.date()
            data["start"] = {
                "day": start_date.day(),
                "month": start_date.month(),
                "year": start_date.year()
            }
            end_date = self.end_date_model.content.date()
            data["end"] = {
                "day": end_date.day(),
                "month": end_date.month(),
                "year": end_date.year()
            }
        if event_type == "Recurring Event":
            data["day"] = self.recurring_event_time_picker.day_picker.get_day()
            time = self.recurring_event_time_picker.get_time()
            data["time"] = {"hour": time.hour(), "minute": time.minute()}
        if event_type == "One Time Class Event":
            data["class_name"] = self.class_picker.text()
        if event_type in ["One Time Event", "One Time Class Event"]:
            date_time = self.event_date_model.content
            date = date_time.date()
            time = date_time.time()
            data["date"] = {
                "day": date.day(),
                "month": date.month(),
                "year": date.year(),
            }
            data["time"] = {"hour": time.hour(), "minute": time.minute()}
        return data

    def accept(self):
        event_type = self.event_type.text()
        if event_type == "":
            error = QMessageBox()
            error.setText("Please select a type for the event.")
            error.exec_()
            self.event_type.setFocus()
            return
        # Check Name
        if len(self.get_name()) == 0:
            error = QMessageBox()
            error.setText("Please enter a name for the event.")
            error.exec_()
            self.name_edit.setFocus()
            return
        if event_type in ["Class", "Recurring Event"]:
            # Check Start/End Date
            start_date = self.start_date_model.content.date()
            end_date = self.end_date_model.content.date()
            if start_date >= end_date:
                error = QMessageBox()
                error.setText("End date cannot {} start date.".format(
                    "be equal to" if start_date ==
                    end_date else "come before"))
                error.exec_()
                if event_type == "Class":
                    self.class_end_date.setFocus()
                else:
                    self.event_end_date.setFocus()
                return
            if event_type == "Class":
                # Check Blocks
                # noinspection PyTypeChecker
                class_layout: QFormLayout = self.stack.currentWidget().layout()
                print(class_layout)
                for row in range(self.rows_before_blocks,
                                 class_layout.rowCount()):
                    block_widget = class_layout.itemAt(
                        row, QFormLayout.FieldRole).widget()
                    if block_widget.isHidden():
                        continue
                    # Make sure a day is selected for each block
                    if not block_widget.is_valid():
                        block_name = "the class block" if self.blocks == 1 else str.lower(
                            class_layout.itemAt(row, QFormLayout.LabelRole).
                            widget().text()).replace(" time:", "")
                        error = QMessageBox()
                        error.setText(
                            "Please select a valid day for {}.".format(
                                block_name))
                        error.exec_()
                        return
                    # Check for duplicate blocks
                    for other in range(self.rows_before_blocks,
                                       class_layout.rowCount() - 1):
                        if row == other:
                            continue
                        other_block_widget = class_layout.itemAt(
                            other, QFormLayout.FieldRole).widget()
                        same_time = block_widget.get_time(
                        ) == other_block_widget.get_time()
                        same_day = block_widget.day_picker.get_day(
                        ) == other_block_widget.day_picker.get_day()
                        if same_time and same_day:
                            error = QMessageBox()
                            error.setText(
                                "Block {} and {} cannot have the same day and time."
                                .format(row - self.rows_before_blocks + 1,
                                        other - self.rows_before_blocks + 1))
                            error.exec_()
                            return
            if event_type == "Recurring Event":
                # Make sure a day is selected
                if not self.recurring_event_time_picker.is_valid():
                    error = QMessageBox()
                    error.setText("Please select a valid day for this event.")
                    error.exec_()
                    self.recurring_event_time_picker.setFocus()
                    return
        if event_type == "One Time Class Event":
            # Check Class
            if len(self.class_picker.text()) == 0:
                error = QMessageBox()
                error.setText("Please select a class for this event.")
                error.exec_()
                self.class_picker.setFocus()
                return
        if self.data is not None:
            error = QMessageBox()
            error.setText(
                "Changes will not be saved because this feature is incomplete."
            )
            error.exec_()
            super(Popup, self).reject()
        # Valid name
        elif self.get_name() in self.schedule.schedule.keys():
            error = QMessageBox()
            error.setText(
                "An event with this name already exists, would you like to overwrite it?"
            )
            error.setStandardButtons(error.Apply | error.Cancel)
            result = error.exec_()
            if result == error.Apply:
                self.schedule.edit_event(self.get_data())
                self.reject()
            elif result == error.Cancel:
                self.name_edit.setFocus()
        super(Popup, self).accept()

    def reject(self):
        super(Popup, self).reject()
コード例 #17
0
class TaskAddEditor(QDialog):

    #initialize everything
    def __init__(self, dialog_name, button_name, identifier=None):
        super(TaskAddEditor, self).__init__()
        self.dialog_name = dialog_name
        self.button_name = button_name
        self.identifier = identifier

        self.setGeometry(50, 50, 300, 250)

        self.tabs = QTabWidget()
        self.tabs.tab_1 = QWidget()
        self.tabs.tab_2 = QWidget()

        self.tabs.addTab(self.tabs.tab_1, "Basic Info")
        self.tabs.addTab(self.tabs.tab_2, "Notifications")

        self.tab_1()
        self.tab_2()

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.tabs)

        buttons = QHBoxLayout()

        button_ok = QPushButton(self.button_name)
        button_close = QPushButton("Cancel")
        button_ok.clicked.connect(self.dialog_button_click)
        button_close.clicked.connect(self.dialog_cancel_click)
        buttons.addWidget(button_ok)
        buttons.addWidget(button_close)

        main_layout.addLayout(buttons)

        self.setLayout(main_layout)

        self.setWindowTitle(dialog_name)
        self.exec_()

    def tab_1(self):
        # main layout
        layout = QVBoxLayout()

        task_name = QLabel('Task Name')
        due_date = QLabel('Due Date')
        due_time = QLabel('Due Time')

        if (self.button_name == "Add"):
            self.task_name_input = QLineEdit()
            self.due_date_input = QDateEdit()
            self.due_date_input.setMinimumDate(QDate.currentDate())
            self.due_time_input = QTimeEdit()

        else:

            task_info = user_tasks.get_task(self.identifier)

            self.task_name_input = QLineEdit(task_info[1])
            self.due_date_input = QDateEdit(task_info[2].date())
            self.due_date_input.setMinimumDate(QDate.currentDate())
            self.due_time_input = QTimeEdit(task_info[2].time())

        layout.addWidget(task_name)
        layout.addWidget(self.task_name_input)
        layout.addWidget(due_date)
        layout.addWidget(self.due_date_input)
        layout.addWidget(due_time)
        layout.addWidget(self.due_time_input)
        layout.addSpacing(20)

        self.tabs.tab_1.setLayout(layout)

    def tab_2(self):
        layout = QVBoxLayout()

        page_name = QLabel('Notification Settings')
        layout.addWidget(page_name)

        add_notification_area = QHBoxLayout()

        description = QLabel('Remind Me Everyday At: ')
        self.time_input = QTimeEdit()
        add_notification = QPushButton('+')
        add_notification.setFixedSize(30, 30)
        add_notification.clicked.connect(self.add_notification)

        add_notification_area.addWidget(description)
        add_notification_area.addWidget(self.time_input)
        add_notification_area.addWidget(add_notification)

        layout.addLayout(add_notification_area)

        your_notifications = QLabel('Your Notifications:')

        layout.addWidget(your_notifications)

        #create a scroll area to hold notifications
        notifications_area = QScrollArea(self)
        notifications_area.setWidgetResizable(True)
        widget = QWidget()
        notifications_area.setWidget(widget)
        self.notifications_layout = QVBoxLayout(widget)
        notifications_area.setAlignment(Qt.AlignTop)
        self.notifications_layout.setAlignment(Qt.AlignTop)

        layout.addWidget(notifications_area)

        if self.identifier is not None:

            #get a list of datetime objects
            notifications = user_tasks.get_notifications(self.identifier)

            #add notifications to the tab
            for notification_date in notifications:
                self.notifications_layout.addWidget(
                    Notification(notification_date))

        self.tabs.tab_2.setLayout(layout)

    def add_notification(self):
        # adds a notification to the layout of notifications
        for index in range(self.notifications_layout.count()):
            if ((self.notifications_layout.itemAt(
                    index).widget().notification_time) >
                (self.time_input.time().toPyTime())):
                self.notifications_layout.insertWidget(
                    index, Notification(self.time_input.time().toPyTime()))
                return
            elif (self.notifications_layout.itemAt(index).widget().
                  notification_time) == self.time_input.time().toPyTime():
                error = QMessageBox()
                error.setText("Time Already Set")
                error.exec_()
                return

        self.notifications_layout.addWidget(
            Notification(self.time_input.time().toPyTime()))

    def dialog_button_click(self):
        # when add is pressed
        if (input_error_box(self.due_time_input, self.due_date_input,
                            self.task_name_input)):

            notification_dates = []
            for notification in range(self.notifications_layout.count()):
                notification_dates.append(
                    self.notifications_layout.itemAt(
                        notification).widget().notification_time)

            if (self.button_name == 'Add'):
                print(notification_dates)
                user_tasks.add_task(
                    self.task_name_input.text(),
                    datetime.combine(self.due_date_input.date().toPyDate(),
                                     self.due_time_input.time().toPyTime()),
                    datetime.today(), str(uuid.uuid4()), notification_dates)
            else:
                print(notification_dates)
                user_tasks.edit_task(
                    self.identifier, self.task_name_input.text(),
                    datetime.combine(self.due_date_input.date().toPyDate(),
                                     self.due_time_input.time().toPyTime()),
                    notification_dates)

            self.reject()
            gui_window.refresh_tasks()

    def dialog_cancel_click(self):
        #used in the input window and closes it
        self.reject()
コード例 #18
0
class LiveWidget(QWidget):
    """

    """
    def __init__(self):
        """

        """
        super(LiveWidget, self).__init__()

        self.pot_btn = QPushButton('PotPlayer播放')

        self.vlc_btn = QPushButton('VLC播放')
        self.vlc_widget = VLCWidget()

        self.player_widget = QWidget()
        self.player_layout = QVBoxLayout()
        self._layout = QVBoxLayout()

        self.set_player_widget()

        self.init_ui()

    def init_ui(self):
        """

        :return:
        """
        # player_layout = QVBoxLayout()
        self.player_layout.setContentsMargins(0, 0, 0, 0)
        self.player_layout.setSpacing(0)
        self.player_layout.addWidget(self.player_widget)

        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        main_layout.addLayout(self.player_layout)
        self.setLayout(main_layout)

        self.setStyleSheet(
            "background-image:url(./resources/img/live_null.png); ")

    def clear_layout(self):
        """

        :return:
        """
        for i in range(self._layout.count()):
            print("i {0}".format(i))
            self._layout.removeItem(self._layout.itemAt(i))
        self._layout.setParent(None)
        self.player_layout.removeItem(self._layout)

    def set_widget_visible(self, visible):
        """

        :return:
        """
        if visible:
            # self.vlc_widget.setVisible(True)
            self.vlc_widget.show()
        else:
            # self.vlc_widget.setVisible(False)
            self.vlc_widget.hide()

    def set_player_widget(self, widget=False):
        """

        :param widget:
        :return:
        """
        # self.clear_layout()

        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        self._layout.addWidget(self.vlc_widget)

        self.set_widget_visible(widget)

        self.player_widget.setLayout(self._layout)
コード例 #19
0
class App(QWidget):

    #initialize all of the variables and call gui functions
    def __init__(self):
        super(App, self).__init__()
        self.setWindowTitle('v1.4.0')
        self.setGeometry(300, 200, 600, 600)
        self.create_task_area()
        self.vertical_layout = QVBoxLayout(self)
        self.vertical_layout.addLayout(self.create_header())
        self.vertical_layout.addWidget(self.tasks_area)
        self.show()

        self.refresh_tasks()

        timer = QTimer(self)
        timer.timeout.connect(self.countdown_update)
        timer.start(100)

    def create_header(self):
        # create the header for the gui (i dont think it needs to be it's own function tbh, might change later)

        header_layout = QHBoxLayout()
        btn_add_task = QPushButton('+')
        btn_add_task.setFixedSize(40, 40)
        btn_add_task.clicked.connect(
            lambda: TaskAddEditor('Add a task', 'Add', None))
        task_label = QLabel('Add Task')
        header_layout.addWidget(btn_add_task)
        header_layout.addWidget(task_label)

        sort_by_menu = QLabel('Sort By')

        sort_by = QComboBox()
        sort_by.addItems(
            ["Alphabetic", "Date Created", "Furthest Due Date", "Time Left"])
        sort_by.currentIndexChanged.connect(self.sort_by_func)
        header_layout.addStretch()
        header_layout.addWidget(sort_by_menu)
        header_layout.addWidget(sort_by)

        return header_layout

    def sort_by_func(self, choice):
        # calls backend sort functions
        if choice == 0:
            print('sorting alphabetically')
            self.refresh_tasks('alpha')
        elif choice == 1:
            print('sorting by date created')
            self.refresh_tasks('da')
        elif choice == 2:
            print('sorting by furthest due date')
            self.refresh_tasks('tra')
        elif choice == 3:
            print('sorting by amount of time left')
            self.refresh_tasks('trd')

    def create_task_area(self):
        # create a scroll area to hold tasks -- # create the task area for the gui, this will hold all of the tasks (probably doesn't need to be it's own function and can be made in the init_gui class)
        self.tasks_area = QScrollArea(self)
        self.tasks_area.setWidgetResizable(True)
        widget = QWidget()
        self.tasks_area.setWidget(widget)
        self.tasks_layout = QVBoxLayout(widget)
        self.tasks_layout.setAlignment(Qt.AlignTop)
        logger.log("Drawing GUI")

    def refresh_tasks(self, sort_by='alpha'):

        # erase all current tasks in layout
        for task_num in range(self.tasks_layout.count()):
            self.tasks_layout.itemAt(task_num).widget().deleteLater()

        # get current tasks from database
        all_tasks = user_tasks.get_tasks(sort_by)

        #creates new task windows based off the database data
        for task_tuple in all_tasks:
            self.tasks_layout.addWidget(
                TaskWindow(task_tuple[0], task_tuple[1], task_tuple[2],
                           task_tuple[3], task_tuple[4]))

    def countdown_update(self):
        # updates all of the tasks timers at the same time
        for task in range(self.tasks_layout.count()):
            try:
                self.tasks_layout.itemAt(task).widget().update_time()
            except:
                pass
コード例 #20
0
ファイル: gui.py プロジェクト: Kullmann/Photocrypt
class Contacts(QWidget):
    """
    Contacts window
    """
    def __init__(self, key_manager, setter):
        super(Contacts, self).__init__()
        self.setStyleSheet(
            "background-color:#315d90; font: 12pt Helvetica; color: #d3e1ed")
        self.setWindowTitle("Contacts - Photo Crypto")
        self.setFixedSize(500, 600)
        self.delete_button = QIcon(
            join(WORKING_DIRECTORY, 'resource', 'delete.png'))
        self.key_manager = key_manager
        self.setter = setter
        self.key_manager.connect()
        self.contact_list_box = QWidget()
        self.contact_list_box.setStyleSheet(
            "background-color:#315d90; color: #ffffff")
        self.contact_list = QVBoxLayout()
        self.contact_list_box.setLayout(self.contact_list)
        self.contact_list.setAlignment(Qt.AlignTop)

        self.keys = {}
        self.set_callers = {}
        self.del_callers = {}
        self.list_key()

        scroll = QScrollArea()
        scroll.setWidget(self.contact_list_box)
        scroll.setWidgetResizable(True)
        scroll.setStyleSheet("font: 11pt Helvetica;")
        add = QPushButton("Add Contact")
        add.setStyleSheet(blue_button_style(height=60))
        layout = QVBoxLayout(self)

        layout.addWidget(scroll)
        layout.addWidget(add)

        self.add_contact = AddContact(self.add_key)
        add.clicked.connect(self.open_add_contact)

    def list_key(self):
        self.keys = {}
        self.set_callers = {}
        self.del_callers = {}
        names = []
        emails = []
        buttons = []
        deletebs = []

        keys = self.key_manager.list_key()
        for i in reversed(range(self.contact_list.count())):
            layout = self.contact_list.itemAt(i).layout()
            if layout:
                for j in reversed(range(layout.count())):
                    widget = layout.itemAt(j).widget()
                    if widget:
                        widget.deleteLater()
                layout.deleteLater()

        i = 0
        hbox = QHBoxLayout()
        name, email, action = QLabel("Name"), QLabel("Email"), QLabel(
            "Actions")
        name.setStyleSheet("font-weight: bold; font-size: 12pt")
        email.setStyleSheet("font-weight: bold; font-size: 12pt")
        action.setStyleSheet("font-weight: bold; font-size: 12pt")
        hbox.setContentsMargins(0, 10, 0, 10)
        hbox.addStretch(2)
        hbox.addWidget(name)
        hbox.addStretch(5)
        hbox.addWidget(email)
        hbox.addStretch(3)
        hbox.addWidget(action)
        hbox.addStretch(1)
        self.contact_list.addLayout(hbox)
        for key in keys:
            self.keys[key['uid']] = key

            name = QLabel(key['name'])
            email = QLabel(key['email'])
            names.append(name)
            emails.append(email)

            button = QPushButton("Choose")
            button.setStyleSheet(green_button_style())
            button.clicked.connect(self.set_key)
            self.set_callers[button] = key['uid']
            buttons.append(button)

            deleteb = QPushButton()
            deleteb.setIcon(self.delete_button)
            deleteb.clicked.connect(self.delete_key)
            deleteb.setStyleSheet(red_button_style())
            self.del_callers[deleteb] = key['uid']
            deletebs.append(deleteb)

            hbox = QHBoxLayout()
            hbox.setContentsMargins(0, 20, 0, 20)
            hbox.addStretch(2)
            hbox.addWidget(names[i])
            hbox.addStretch(5)
            hbox.addWidget(emails[i])
            hbox.addStretch(2)
            hbox.addWidget(buttons[i])
            hbox.addStretch(1)
            hbox.addWidget(deletebs[i])
            self.contact_list.addLayout(hbox)
            i += 1
        return keys

    def set_key(self):
        for s in self.set_callers:
            s.setDisabled(False)
            s.setStyleSheet(green_button_style())
        self.sender().setDisabled(True)
        self.sender().setStyleSheet(disabled_button_style())
        self.setter(self.keys[self.set_callers[self.sender()]])

    def add_key(self, name, email, keypath):
        try:
            key = load_key(keypath)
            self.key_manager.write_key(name, email, key)
            self.add_contact.close()
            self.list_key()
            self.popup_message("Success", "Successfully added contect info.")
        except ValueError as err:
            self.popup_message("Error", str(err))
        except FileNotFoundError as err:
            self.popup_message("Error", str(err))

    def delete_key(self):
        key = self.keys[self.del_callers[self.sender()]]
        self.key_manager.delete_key(key['uid'])
        self.list_key()

    def popup_message(self, title, text):
        dialog = QMessageBox()
        dialog.setWindowTitle(title)
        dialog.setText(text)
        dialog.exec_()

    def open_add_contact(self):
        self.add_contact.show()

    def closeEvent(self, event):
        self.add_contact.close()
コード例 #21
0
ファイル: scene_widget.py プロジェクト: limgit/opdss
class SceneDataTab(QWidget):
    def __init__(self, obj_mng: ObjectManager, mtm_mng: MultimediaManager):
        super().__init__()

        self._vbox_data = QVBoxLayout()
        self._component_widgets = dict()  # id -> ComponentWidget
        self._tview_detail = QTextBrowser()

        self._obj_mng = obj_mng
        self._mtm_mng = mtm_mng

        self._res = ResourceManager()
        self.init_ui()

    def load_ui(self, template: SceneTemplate) -> None:
        # Clean the previous layout
        self._component_widgets = dict()
        for i in range(self._vbox_data.count()):
            widget = self._vbox_data.itemAt(0).widget()
            self._vbox_data.removeWidget(widget)
            widget.deleteLater()
        self._tview_detail.setText("")

        # Load the new layout
        fields = template.definition.fields
        for field_id in fields.keys():

            def clicked_handler(name: str, description: str,
                                constraint: str) -> None:
                text = "<b>" + name + "</b><br />"
                text += description + "<br />"
                text += "Constraint: " + constraint
                self._tview_detail.setText(text)

            field = fields[field_id]  # Tuple[DataType, name, description]
            if isinstance(field[0], StringDataType):
                widget = StringDataWidget(field[0], field[1], field[2],
                                          clicked_handler)
                widget.value = field[0].default
                self._component_widgets[field_id] = widget
                self._vbox_data.addWidget(widget)
            elif isinstance(field[0], BooleanDataType):
                widget = BooleanDataWidget(field[0], field[1], field[2],
                                           clicked_handler)
                widget.value = field[0].default
                self._component_widgets[field_id] = widget
                self._vbox_data.addWidget(widget)
            elif isinstance(field[0], IntegerDataType):
                widget = IntegerDataWidget(field[0], field[1], field[2],
                                           clicked_handler)
                widget.value = field[0].default
                self._component_widgets[field_id] = widget
                self._vbox_data.addWidget(widget)
            elif isinstance(field[0], DateDataType):
                widget = DateTimeDataWidget(field[0], field[1], field[2],
                                            clicked_handler)
                widget.value = datetime.strptime(field[0].default,
                                                 DateDataType.format)
                self._component_widgets[field_id] = widget
                self._vbox_data.addWidget(widget)
            elif isinstance(field[0], ObjectDataType):
                widget = ObjectDataWidget(field[0], field[1], field[2],
                                          clicked_handler, self._obj_mng)
                widget.value = field[0].default
                self._component_widgets[field_id] = widget
                self._vbox_data.addWidget(widget)
            elif isinstance(field[0], FileDataType):
                widget = MediaWidget(field[0] is self._mtm_mng.image_type,
                                     field[1], field[2], clicked_handler,
                                     self._mtm_mng)
                widget.value = field[0].default
                self._component_widgets[field_id] = widget
                self._vbox_data.addWidget(widget)
            elif isinstance(field[0], ListDataType):
                widget = ListDataWidget(field[0], field[1], field[2],
                                        clicked_handler)
                widget.value = field[0].default
                self._component_widgets[field_id] = widget
                self._vbox_data.addWidget(widget)
                # TODO: Add more UI components according to data type

    def load_data_on_ui(self, scene: Scene) -> None:
        # scene_idx from 0
        self.load_ui(scene.template)
        flat_values = scene.values.get_values(False)
        for field_id in scene.values.get_values().keys():
            field_value = flat_values[field_id]
            if field_id in self._component_widgets:  # TODO: This line should be removed
                self._component_widgets[field_id].value = field_value

    def init_ui(self) -> None:
        vbox_outmost = QVBoxLayout()
        vbox_outmost.addLayout(self._vbox_data)
        vbox_outmost.addWidget(self._tview_detail)
        self.setLayout(vbox_outmost)

    def save(self, scene: Scene) -> None:
        # Gather all data
        values = dict()
        for field_id in self._component_widgets.keys():
            widget = self._component_widgets[field_id]
            values[field_id] = widget.value
        # Save it
        scene.values.set_values(**values)

    def is_data_valid(self) -> bool:
        for field_id in self._component_widgets.keys():
            widget = self._component_widgets[field_id]
            if not widget.is_data_valid():
                return False
        return True
コード例 #22
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")
        self.is_added = False
        hint = create_hint("Введіть значення параметрів: ")

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(hint)
        self.main_layout.addWidget(self.create_field('T:'))
        self.main_layout.addWidget(self.create_field("l_0:"))
        self.main_layout.addWidget(self.create_field("l_g1:"))
        self.main_layout.addWidget(self.create_field("l_g2:"))
        self.main_layout.addWidget(self.create_field("m_0:"))
        self.main_layout.addWidget(self.create_field("m_gamma:"))
        self.main_layout.addWidget(self.create_field("a0:"))
        self.main_layout.addWidget(self.create_field("b0:"))
        self.main_layout.addWidget(self.create_field("a1:"))
        self.main_layout.addWidget(self.create_field("b1:"))

        self.button_pass_args = QPushButton()
        self.button_pass_args.setText("Ввести")
        self.button_pass_args.clicked.connect(self.input_button_clicked)

        self.main_layout.addWidget(self.button_pass_args)

        main_widget = QWidget()
        main_widget.setLayout(self.main_layout)

        self.setCentralWidget(main_widget)

    def create_field(self, field_title: str, values_num: int = 1):
        hint = create_hint(field_title)
        second_input = QHBoxLayout()
        for _ in range(values_num):
            value_input = QSpinBox()
            value_input.setMaximum(500)
            second_input.addWidget(hint)
            second_input.addWidget(value_input)

        second_input_widget = QWidget()
        second_input_widget.setLayout(second_input)

        return second_input_widget

    def input_button_clicked(self):
        """ 
        Slot for processing signal from
        first button, that adds input
        matrix and vector of right dimension
        to the main layout.
        """
        if self.is_added:
            self.delete_from_main_layout(
            )  # if widgets already added - remove them
            self.is_added = False
        else:
            self.is_added = True
            values = self.get_data_from_widgets()
            args = self.set_dict(values)
            lab4.arg = args
            lab4.main()

    def set_dict(self, values):
        arg = {
            "T": values[0],
            "l_0": values[1],
            "l_g": [values[2], values[3]],
            "m_0": values[4],
            "m_gamma": values[5],
            "a0": values[6],
            "b0": values[7],
            "a1": values[8],
            "b1": values[8],
        }
        return arg

    def get_data_from_widgets(self):
        items, values = [], []
        for i in range(1, self.main_layout.count() - 1):
            items.append(self.main_layout.itemAt(i).widget())
        for widget in items:
            child_widgets = widget.children()
            if isinstance(child_widgets, list):
                values.append(int(child_widgets[-1].cleanText()))
        return values

    def delete_from_main_layout(self):
        """
        Clearing layout from widgets
        after updating m and n
        """
        items = []
        for i in range(1, self.main_layout.count() - 1):
            items.append(self.main_layout.itemAt(i).widget())
        for widget in items:
            widgets = widget.children()
            if isinstance(widgets, list):
                widgets[-1].setValue(0)
コード例 #23
0
class NeuralNetworkModelControllerWidget(QWidget):
    def __init__(self, model, parent=None):
        super(NeuralNetworkModelControllerWidget, self).__init__(parent=parent)
        self._model = model
        self._layout = QVBoxLayout(self)
        self._layers_layout = QVBoxLayout()

        self.__update_layers_info()
        add_layout_button = QPushButton("Add new layer")
        add_layout_button.clicked.connect(self._add_layer)
        self._layout.addLayout(self._layers_layout, 1)
        self._layout.addWidget(add_layout_button, alignment=Qt.AlignBottom)

    @property
    def model(self):
        return self._model

    @model.setter
    def model(self, model):
        self._model = model
        self.__update_layers_info()

    def __update_layers_info(self):
        for i in range(self._layers_layout.count()):
            child = self._layers_layout.itemAt(i)
            widget = child.widget()
            widget.setVisible(False)
        for i, layer in enumerate(self._model.layers[:-1]):
            self.__add_layer_info(i, layer)
        index = len(self._model.layers) - 1
        self.__add_layer_info(index, self._model.layers[-1], False)
        self._layers_layout.setAlignment(Qt.AlignTop)

    def __create_new_layer(self, i, layer, enabled=True):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        layer_count_line_edit = QLineEdit(str(layer.output_dimension))
        layer_count_line_edit.setFixedWidth(120)
        layer_count_line_edit.textChanged[str].connect(
            self.__on_change_layer_count_maker(layer_count_line_edit, i))
        layer_count_line_edit.setEnabled(enabled)
        remove_layout_button = QPushButton("X")
        remove_layout_button.clicked.connect(self._remove_layout_maker(i))
        remove_layout_button.setVisible(enabled)
        label = QLabel("Layer %d:" % (i + 1))
        line = QHBoxLayout()
        line.addWidget(label, alignment=Qt.AlignTop)
        line.addWidget(remove_layout_button, alignment=Qt.AlignTop)
        activation_functions = QComboBox()
        activation_functions.addItem("Linear function")
        activation_functions.addItem("Sigmoid function")
        activation_functions.setCurrentIndex(
            get_current_function_index(layer.activation_function))
        activation_functions.currentIndexChanged.connect(
            self.__change_activation_function_maker(i))
        layout.addLayout(line)
        layout.addWidget(layer_count_line_edit, alignment=Qt.AlignTop)
        layout.addWidget(activation_functions, alignment=Qt.AlignTop)
        return widget

    def __add_layer_info(self, i, layer, enabled=True):
        item = self._layers_layout.itemAt(i)
        if item is not None:
            widget = item.widget()
            widget_layout = widget.layout()
            line_item = widget_layout.itemAt(0)
            line = line_item.layout()
            remove_layout_button_item = line.itemAt(1)
            remove_layout_button = remove_layout_button_item.widget()
            remove_layout_button.setVisible(enabled)
            layer_count_line_edit_item = widget_layout.itemAt(1)
            layer_count_line_edit = layer_count_line_edit_item.widget()
            layer_count_line_edit.setText(str(layer.output_dimension))
            layer_count_line_edit.setEnabled(enabled)
            activation_function_item = widget_layout.itemAt(2)
            activation_function = activation_function_item.widget()
            activation_function.setCurrentIndex(
                get_current_function_index(layer.activation_function))
            widget.setVisible(True)
        else:
            widget = self.__create_new_layer(i, layer, enabled)
            self._layers_layout.addWidget(widget, alignment=Qt.AlignTop)

    def __change_activation_function_maker(self, index):
        def __change_activation_function(selected):
            function = None
            if selected == 0:
                function = LinearFunction()
            if selected == 1:
                function = SigmoidFunction()
            if function is not None:
                self._model.change_activation_function(index, function)

        return __change_activation_function

    def _remove_layout_maker(self, index):
        def _remove_layout():
            self._model.remove_layer(index)
            self.__update_layers_info()
            self.repaint()

        return _remove_layout

    def _add_layer(self):
        self._model.add_layer()
        self.__update_layers_info()

    def __on_change_layer_count_maker(self, layer_count_line_edit, index):
        def __on_change_layer_count(text):
            layer_count = 0
            for ch in text:
                if ord('0') <= ord(ch) <= ord('9'):
                    layer_count = 10 * layer_count + ord(ch) - ord('0')
            layer_count_line_edit.setText(str(layer_count))
            layer_count = max(layer_count, 1)
            self._model.change_layer_count(index, layer_count)

        return __on_change_layer_count
コード例 #24
0
class Connect_Directions_Online(QObject):
    """
    This class is used to connect the directions modifications in case of the online
    modality. It modifies the module according to the newly selected
    parameter value.
    """

    signal_paramChanged = pyqtSignal([str, list])
    signal_error = pyqtSignal(str)

    #----------------------------------------------------------------------
    def __init__(self, paramName, chosen_value, all_Values, nb_directions,
                 chosen_events, events):
        """Constructor

        paramName = Name of the parameter corresponding to the widget to create
        chosen_value = the subject's specific parameter directions.
        all_Values = list of all possible directions
        nb_directions = number of directions to add.
        chosen_events = the subject's specific parameter events linked to the corresponding direction.
        events = events
        """
        super().__init__()

        self.nb_direction = nb_directions
        self.all_values = all_Values
        self.chosen_events = chosen_events
        self.chosen_value = chosen_value
        self.events = None
        self.tdef = None

        self.directions = Connect_Directions(paramName, chosen_value,
                                             all_Values, nb_directions)
        self.directions.signal_paramChanged[str, list].connect(self.on_modify)

        self.associated_events = Connect_Directions('DIR_EVENTS',
                                                    chosen_events, events,
                                                    nb_directions)
        self.associated_events.signal_paramChanged[str, list].connect(
            self.on_modify)

        self.l = QVBoxLayout()
        self.l.addLayout(self.directions.l)
        self.l.addLayout(self.associated_events.l)

    #----------------------------------------------------------------------
    def clear_VBoxLayout(self):
        """
        Clear the layout containing additional layouts and widgets
        """
        if self.l.itemAt(1):
            self.associated_events.clear_hBoxLayout()
            self.l.itemAt(1).setParent(None)
        if self.l.itemAt(0):
            self.directions.clear_hBoxLayout()
            self.l.itemAt(0).setParent(None)

    @pyqtSlot(str, str)
    #----------------------------------------------------------------------
    def on_new_decoder_file(self, key, filePath):
        """
        Update the event QComboBox with the new events from the new .
        """
        with open(filePath, 'rb') as f:
            cls = pickle.load(f)
        events = cls[
            'cls'].classes_  # Finds the events on which the decoder has been trained on
        self.events = list(map(int, events))
        self.nb_directions = len(events)

        if self.tdef:
            self.on_update_VBoxLayout()

    @pyqtSlot(str, str)
    #----------------------------------------------------------------------
    def on_new_tdef_file(self, key, trigger_file):
        """
        Update the event QComboBox with the new events from the new tdef file.
        """
        self.tdef = TriggerDef(trigger_file)

        if self.events:
            self.on_update_VBoxLayout()

    @pyqtSlot()
    #----------------------------------------------------------------------
    def on_update_VBoxLayout(self):
        """
        Update the layout with the new events and chosen values
        """
        self.clear_VBoxLayout()
        events = [self.tdef.by_value[i] for i in self.events]

        if len(self.chosen_value) != self.nb_directions:
            self.chosen_value = list(self.all_values[:self.nb_directions])

        self.directions.create_the_comboBoxes(self.chosen_value,
                                              self.all_values,
                                              self.nb_directions)

        if len(self.chosen_events) != self.nb_directions:
            self.chosen_events = events

        self.associated_events.create_the_comboBoxes(self.chosen_events,
                                                     events,
                                                     self.nb_directions)

        self.l.addLayout(self.directions.l)
        self.l.addLayout(self.associated_events.l)

    @pyqtSlot(str, list)
    #----------------------------------------------------------------------
    def on_modify(self, paramName, new_Values):
        """
        Slot connected to the changes in the directions.
        """
        updatedList = []

        if paramName == self.directions.paramName:
            for i in range(len(new_Values)):
                updatedList.append(
                    (new_Values[i], self.associated_events.chosen_value[i]))

        elif paramName == self.associated_events.paramName:
            for i in range(len(new_Values)):
                updatedList.append(
                    (self.directions.chosen_value[i], new_Values[i]))

        self.signal_paramChanged[str, list].emit(self.directions.paramName,
                                                 updatedList)
コード例 #25
0
class WorkersEditor(ViewInfoChanger):
    def __init__(self, header, info, parent: ViewShower):
        super().__init__(header, info, parent)
        self.way_layout = QVBoxLayout()
        push_btn = self.main_layout.takeAt(self.main_layout.count() -
                                           1).widget()

        self.worker_id = info[0]
        self.slave_combo_config = {
            "название_параметра":
            ("параметры", "*", "название_параметра", "код_параметра")
        }
        self.combo_change_idx["название_параметра"] = {}
        add_btn = QPushButton("Добавить")
        add_btn.clicked.connect(lambda e: self.add_cell(-1))
        self.main_layout.addWidget(add_btn)

        way = self.db.execute(
            f"SELECT код_параметра, название_параметра, корректировка_нижнего_порога, корректировка_верхнего_порога FROM `корректировки_view` where `табельный_номер` = {self.worker_id}"
        )
        for pos, point in enumerate(way, start=-1):
            param_name = str(point[1])
            self.combo_change_idx["название_параметра"][param_name] = point[0]
            self.add_cell(pos, param_name, point[2], point[3])

        self.main_layout.addLayout(self.way_layout)
        self.main_layout.addWidget(push_btn)

    def add_cell(self, pos: int, txt="", dnw_val="", up_val=""):
        """Вставляет ячейку ниже активирующей кнопки для вставки на уровне надо передать ::pos:: = -1"""

        cell = QHBoxLayout()
        edi = QLineEdit()
        edi.setText(txt)

        dwn_val_edt = QLineEdit()
        dwn_val_edt.setText(str(dnw_val))
        up_val_edt = QLineEdit(str(up_val))

        add_btn = QPushButton("Добавить")
        del_btn = QPushButton("Удалить")

        cmb = QComboBox()
        cmb.addItem(txt)

        edi.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        cmb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        dwn_val_edt.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        up_val_edt.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        add_btn.clicked.connect(lambda e, c=cell: self.add_cell(c.pos))
        del_btn.clicked.connect(lambda e, c=cell: self.del_cell(c.pos))

        edi.editingFinished.connect(
            lambda c=cmb, t=edi.text: self.slave_combo_update(
                "название_параметра", c, t()))  # le-kostyl
        cell.pos = pos
        cell.addWidget(edi)
        cell.addWidget(cmb)
        cell.addWidget(dwn_val_edt)
        cell.addWidget(up_val_edt)
        cell.addWidget(add_btn)
        cell.addWidget(del_btn)
        for i in range(pos + 1, self.way_layout.count()):
            cell_to_move = self.way_layout.itemAt(i)
            cell_to_move.pos += 1
        cell.pos += 1  # для вставки ниже активированной кнопки

        self.way_layout.insertLayout(cell.pos, cell)

    def slave_combo_update(self, c_name: str, c: QComboBox,
                           text: str):  # grand le-kostyl
        tmp = self.combo_config
        self.combo_config = self.slave_combo_config
        self.combo_update(c_name, c, text)
        self.combo_config = tmp

    def del_cell(self, pos):
        cell: QVBoxLayout
        cell = self.way_layout.takeAt(pos)
        for i in range(cell.count()):
            w = cell.takeAt(0).widget()
            w.deleteLater()
        cell.deleteLater()

        for i in range(pos, self.way_layout.count()):
            cell_to_move = self.way_layout.itemAt(i)
            cell_to_move.pos -= 1

    def push_slave_changes(self):
        params = []
        kakoito_set = set()
        try:
            for i in range(self.way_layout.count()):
                cell = self.way_layout.itemAt(i)
                w = cell.itemAt(1).widget()
                param = w.currentText()
                if param:
                    if param in kakoito_set:
                        raise KeyError
                    kakoito_set.add(param)
                    param_id = self.combo_change_idx["название_параметра"][
                        param]
                    dwn_w = cell.itemAt(2).widget()
                    up_w = cell.itemAt(3).widget()
                    dwn_val = dwn_w.text()
                    up_val = up_w.text()
                    if not dwn_val:
                        dwn_val = 0
                    if not up_val:
                        up_val = 0
                    params.append((self.worker_id, param_id, dwn_val, up_val))

            query = f" insert into `корректировки` values(%s, %s, %s, %s)"
            self.db.execute(
                "delete from `корректировки` where табельный_номер = %s",
                (self.worker_id, ))
            self.db.executemany(query, params)
            self.db.commit()
        except KeyError as er:
            from PyQt5.QtWidgets import QErrorMessage
            error_widget = QErrorMessage()
            error_widget.showMessage(f"Дубликат параметра")
            error_widget.exec()

    def push_changes(self):
        self.push_slave_changes()
        super().push_changes()
コード例 #26
0
class OpenPoseWidget(QWidget):
    def __init__(self, exer, view):
        super(OpenPoseWidget, self).__init__()
        self.main_layout = QHBoxLayout()
        self.op_layout = QVBoxLayout()
        self.control_layout = QVBoxLayout()

        self.start_control = 0

        # op_layout
        op_tmp = QLabel('Please push Start button')
        op_tmp.setAlignment(Qt.AlignCenter)

        self.op_layout.addWidget(op_tmp)

        # contorl_layout
        self.sub1_layout = QHBoxLayout() 
        self.sub2_layout = QVBoxLayout()

        start = QPushButton('Start')
        stop = QPushButton('Stop') 
        feedback = QPushButton('Feedback')

        font = QFont('Arial', 20)
        start.setFont(font)
        stop.setFont(font)
        feedback.setFont(font)



        start.setFixedSize(QSize(150,75))
        stop.setFixedSize(QSize(150,75))
        feedback.setFixedSize(QSize(150,75))
        
        start.clicked.connect(partial(self.run_op_screen, exer, view))
        stop.clicked.connect(partial(self.stop_op_screen))
        feedback.clicked.connect(partial(self.start_feedback))
        
        self.sub1_layout.addWidget(start)
        self.sub1_layout.addWidget(stop)
        self.sub1_layout.addWidget(feedback)

        msg = "" 
        if exer == 'squat':
            msg += "스쿼트를 선택하셨습니다.\n"
        else:
            msg += "푸쉬업을 선택하셨습니다.\n"

        msg += "영상 촬영을 시작하기 위해서 버튼을 눌러주세요. \n" + \
                "시작되는데 15초 가량 소요될 수 있습니다."

        label1 = QLabel(msg)
        label1.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        font = QFont('Arial', 15)
        label1.setFont(font)

        self.exer_img = QLabel()
        if exer == 'squat':
            self.exer_img.setPixmap(QPixmap("../pictures/squat.JPG").scaledToWidth(320))
        else:
            self.exer_img.setPixmap(QPixmap("../pictures/pushup.JPG").scaledToWidth(320))

    
        self.exer_img.setAlignment(Qt.AlignCenter)


        self.sub2_layout.addWidget(self.exer_img)
        #self.sub2_layout.addWidget(label1)
        #self.sub2_layout.addWidget(label2)



        #self.control_layout.addLayout(self.sub1_layout)
        self.control_layout.addLayout(self.sub2_layout)

        
        right_layout = QVBoxLayout()
        right_layout.addLayout(self.op_layout)
        right_layout.addLayout(self.sub1_layout)

        # main_layout
        self.main_layout.addLayout(self.control_layout)
        self.main_layout.addLayout(right_layout)
        #self.main_layout.addLayout(self.op_layout)

        self.setLayout(self.main_layout)

    def run_op_screen(self, exer, view):
        if self.start_control is 1:
            return

        # clear op_layout
        self.start_control = 1
        for i in reversed(range(self.op_layout.count())):
            self.op_layout.itemAt(i).widget().setParent(None)

        # run OpenPose
        for f in os.listdir(json_dir):
            os.remove(os.path.join(json_dir, f))

        self.op_handler = subprocess.Popen([openpose_demo_path, "--camera=" + str(camera_offset), "--net_resolution=128x128", "--write_json=" + json_dir, "--model_folder=" + model_dir, "--number_people_max=1"], shell=False)

        # add widget!
        winid = self.get_op_winid()
        while winid is -1:
            winid = self.get_op_winid() 
        op_window = QWindow.fromWinId(winid)
        op_window.setFlags(Qt.FramelessWindowHint)
        op_widget = QWidget.createWindowContainer(op_window)
        self.op_layout.addWidget(op_widget)

        for i in reversed(range(self.sub2_layout.count())):
            self.sub2_layout.itemAt(i).widget().setParent(None)
        
        ready_img = QLabel()
        ready_img.setPixmap(QPixmap("../pictures/ready.JPG").scaledToWidth(320))
        ready_img.setAlignment(Qt.AlignCenter)
        self.sub2_layout.addWidget(ready_img)


       
    def stop_op_screen(self, msg=None):
        if self.start_control is 0:
            return
        
        self.op_handler.terminate()
        self.start_control = 0
        for i in reversed(range(self.op_layout.count())):
            self.op_layout.itemAt(i).widget().setParent(None)
        
        op_tmp = QLabel(msg if msg else 'Please push Start button')
        op_tmp.setAlignment(Qt.AlignCenter)
        
        """
        if msg:
            ox_img = QLabel()
            ox_img.setPixmap(QPixmap("test.png"))
            #ox_img.show()
            self.op_layout.addWidget(ox_img)
        """
        self.op_layout.addWidget(op_tmp)


    def start_feedback(self): 
        #time.sleep(5)
        #collect data 
        
        
        print("feedback start")
        print("GET READY")
        time.sleep(3)
        print("START")

        #for i in reversed(range(self.sub2_layout.count())):
        #    self.sub2_layout.itemAt(i).widget().setParent(None)
 
        #go_img = QLabel("GO")
        #go_img.setPixmap(QPixmap("../pictures/go.JPG").scaledToWidth(320))
        #go_img.setAlignment(Qt.AlignCenter)
        #self.sub2_layout.addWidget(go_img)




        start_point = len(os.listdir(json_dir))
        j = JsonParser(start_point=start_point)
   
        # incremental try
        frame_no_list = [i*10 for i in range(4,10)]
        err = 0
        
        tys = ["elbow", "arm", "shoulder"]
        result_dict = {} 
        

        for frame_no in frame_no_list:  
            print(str(frame_no) + " frame test")
            video = j.parse(None, frame_no , json_dir, "front", None)
            result_dict = {}
            err = 0 
            for ty in tys:
                print("doing " + ty)
                fds = FeedbackSystem()
                fds.load("demo_front_" + ty + "_model", "front")
                result, div_zero = fds.feedback_kmeans(video, ty, threshold=0.3)
                if div_zero:
                    err = 1
                else:
                    result_dict[ty] = result 

            if err is 0:
                break
            
        if err is 1:
            self.stop_op_screen("Posture is not detected. Please adjust webcam position") 
            return
         
        fdm = FeedbackMsg(result_dict)
        msg = fdm.get_feedback_msg()
        #self.op_handler.terminate()


        # now print out feedback msg
        #self.stop_op_screen("Result")
              
        need_cor = msg[0]
        cor_msg = msg[1:]

        #top_layout = QVBoxLayout() 
        #bottom_layout = QVBoxLayout()

        """ 
        for m in cor_msg:  
            op_tmp = QLabel(m)
            op_tmp.setAlignment(Qt.AlignCenter)
            self.op_layout.addWidget(op_tmp)
        """
        
        for i in reversed(range(self.sub2_layout.count())):
            self.sub2_layout.itemAt(i).widget().setParent(None)
       
        if need_cor:
            bad_img = QLabel()
            bad_img.setPixmap(QPixmap("../pictures/bad.JPG").scaledToWidth(260))
            bad_img.setAlignment(Qt.AlignCenter)
            self.sub2_layout.addWidget(bad_img)
        else:
            nice_img = QLabel()
            nice_img.setPixmap(QPixmap("../pictures/nice.JPG").scaledToWidth(260))
            nice_img.setAlignment(Qt.AlignCenter)
            self.sub2_layout.addWidget(nice_img)

        feedback_msg = ""
        for m in cor_msg:  
            feedback_msg += m + "\n"

        op_tmp = QLabel(feedback_msg)
        op_tmp.setAlignment(Qt.AlignCenter)
        op_tmp.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        self.sub2_layout.addWidget(op_tmp)

        """
        ox_img = QLabel()
        ox_img.setPixmap(QPixmap("test.png"))
        ox_img.show()
        top_layout.addWidget(ox_img)

        for m in cor_msg:  
            op_tmp = QLabel(m)
            op_tmp.setAlignment(Qt.AlignCenter)
            bottom_layout.addWidget(op_tmp)


        self.op_layout.addLayout(top_layout)
        self.op_layout.addLayout(bottom_layout)
        """


    def get_op_winid(self):
        tmp1w = open("tmp1", "w")
        tmp1r = open("tmp1", "r")
        tmp2w = open("tmp2", "w")
        tmp2r = open("tmp2", "r")

        subprocess.call(['wmctrl', '-lp'], stdout=tmp1w)
        subprocess.call(['grep', 'OpenPose'], stdin=tmp1r, stdout=tmp2w)
        l = tmp2r.readline().split()
       
        out = 0
        if (len(l) is 0):
            out = -1
        else:
            out = int(l[0], base=16)


        tmp1w.close()
        tmp1r.close()
        tmp2w.close()
        tmp2r.close()
        return out
コード例 #27
0
class ExtensionTab(QScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)

    def display(self, path: str):
        self.extended_query_subject = Subject()

        self.container_vertical_layout = QVBoxLayout()
        container_group_box = QGroupBox()
        container_group_box.setLayout(self.container_vertical_layout)
        self.setWidget(container_group_box)
        self.setWidgetResizable(True)

        for i in reversed(range(self.container_vertical_layout.count())):
            self.container_vertical_layout.itemAt(i).widget().deleteLater()

        self.initial_query: Query = None
        self.rfd: RFD = None

        self.path = path
        self.csv_parser: CSVParser = CSVParser(path)
        self.data_frame: DataFrame = self.csv_parser.data_frame

        self.initial_query_title = QLabel("Initial Query")
        self.initial_query_title.setWordWrap(True)
        self.initial_query_title.setFont(
            QtGui.QFont("Times", 12, QtGui.QFont.Bold))
        self.container_vertical_layout.addWidget(self.initial_query_title)

        self.initial_query_value = QLabel("")
        self.initial_query_value.setWordWrap(True)
        self.initial_query_value.setFont(
            QtGui.QFont("Arial", 12, QtGui.QFont.Cursive))
        self.container_vertical_layout.addWidget(self.initial_query_value)

        self.rfd_title = QLabel("RFD")
        self.rfd_title.setWordWrap(True)
        self.rfd_title.setFont(QtGui.QFont("Times", 12, QtGui.QFont.Bold))
        self.container_vertical_layout.addWidget(self.rfd_title)

        self.rfd_value = QLabel("")
        self.rfd_value.setWordWrap(True)
        self.rfd_value.setFont(QtGui.QFont("Times", 12, QtGui.QFont.Cursive))
        self.container_vertical_layout.addWidget(self.rfd_value)

        self.extended_query_title = QLabel("Extended Query")
        self.extended_query_title.setWordWrap(True)
        self.extended_query_title.setFont(
            QtGui.QFont("Times", 12, QtGui.QFont.Bold))
        self.container_vertical_layout.addWidget(self.extended_query_title)

        self.extended_query_value = QLabel("")
        self.extended_query_value.setTextInteractionFlags(
            Qt.TextSelectableByMouse)
        self.extended_query_value.setWordWrap(True)
        self.extended_query_value.setFont(
            QtGui.QFont("Arial", 12, QtGui.QFont.Cursive))
        self.container_vertical_layout.addWidget(self.extended_query_value)

    def set_initial_query_subject(self, query_subject: Subject):
        self.initial_query_subject: Subject = query_subject
        self.initial_query_subject.subscribe(on_next=lambda query: (
            self.update_initial_query(query), self.extend_query()))

    def update_initial_query(self, query: Query):
        self.initial_query: Query = query
        self.initial_query_value.setText(
            self.initial_query.to_rich_text_expression())
        self.initial_query_value.setTextFormat(Qt.RichText)

    def set_rfd_subject(self, rfd_subject: Subject):
        self.rfd_subject: Subject = rfd_subject
        self.rfd_subject.subscribe(on_next=lambda rfd: (
            self.update_selected_rfd(rfd), self.extend_query()))

    def update_selected_rfd(self, rfd: RFD):
        self.rfd: RFD = rfd
        self.rfd_value.setText(self.rfd.__str__())

    def extend_query(self):
        if self.initial_query and self.rfd:
            self.extended_query = self.initial_query.extend_ranges(
                self.rfd, self.data_frame)
            self.extended_query_subject.on_next(self.extended_query)

            self.extended_query_value.setText(
                self.extended_query.to_rich_text_expression())
            self.extended_query_value.setTextFormat(Qt.RichText)

    def get_extended_query_subject(self) -> Subject:
        return self.extended_query_subject
コード例 #28
0
ファイル: padulator.py プロジェクト: sparsile/padulator
class PadCalc(QWidget):
    def __init__(self):
        super().__init__()
        load_data()

        card_tags = ['leader','sub1','sub2','sub3','sub4','friend']
        self.cards = { t: CardIcon() for t in card_tags }

        self.vlayout = QVBoxLayout(self)
        self.vlayout.setSpacing(0)
        self.setLayout(self.vlayout)

        self.userbox = QHBoxLayout()
        userfield = QLineEdit()
        userbutton = QPushButton('Load')
        userbutton.clicked.connect(lambda: self.set_user(userfield.text()))
        self.userbox.addWidget(userfield)
        self.userbox.addWidget(userbutton)
        userfield.returnPressed.connect(userbutton.click)
        self.vlayout.addLayout(self.userbox)

        maxcheckbox = QCheckBox('Use maxed stats?')
        maxcheckbox.stateChanged[int].connect(self.setMaxed)
        self.vlayout.addWidget(maxcheckbox)


        self.teamchooser = QComboBox(self)
        self.teamchooser.currentIndexChanged[int].connect(self.set_team)
        self.vlayout.addWidget(self.teamchooser)

        teambox = QHBoxLayout()
        teambox.addStretch(1)
        for card in card_tags:
            teambox.addWidget(self.cards[card])

        teambox.setSpacing(0)
        teambox.addStretch(1)
        teambox.setAlignment(Qt.AlignCenter)
        self.vlayout.addLayout(teambox)

        self.board = Board()
        self.vlayout.addWidget(self.board)
        self.vlayout.itemAt(self.vlayout.indexOf(self.board)).setAlignment(Qt.AlignCenter)

        self.orbchooser = QHBoxLayout()
        b = OrbButton(value = 0)
        b.clicked.connect(functools.partial(self.setPaintOrb,Orb.Null))
        self.orbchooser.addWidget(b)
        for i in ORBS:
            b = OrbButton(value=i)
            #print('Setting click value of button %s to %s' % (id(b),i))
            b.clicked.connect(functools.partial(self.setPaintOrb,i))
            self.orbchooser.addWidget(b)

        self.vlayout.addLayout(self.orbchooser)

        self.damagereadout = QLabel()
        font = QFont()
        font.setPointSize(30)
        self.damagereadout.setAlignment(Qt.AlignCenter)
        self.damagereadout.setFont(font)
        self.vlayout.addWidget(self.damagereadout)
        self.board.valueChanged.connect(self.update_damage)

        labels = ['atk','combos','leaders','enhance','prongs','rows']
        lfont = QFont()
        lfont.setPointSize(9)
        vfont = QFont()
        vfont.setPointSize(12)
        self.details = {key: QVBoxLayout() for key in labels}
        for i in labels:
            label = QLabel(i)
            label.setFont(lfont)
            label.setAlignment(Qt.AlignCenter)
            label.setMargin(0)
            label.setContentsMargins(0,0,0,0)
            label.setIndent(0)
            self.details[i].label = label
            self.details[i].addWidget(self.details[i].label)
            value = QLabel('1')
            value.setFont(vfont)
            value.setAlignment(Qt.AlignCenter)
            value.setMargin(0)
            value.setIndent(0)
            value.setContentsMargins(0,0,0,0)
            self.details[i].value = value
            self.details[i].addWidget(self.details[i].value)
            self.details[i].setContentsMargins(1,1,1,1)

        self.detailreadout = QHBoxLayout()
        for i in labels:
            self.detailreadout.addLayout(self.details[i])
            timeslabel = QLabel('\u00d7')
            timeslabel.setMargin(0)
            timeslabel.setIndent(0)
            timeslabel.setAlignment(Qt.AlignCenter)
            timeslabel.setContentsMargins(0,0,0,0)
            self.detailreadout.addWidget(timeslabel)

        self.detailreadout.takeAt(self.detailreadout.count()-1)
        self.vlayout.addLayout(self.detailreadout)

        self.vlayout.addStretch(1000)
        self.skillbox = QHBoxLayout()
        self.vlayout.addLayout(self.skillbox)
        #self.set_user('korora')

    def setMaxed(self,state):
        Card.use_max_stats = (state == Qt.Checked)
        self.drawui()
        self.update_damage()
        self.set_team(self.teamchooser.currentIndex())

    def setPaintOrb(self,orb):
        global paintOrb
        paintOrb = orb

    def set_user(self,username):
        newuser = User(username)

        if hasattr(self,'user'):
            olduser = self.user.username
        else:
            olduser = ''

        if hasattr(newuser,'teams') and len(newuser.teams) > 0:
            teamchooser = self.teamchooser
            self.user = newuser
            index = teamchooser.currentIndex()
            try:
                teamchooser.currentIndexChanged[int].disconnect()
            except:
                return

            teamchooser.clear()
            for team in self.user.teams:
                teamchooser.addItem('%s' % (team['name']))

            if newuser.username != olduser:
                self.set_team(0)
            else:
                teamchooser.setCurrentIndex(index)
                self.set_team(index)

            teamchooser.currentIndexChanged[int].connect(self.set_team)

    def update_damage(self):
        (match,enhanced,row) = self.board.match()
        nmatch = sum(len(v) for v in match.values())
        nrow = sum(v for v in row.values())
        (dmg, multipliers) = compute_damage((match,enhanced,row),self.team)
        self.damagereadout.setText('{:,}'.format(round(sum([sum(i) for i in dmg.values()]))))
        for i in multipliers:
            if i is not 'atk':
                self.details[i].value.setText('%.2f' % multipliers[i])
            else:
                self.details[i].value.setText('%d' % multipliers[i])

        for card in self.cards.values():
            # add a damage label
            dam = dmg[card.card]
            card.main_attack = dam[0]
            card.sub_attack = dam[1]
            card.repaint()

    def set_team(self,index):
        teamdata = self.user.teams[index]
        team = []
        for i in ['leader','sub1','sub2','sub3','sub4']:
            team += [Card().load_from_id(self.user,teamdata[i])]
        friend = {
                'monster': teamdata['friend_leader'],
                'plus_atk': teamdata['friend_atk'],
                'plus_hp': teamdata['friend_hp'],
                'plus_rcv': teamdata['friend_rcv'],
                'current_awakening': teamdata['friend_awakening'],
                'lv': teamdata['friend_level'],
                'current_skill': teamdata['friend_skill']
                }
        team += [Card().load_from_card(friend)]
        self.team = Team(team)
        #print('|'+self.teamchooser.itemText(index)+'|')
        #print(len(self.teamchooser.itemText(index)))
        self.teamchooser.setMinimumContentsLength(len(self.teamchooser.itemText(index))-3)
        for i in range(self.skillbox.count()):
            w = self.skillbox.takeAt(i)
            w.widget().deleteLater()
            
        #svc = SkillViewController(skill=self.team.lskills[0])
        #svc.skillsChanged.connect(self.update_damage)
        #self.skillbox.addWidget(svc)
        self.drawui()
        self.update_damage()

    def drawui(self):
        self.cards['leader'].card = (self.team.cards[0])
        self.cards['sub1'].card = (self.team.cards[1])
        self.cards['sub2'].card = (self.team.cards[2])
        self.cards['sub3'].card = (self.team.cards[3])
        self.cards['sub4'].card = (self.team.cards[4])
        self.cards['friend'].card = (self.team.cards[5])
        for card in self.cards.values():
            card.load_icon()
コード例 #29
0
ファイル: rosconfigdialog.py プロジェクト: Diegojnb/JdeRobot
class TopicsTab(QWidget):
    configChanged = pyqtSignal()
    def __init__(self):
        super(QWidget, self).__init__()
        self.config = None
        self.count = 0
        self.topicRows = {}

        self.nameEdit = QLineEdit()
        self.dataTypeComboBox = QComboBox()
        self.fillDataTypes()
        self.opTypeComboBox = QComboBox()
        self.opTypeComboBox.addItem('sub', 'Subscribe')
        self.opTypeComboBox.addItem('pub', 'Publish')
        self.addButton = QPushButton('Add')
        self.addButton.clicked.connect(self.addClicked)

        self.mainLayout = QVBoxLayout()
        rowLayout = QHBoxLayout()
        rowLayout.addWidget(self.nameEdit)
        rowLayout.addWidget(self.dataTypeComboBox)
        rowLayout.addWidget(self.opTypeComboBox)
        rowLayout.addWidget(self.addButton)
        rowContainer = QWidget()
        rowContainer.setLayout(rowLayout)
        rowContainer.setObjectName('titleRow')
        self.mainLayout.addWidget(rowContainer)
        self.setLayout(self.mainLayout)


    def fillDataTypes(self):
        rosTypes = Interfaces.getRosMessageTypes()
        for type in rosTypes:
            concatType = type['typeDir'] + '/' + type['type']
            self.dataTypeComboBox.addItem(concatType, concatType)


    def addTopicRow(self, name, type, opType):
        rowLayout = QHBoxLayout()
        rowLayout.addWidget(QLabel(name))
        rowLayout.addWidget(QLabel(type))
        rowLayout.addWidget(QLabel(opType))
        removeButton = QPushButton('Remove')
        removeButton.clicked.connect(self.removeTopicClicked)
        removeButton.setObjectName(str(self.count))
        rowLayout.addWidget(removeButton)
        rowContainer = QWidget()
        rowContainer.setLayout(rowLayout)
        rowContainer.setObjectName('row' + str(self.count))
        self.mainLayout.addWidget(rowContainer)
        self.topicRows[self.count] = rowContainer
        self.count += 1


    def addClicked(self):
        if self.config is not None:
            self.config.addTopic(self.count, self.nameEdit.text(), self.dataTypeComboBox.currentData(), self.opTypeComboBox.currentData())
            self.addTopicRow(self.nameEdit.text(), self.dataTypeComboBox.currentData(), self.opTypeComboBox.currentData())
            self.nameEdit.setText('')
            self.configChanged.emit()

    def removeTopicClicked(self):
        if self.config is not None:
            itemToRemove = None
            for i in range(self.mainLayout.count()):
                if self.mainLayout.itemAt(i).widget().objectName() == 'row' + self.sender().objectName():
                    itemToRemove = self.mainLayout.itemAt(i)
                    break
            if itemToRemove is not None:
                self.mainLayout.removeItem(itemToRemove)
                itemToRemove.widget().setParent(None)
                self.mainLayout.update()
                self.configChanged.emit()
            self.config.removeTopic(int(self.sender().objectName()))
            del self.topicRows[int(self.sender().objectName())]


    def clearAllRows(self):
        clearList = []
        for i in range(self.mainLayout.count()):
            item = self.mainLayout.itemAt(i)
            if item.widget().objectName() != 'titleRow':
                clearList.append(item)

        for item in clearList:
            self.mainLayout.removeItem(item)
            item.widget().setParent(None)

        self.mainLayout.update()
        self.count = 0


    def setConfig(self, config):
        self.config = config
        self.clearAllRows()
        for topic in self.config.getTopics():
            topic['id'] = self.count
            self.addTopicRow(topic['name'], topic['type'], topic['opType'])
コード例 #30
0
ファイル: DashboardPage.py プロジェクト: rendtTeam/rendt
class RentingList(QWidget):
    def __init__(self, parent):
        super(RentingList, self).__init__()

        self.parent = parent

        self.setMaximumWidth(1000)

        self.current_theme = self.parent.current_theme
        self.current_font = self.parent.current_font
        self.current_sf = self.parent.current_sf

        if (self.current_theme == 'Dark'):
            self.darkTheme()
        elif (self.current_theme == 'Light'):
            self.lightTheme()
        else:
            self.classicTheme()

        self.requests = []

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(30, 30, 30, 30)
        self.layout.setSpacing(10)
        self.layout.setAlignment(QtCore.Qt.AlignTop)
        self.setLayout(self.layout)

    def addRequests(self):
        self.requests = []

        while (not self.layout.isEmpty()):
            self.layout.removeWidget(self.layout.itemAt(0).widget())

        stats = self.parent.parent.sender.get_job_statuses()

        for job in stats:
            request = RentingRequest(self, job)
            self.requests.append(request)
            self.layout.addWidget(request, alignment=QtCore.Qt.AlignTop)

        if (len(self.requests) == 0):
            request = EmptyRequest(self)
            request.requestLabel.setText('You have no renting requests')
            self.requests.append(request)
            self.layout.addWidget(request, alignment=QtCore.Qt.AlignTop)

            return 0

        return len(self.requests)

    def darkTheme(self):
        self.setStyleSheet('background: rgb(69, 69, 69);\n'
                           'color: white;\n'
                           'border: 0px solid white;\n'
                           'margin: 0px;\n')

    def lightTheme(self):
        self.setStyleSheet('background: rgb(204, 204, 204);\n'
                           'color: white;\n'
                           'border: 0px solid black;\n')

    def classicTheme(self):
        self.setStyleSheet('background: rgb(0, 23, 37);\n'
                           'color: white;\n'
                           'border: 0px solid white;\n')
コード例 #31
0
class GUI(QWidget):
    def __init__(self):
        super().__init__()

        try:
            urlopen('http://maia.usno.navy.mil/ser7/finals2000A.all')
        except HTTPError as e:
            print("Main IERS link not working, using mirror")
            iers.conf.iers_auto_url = 'http://toshi.nofs.navy.mil/ser7/finals2000A.all'
        except URLError as e:
            print("Main IERS link not working, using mirror")
            iers.conf.iers_auto_url = 'http://toshi.nofs.navy.mil/ser7/finals2000A.all'

        #download_IERS_A()

        plt.style.use(astropy_mpl_style)

        irbeneLocation = EarthLocation(lat=57.5535171694 * u.deg, lon=21.8545525000 * u.deg, height=87.30 * u.m)
        self.irbene = Observer(location=irbeneLocation, name="Irbene", timezone="Europe/Riga")

        observe_time = Time(['2019-02-05 15:30:00'])

        self.targets = []
        self.targetsDict = {}
        with open("config/config.csv", "r") as csvfile:
            next(csvfile)
            reader = csv.reader(csvfile, delimiter=",", quotechar="|")
            for row in reader:
                sourceName = row[0]

                raText = row[1]
                raText = insert(raText, 'h', 2)     #Nolasa targets no faila un ievieto targetsDict un targets
                raText = insert(raText, 'm', 5)
                raText = insert(raText, 's', len(raText))

                decText = row[2]
                if (decText[0] != "-"):
                    decText = insert(decText, 'd', 2)
                    decText = insert(decText, 'm', 5)
                    decText = insert(decText, 's', len(decText))
                else:
                    decText = insert(decText, 'd', 3)
                    decText = insert(decText, 'm', 6)
                    decText = insert(decText, 's', len(decText))

                ra = Angle(raText)
                dec = Angle(decText)

                targetCoord = SkyCoord(frame='icrs', ra=ra, dec=dec, obstime="J2000")
                target = FixedTarget(coord=targetCoord, name=sourceName)
                plannedObs = PlannedObs(target, int(row[4]), int(row[3]), int(row[5]))
                self.targets.append(plannedObs)  # target / obs per_week / priority / scans per obs
                coords = {"ra": ra, "dec": dec}
                self.targetsDict[sourceName] = coords

        self.targets = sorted(self.targets, key=lambda x: x.priority)  # sort targets by priority
        self.calibrators = []
        self.calibratorsDict = {}
        with open("config/calibrators.csv", "r") as csvfile:
            next(csvfile)
            reader = csv.reader(csvfile, delimiter=";", quotechar="|")
            for row in reader:
                sourceName = row[0]

                raText = str(row[1]).replace(" ", "")
                raText = insert(raText, 'h', 2)
                raText = insert(raText, 'm', 5)
                raText = insert(raText, 's', len(raText))

                decText = str(row[2]).replace(" ", "")
                if (decText[0] != "-"):
                    decText = insert(decText, 'd', 3)
                    decText = insert(decText, 'm', 6)
                    decText = insert(decText, 's', len(decText))
                else:
                    decText = insert(decText, 'd', 3)
                    decText = insert(decText, 'm', 6)
                    decText = insert(decText, 's', len(decText))            #Nolasa no faila calibratorus un ievieto calibratorsDict un calibrators

                ra = Angle(raText)
                dec = Angle(decText)

                coords = {"ra": ra, "dec": dec}
                self.calibratorsDict[sourceName] = coords
                calibratorCoord = SkyCoord(frame='icrs', ra=ra, dec=dec, obstime="J2000")
                calibrator = FixedTarget(coord=calibratorCoord, name=sourceName)
                self.calibrators.append(calibrator)

        startArray, endArray, summaryArray = get_all_events()       #No google calendar sanem noverosanas datumus un laikus
        self.dateList = QListWidget()

        tempCheck = True
        for i in range(len(startArray)):
            dayStart = parse(startArray[i])
            dayEnd = parse(endArray[i])
            daySummary = summaryArray[i]
            daySummary = daySummary + " " + str(dayStart.date()) + " " + str(dayStart.time()) + "-" + str(dayEnd.time())
            item = QListWidgetItem(daySummary, self.dateList)
            item.setData(Qt.UserRole, [dayStart, dayEnd])               #Izveido listwidget item no datuma un laika un to ievieto listwidget
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            if tempCheck and "maser" in daySummary:
                item.setCheckState(Qt.Checked)
                tempCheck = False
            self.dateList.addItem(item)

        config = configparser.ConfigParser()
        config.read('config/config.ini')
        self.config = config._sections['Default']
        self.config['calibration'] = config['Default'].getboolean('calibration')  #Nolasa config failu


        self.layout = QGridLayout()
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(0,0,0,0)
        self.setLayout(self.layout)
        self.resize(1000, 600)



        self.dateBoxList = []
        self.targetTimesCount = 0
        self.load_ui()

    def load_ui(self):   #Funkcija kas ielade galveno skatu
        self.observationList = QListWidget()
        self.plannedTargets = []
        for target in self.targets[:10]:
            item = QListWidgetItem(str(target), self.observationList)    #Aizpilda planotaju ar 10 targets kurus ieprieks nolasija no faila
            item.setData(Qt.UserRole, target)
            self.observationList.addItem(item)
            self.plannedTargets.append(target.name)

        self.layout.addWidget(self.observationList, 0, 0, 10, 2)

        self.observationList.itemSelectionChanged.connect(self.obsChanged) #Connect savieno kada UI elementa action (piemeram click) ar funkciju koda
                                                                           #Seit mainot izveleto elemntu listwidget izsauksies funkcija obsChanged
        for index in range(self.observationList.count()):
            item = self.observationList.item(index)

        self.targetLayout = QVBoxLayout()
        targetBox = QGroupBox()
        targetBox.setMaximumSize(350, 250)

        line = QHBoxLayout()
        nameLabel = QLabel("Target:")
        self.nameBox = QLineEdit()
        self.nameBox.setEnabled(False)
        nameLabel.setParent(targetBox)
        self.nameBox.setParent(targetBox)
        line.addWidget(nameLabel)
        line.addWidget(self.nameBox)
        self.targetLayout.addLayout(line)

        line = QHBoxLayout()
        priorityLabel = QLabel("Priority:")
        self.priorityBox = QLineEdit()
        priorityLabel.setParent(targetBox)
        self.priorityBox.setParent(targetBox)
        line.addWidget(priorityLabel)
        line.addWidget(self.priorityBox)
        self.targetLayout.addLayout(line)

        line = QHBoxLayout()
        obsLabel = QLabel("Obs per week:")
        self.obsBox = QLineEdit()
        obsLabel.setParent(targetBox)
        self.obsBox.setParent(targetBox)
        line.addWidget(obsLabel)
        line.addWidget(self.obsBox)
        self.targetLayout.addLayout(line)

        line = QHBoxLayout()
        scanLabel = QLabel("Scans per obs:")
        self.scanBox = QLineEdit()
        scanLabel.setParent(targetBox)
        self.scanBox.setParent(targetBox)
        line.addWidget(scanLabel)
        line.addWidget(self.scanBox)
        self.targetLayout.addLayout(line)

        line = QHBoxLayout()
        globalLabel = QLabel("Global time:")
        self.globalTimeBox = QLineEdit()
        line.addWidget(globalLabel)
        line.addWidget(self.globalTimeBox)
        self.targetLayout.addLayout(line)

        line = QHBoxLayout()
        specificLabel = QLabel("Specific times:")
        addTime = QPushButton("Add specific time")
        addTime.clicked.connect(self.add_time)
        line.addWidget(specificLabel)
        line.addWidget(addTime)
        self.targetLayout.addLayout(line)

        saveButton = QPushButton("Save changes")
        saveButton.clicked.connect(self.save_obs_changes)
        self.targetLayout.addWidget(saveButton)

        removeButton = QPushButton("Remove target")
        removeButton.clicked.connect(self.remove_obs)
        self.targetLayout.addWidget(removeButton)

        targetBox.setLayout(self.targetLayout)
        self.layout.addWidget(targetBox, 0, 2, 2, 1)

        self.targetComboBox = QComboBox()
        for key in self.targetsDict:
            if key not in self.plannedTargets:
                self.targetComboBox.addItem(key)
        self.layout.addWidget(self.targetComboBox, 2, 2)

        addButton = QPushButton("Add observation")
        addButton.clicked.connect(self.add_obs)
        self.layout.addWidget(addButton, 3, 2)

        nextButton = QPushButton("Schedule")
        nextButton.clicked.connect(self.prepare_schedule)
        self.layout.addWidget(nextButton, 0, 3)
        datesButton = QPushButton("Dates")
        datesButton.clicked.connect(self.edit_dates)
        self.layout.addWidget(datesButton, 1, 3)
        targetsButton = QPushButton("Targets")
        targetsButton.clicked.connect(self.edit_targets)
        self.layout.addWidget(targetsButton, 2, 3)
        calibratorsButton = QPushButton("Calibrators")
        calibratorsButton.clicked.connect(self.edit_calibrators)
        self.layout.addWidget(calibratorsButton, 3, 3)
        settingsButton = QPushButton("Settings")
        settingsButton.clicked.connect(self.load_settings)
        self.layout.addWidget(settingsButton, 4, 3)
        saveObsButton = QPushButton("Save observation")
        saveObsButton.clicked.connect(self.save_obs)
        self.layout.addWidget(saveObsButton, 5, 3)
        loadObsButton = QPushButton("Load observation")
        loadObsButton.clicked.connect(self.load_obs_new)
        self.layout.addWidget(loadObsButton, 6, 3)

    def add_time(self):    #Pievieno combobox ar izveletajiem datumiem
        datesChecked = 0
        for index in range(self.dateList.count()):
            if self.dateList.item(index).checkState() == Qt.Checked:
                datesChecked = datesChecked + 1
        if datesChecked > self.targetTimesCount:
            line = QHBoxLayout()
            dateBox = QComboBox()
            for index in range(self.dateList.count()):
                if self.dateList.item(index).checkState() == Qt.Checked:
                    dateBox.addItem(self.dateList.item(index).text(), self.dateList.item(index).data(Qt.UserRole))
            dateBox.addItem("Remove")
            dateBox.currentTextChanged.connect(self.timeChanged)
            self.targetTimesCount+= 1
            dateBox.sizePolicy().setHorizontalStretch(1)
            timeBox = QLineEdit()
            timeBox.sizePolicy().setHorizontalStretch(3)
            line.addWidget(dateBox)
            line.addWidget(timeBox)
            self.dateBoxList.append(line)
            self.targetLayout.insertLayout(self.targetLayout.count()-2, line)
        else:
            self.show_error("Date error", "Can't select more times than selected dates")

    def timeChanged(self, item): #Ja pie specifiskajiem laikiem izvelas remove tad iznem to
        if item == "Remove":
            for line in self.dateBoxList:
                if line is not None:
                    item = line.itemAt(0)
                    widget = item.widget()
                    if type(widget) == type(QComboBox()):
                        if widget.currentText() == "Remove":
                            break
            self.targetTimesCount -= 1
            widget.disconnect()
            self.deleteItemsOfLayout(line)
            self.targetLayout.removeItem(line)
            self.dateBoxList.remove(line)


    def obsChanged(self):  #Nomainot observation nomaina visus texta laukus
        if len(self.observationList.selectedItems()) > 0:
            item = self.observationList.currentItem()
            plannedObs = item.data(Qt.UserRole)
            self.nameBox.setText(plannedObs.name)
            self.priorityBox.setText(str(plannedObs.priority))
            self.obsBox.setText(str(plannedObs.obs_per_week))
            self.scanBox.setText(str(plannedObs.scans_per_obs))
            i = 0
            maxi = self.targetLayout.count()
            while(i < maxi):
                layout_item = self.targetLayout.itemAt(i)
                if layout_item in self.dateBoxList:
                    self.deleteItemsOfLayout(layout_item.layout())
                    self.targetLayout.removeItem(layout_item)
                    self.dateBoxList.remove(layout_item)
                    maxi = self.targetLayout.count()
                    i = i -1
                i=i+1
            self.dateBoxList.clear()
            self.targetTimesCount = 0
            if plannedObs.times:
                checkedDates = []
                for index in range(self.dateList.count()):
                    if self.dateList.item(index).checkState() == Qt.Checked:
                        checkedDates.append(self.dateList.item(index).text())
                print(checkedDates)
                for time in list(plannedObs.times):
                    print(time)
                    if time not in checkedDates:    #Ja observation pievienots specifisks laiks datumam kurs vairs netiks izmantots to pazino lietotajam
                        self.show_error("Date mismatch", "Date "+time+" is not checked, removing it")
                        plannedObs.times.remove(time)
                for time in list(plannedObs.times):
                    line = QHBoxLayout()
                    dateBox = QComboBox()
                    for index in range(self.dateList.count()):
                        if self.dateList.item(index).checkState() == Qt.Checked: #Specific laikiem pievieno tikai datumus kas izveleti pie dates
                            dateBox.addItem(self.dateList.item(index).text(), self.dateList.item(index).data(Qt.UserRole))
                    dateBox.addItem("Remove")
                    dateBox.currentTextChanged.connect(self.timeChanged)
                    self.targetTimesCount += 1
                    dateBox.sizePolicy().setHorizontalStretch(1)
                    timeBox = QLineEdit(plannedObs.times[time])
                    timeBox.sizePolicy().setHorizontalStretch(3)
                    line.addWidget(dateBox)
                    line.addWidget(timeBox)
                    self.dateBoxList.append(line)
                    self.targetLayout.insertLayout(self.targetLayout.count() - 2, line)
                    dateBox.setCurrentIndex(dateBox.findText(time))

        else:
            self.nameBox.setText("")
            self.priorityBox.setText("")
            self.obsBox.setText("")
            self.scanBox.setText("")
            self.targetTimesCount = 0

    def remove_obs(self):
        if len(self.observationList.selectedItems()) > 0:
            self.plannedTargets.remove(self.observationList.currentItem().data(Qt.UserRole).name)
            self.targetComboBox.addItem(self.observationList.currentItem().data(Qt.UserRole).name)
            self.observationList.takeItem(self.observationList.currentRow())
        else:
            self.show_error("Observation error","Select an observation to remove it")


    def save_obs_changes(self): #Ja visi teksta lauki atbilst parbaudem tad saglaba datus, ja ne tad pazino lietotajam
        if not self.priorityBox.text().isdigit():
            self.show_error("Priority error", "Priority must be from 1 to 4")
        elif int(self.priorityBox.text()) > 4 or int(self.priorityBox.text()) < 0:
            self.show_error("Priority error", "Priority must be from 1 to 4")
        elif not self.obsBox.text().isdigit():
            self.show_error("Obs error", "Obs must be from 1 to 7")
        elif int(self.obsBox.text()) > 7 or int(self.obsBox.text()) < 0:
            self.show_error("Obs error", "Obs must be from 1 to 7")
        elif not self.scanBox.text().isdigit():
            self.show_error("Scan error", "Scan must be from 1 to 120")
        elif int(self.scanBox.text()) > 120 or int(self.scanBox.text()) < 0:
            self.show_error("Scan error", "Scan must be from 1 to 120")
        elif len(self.dateBoxList) != len(set(self.dateBoxList)):
            self.show_error("Date error", "Make sure specified times don't use same dates")
        else:
            times = {}
            timeCheck = True
            for line in self.dateBoxList:
                if line.count() > 0:
                    item = line.itemAt(0)
                    widget = item.widget()
                    date = widget.currentText()
                    time = date[-17:]
                    time = time.split('-')
                    timeStart = time[0]
                    timeStart = timeStart[:-3]
                    timeEnd = time[1]
                    timeEnd = timeEnd[:-3]
                    time = line.itemAt(1).widget().text()
                    timeCheck = self.time_check(time, timeStart, timeEnd)

                    if timeCheck == False:
                        break
                    else:
                        times[date] = line.itemAt(1).widget().text()

            if timeCheck: #Ja visas parbaudes izietas tad saglaba datus
                self.observationList.currentItem().data(Qt.UserRole).times = times
                self.observationList.currentItem().data(Qt.UserRole).priority = int(self.priorityBox.text())
                self.observationList.currentItem().data(Qt.UserRole).obs_per_week = int(self.obsBox.text())
                self.observationList.currentItem().data(Qt.UserRole).scans_per_obs = int(self.scanBox.text())
                self.observationList.currentItem().data(Qt.UserRole).global_time = self.globalTimeBox.text()
                self.observationList.currentItem().setText(str(self.observationList.currentItem().data(Qt.UserRole)))
            else:
                self.show_error("Specific time error", "Make sure the specific times fit the dates selected")

    def add_obs(self): #Izveido jaunu observation
        if self.targetComboBox.count() > 0:
            targetName = self.targetComboBox.currentText()
            ra = self.targetsDict[targetName]["ra"]
            dec = self.targetsDict[targetName]["dec"]
            coord = SkyCoord(frame='icrs', ra=ra, dec=dec, obstime="J2000")
            target = FixedTarget(coord=coord, name=targetName)
            data = PlannedObs(target, 1, 1, 1)
            item = QListWidgetItem(str(data), self.observationList)
            item.setData(Qt.UserRole, data)
            self.observationList.addItem(item)
            self.plannedTargets.append(data.name)
            self.targetComboBox.removeItem(self.targetComboBox.currentIndex())

    def edit_dates(self): #Atver dates skatu
        self.clear_window()
        self.layout.addWidget(self.dateList, 0, 0, 5, 2)
        backButton = QPushButton("Back to planner")
        self.layout.addWidget(backButton, 1, 2)
        backButton.clicked.connect(self.to_start)

    def edit_targets(self): #Atver targets skatu
        self.clear_window()

        self.targetList = QListWidget()
        for key in self.targetsDict:
            self.targetList.addItem(key)
        self.targetList.itemClicked.connect(self.targetChanged)
        self.layout.addWidget(self.targetList, 0, 0, 3, 1)

        targetLayout = QGridLayout()
        targetLayout.addWidget(QLabel("Ra:"), 0, 0)
        self.raBox = QLineEdit()
        targetLayout.addWidget(self.raBox, 0, 1)
        targetLayout.addWidget(QLabel("Dec:"), 1, 0)
        self.decBox = QLineEdit()
        targetLayout.addWidget(self.decBox, 1, 1)
        self.saveButton = QPushButton("Save changes")
        self.saveButton.clicked.connect(self.save_target_changes)
        targetLayout.addWidget(self.saveButton, 2, 0, 1, 2)
        targetBox = QGroupBox()
        targetBox.setLayout(targetLayout)
        self.layout.addWidget(targetBox, 0, 1)
        self.saveButton.setEnabled(False)

        addTargetLayout = QGridLayout()
        addTargetLayout.addWidget(QLabel("Name:"), 0, 0)
        self.addNameBox = QLineEdit()
        addTargetLayout.addWidget(self.addNameBox, 0, 1)

        addTargetLayout.addWidget(QLabel("Ra:"), 1, 0)
        self.addRaBox = QLineEdit()
        addTargetLayout.addWidget(self.addRaBox, 1, 1)

        addTargetLayout.addWidget(QLabel("Dec:"), 2, 0)
        self.addDecBox = QLineEdit()
        addTargetLayout.addWidget(self.addDecBox, 2, 1)

        self.addSaveButton = QPushButton("Save changes")
        self.addSaveButton.clicked.connect(self.add_target)
        addTargetLayout.addWidget(self.addSaveButton, 3, 0, 1, 2)

        addTargetBox = QGroupBox()
        addTargetBox.setLayout(addTargetLayout)
        self.layout.addWidget(addTargetBox, 1, 1)

        backButton = QPushButton("Back to planner")
        self.layout.addWidget(backButton, 0, 3)
        backButton.clicked.connect(self.to_start)

    def targetChanged(self, item):
        if not self.saveButton.isEnabled():
            self.saveButton.setEnabled(True)
        targetName = item.text()
        target = self.targetsDict[targetName]
        self.raBox.setText(target["ra"].to_string())
        self.decBox.setText(target["dec"].to_string(unit=u.degree))

    def save_target_changes(self):
        if len(self.targetList.selectedItems()) != 1:
            self.show_error("Target error", "Make sure you have selected only 1 target")
        else:
            targetName = self.targetList.selectedItems()[0].text()
            raPattern = re.compile("[0-9]{1,2}h[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,3})?s")
            decPattern = re.compile("-?[0-9]{1,2}d[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,3})?s")
            ra = self.raBox.text()
            dec = self.decBox.text()
            if not raPattern.match(ra):
                self.show_error("Ra error", "Ra coordinates don't match pattern 00h00m00.00s")
            elif not decPattern.match(dec):
                self.show_error("Dec error", "Dec coordinates don't match pattern 00d00m00.00s")
            else:
                self.targetsDict[targetName]["ra"] = Angle(ra)
                self.targetsDict[targetName]["dec"] = Angle(dec)

    def add_target(self): #Pievieno jaunu target
        raPattern = re.compile("[0-9]{1,2}h[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,3})?s")
        decPattern = re.compile("-?[0-9]{1,2}d[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,3})?s")
        ra = self.addRaBox.text()
        dec = self.addDecBox.text()
        name = self.addNameBox.text()
        print(self.targetsDict.keys())
        if ra == "" or dec == "" or name == "":
            self.show_error("Empty box", "Please fill all boxes")
        elif name in self.targetsDict.keys():
            self.show_error("Existing target", "Target already exists, please edit it")
        elif not raPattern.match(ra):
            self.show_error("Ra error", "Ra coordinates don't match pattern 00h00m00.00s")
        elif not decPattern.match(dec):
            self.show_error("Dec error", "Dec coordinates don't match pattern 00d00m00.00s")
        else:
            self.targetsDict[name] = {}
            self.targetsDict[name]["ra"] = Angle(ra)
            self.targetsDict[name]["dec"] = Angle(dec)
            self.edit_targets()

    def edit_calibrators(self): #Atver calibrators skatu
        self.clear_window()

        self.calibratorList = QListWidget()
        for key in self.calibratorsDict:
            self.calibratorList.addItem(key)
        self.calibratorList.itemClicked.connect(self.calibratorChanged)
        self.layout.addWidget(self.calibratorList, 0, 0, 3, 1)

        calibratorLayout = QGridLayout()
        calibratorLayout.addWidget(QLabel("Ra:"), 0, 0)
        self.raBox = QLineEdit()
        calibratorLayout.addWidget(self.raBox, 0, 1)
        calibratorLayout.addWidget(QLabel("Dec:"), 1, 0)
        self.decBox = QLineEdit()
        calibratorLayout.addWidget(self.decBox, 1, 1)
        self.saveButton = QPushButton("Save changes")
        self.saveButton.clicked.connect(self.save_calibrator_changes)
        calibratorLayout.addWidget(self.saveButton, 2, 0, 1, 2)
        calibratorBox = QGroupBox()
        calibratorBox.setLayout(calibratorLayout)
        self.layout.addWidget(calibratorBox, 0, 1)
        self.saveButton.setEnabled(False)

        addcalibratorLayout = QGridLayout()
        addcalibratorLayout.addWidget(QLabel("Name:"), 0, 0)
        self.addNameBox = QLineEdit()
        addcalibratorLayout.addWidget(self.addNameBox, 0, 1)

        addcalibratorLayout.addWidget(QLabel("Ra:"), 1, 0)
        self.addRaBox = QLineEdit()
        addcalibratorLayout.addWidget(self.addRaBox, 1, 1)

        addcalibratorLayout.addWidget(QLabel("Dec:"), 2, 0)
        self.addDecBox = QLineEdit()
        addcalibratorLayout.addWidget(self.addDecBox, 2, 1)

        self.addSaveButton = QPushButton("Save changes")
        self.addSaveButton.clicked.connect(self.add_calibrator)
        addcalibratorLayout.addWidget(self.addSaveButton, 3, 0, 1, 2)

        addcalibratorBox = QGroupBox()
        addcalibratorBox.setLayout(addcalibratorLayout)
        self.layout.addWidget(addcalibratorBox, 1, 1)

        backButton = QPushButton("Back to planner")
        self.layout.addWidget(backButton, 0, 3)
        backButton.clicked.connect(self.to_start)

    def calibratorChanged(self, item):
        if not self.saveButton.isEnabled():
            self.saveButton.setEnabled(True)
        calibratorName = item.text()
        calibrator = self.calibratorsDict[calibratorName]
        self.raBox.setText(calibrator["ra"].to_string())
        self.decBox.setText(calibrator["dec"].to_string(unit=u.degree))

    def save_calibrator_changes(self):
        if len(self.calibratorList.selectedItems()) != 1:
            self.show_error("calibrator error", "Make sure you have selected only 1 calibrator")
        else:
            calibratorName = self.calibratorList.selectedItems()[0].text()
            raPattern = re.compile("[0-9]{1,2}h[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,5})?s")
            decPattern = re.compile("-?[0-9]{1,2}d[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,5})?s")
            ra = self.raBox.text()
            dec = self.decBox.text()
            if not raPattern.match(ra):
                self.show_error("Ra error", "Ra coordinates don't match pattern 00h00m00.00s")
            elif not decPattern.match(dec):
                self.show_error("Dec error", "Dec coordinates don't match pattern 00d00m00.00s")
            else:
                self.calibratorsDict[calibratorName]["ra"] = Angle(ra)
                self.calibratorsDict[calibratorName]["dec"] = Angle(dec)

    def add_calibrator(self):
        raPattern = re.compile("[0-9]{1,2}h[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,5})?s")
        decPattern = re.compile("-?[0-9]{1,2}d[0-9]{1,2}m[0-9]{1,2}(\.[0-9]{1,5})?s")
        ra = self.addRaBox.text()
        dec = self.addDecBox.text()
        name = self.addNameBox.text()
        print(self.calibratorsDict.keys())
        if ra == "" or dec == "" or name == "":
            self.show_error("Empty box", "Please fill all boxes")
        elif name in self.calibratorsDict.keys():
            self.show_error("Existing calibrator", "calibrator already exists, please edit it")
        elif not raPattern.match(ra):
            self.show_error("Ra error", "Ra coordinates don't match pattern 00h00m00.00s")
        elif not decPattern.match(dec):
            self.show_error("Dec error", "Dec coordinates don't match pattern 00d00m00.00s")
        else:
            self.calibratorsDict[name] = {}
            self.calibratorsDict[name]["ra"] = Angle(ra)
            self.calibratorsDict[name]["dec"] = Angle(dec)
            self.edit_calibrators()


    def load_settings(self): #Atver settings skatu
        self.clear_window()
        targetLayout = QFormLayout()
        targetBox = QGroupBox()
        targetBox.setMaximumSize(350, 250)

        calibLabel = QLabel("Calib every X min:")
        self.calibBox = QLineEdit()
        calibLabel.setParent(targetBox)
        self.calibBox.setParent(targetBox)
        self.calibBox.setText(self.config['maxtimewithoutcalibration'])
        targetLayout.addRow(calibLabel, self.calibBox)

        calibDurLabel = QLabel("Calib duration:")
        self.calibDurBox = QLineEdit()
        calibDurLabel.setParent(targetBox)
        self.calibDurBox.setParent(targetBox)
        self.calibDurBox.setText(self.config['calibrationlength'])
        targetLayout.addRow(calibDurLabel, self.calibDurBox)

        minAltLabel = QLabel("Min alt:")
        self.minAltBox = QLineEdit()
        minAltLabel.setParent(targetBox)
        self.minAltBox.setParent(targetBox)
        self.minAltBox.setText(self.config['minaltitude'])
        targetLayout.addRow(minAltLabel, self.minAltBox)

        maxAltLabel = QLabel("Max alt:")
        self.maxAltBox = QLineEdit()
        maxAltLabel.setParent(targetBox)
        self.maxAltBox.setParent(targetBox)
        self.maxAltBox.setText(self.config['maxaltitude'])
        targetLayout.addRow(maxAltLabel, self.maxAltBox)

        calibToggleLabel = QLabel("Calibration on/off")
        self.calibCheckBox = QCheckBox()
        calibToggleLabel.setParent(targetBox)
        self.calibCheckBox.setParent(targetBox)
        if (self.config['calibration']):
            self.calibCheckBox.setChecked(True)
        else:
            self.calibCheckBox.setChecked(False)
        targetLayout.addRow(calibToggleLabel, self.calibCheckBox)

        saveButton = QPushButton("Save settings")
        saveButton.clicked.connect(self.save_settings)
        targetLayout.addRow(saveButton)

        targetBox.setLayout(targetLayout)
        self.layout.addWidget(targetBox, 0, 2, 2, 1)

    def save_settings(self):
        if not (self.calibBox.text().isdigit() and int(self.calibBox.text()) > 0):
            self.show_error("Input error","Max time without calib must be positive number")
        elif not (self.calibDurBox.text().isdigit() and int(self.calibDurBox.text()) > 0):
            self.show_error("Input error","Calib duration must be positive number")
        elif not (self.minAltBox.text().isdigit() and int(self.minAltBox.text()) > 0):
            self.show_error("Input error","Min alt must be positive number")
        elif not (self.maxAltBox.text().isdigit() and int(self.maxAltBox.text()) > 0):
            self.show_error("Input error","Max alt must be positive number")
        else:
            self.config['maxtimewithoutcalibration'] = self.calibBox.text()
            self.config['calibrationlength'] = self.calibDurBox.text()
            self.config['minaltitude'] = self.minAltBox.text()
            self.config['maxaltitude'] = self.maxAltBox.text()
            self.config['calibration'] = self.calibCheckBox.isChecked()
            self.to_start()

    def prepare_schedule(self): #Pirms uzsak planosanu, parbauda vai ir izvelets kads datums
        hasDate = False
        for index in range(self.dateList.count()):
            if self.dateList.item(index).checkState() == Qt.Checked:
                hasDate = True
                break
        if not hasDate:
            self.show_error("Date error", "No dates selected for schedule")
        else:
            self.start_schedule()

    def start_schedule(self): #Sak planosanu
        items = (self.layout.itemAt(i).widget() for i in range(self.layout.count()))
        self.targets = []

        for index in range(self.observationList.count()):
            item = self.observationList.item(index)
            target = item.data(Qt.UserRole)
            self.targets.append(target)  #Visus obs ievieto masiva targets

        targ_to_color = {}
        color_idx = np.linspace(0, 1, len(self.targets))

        for target, ci in zip(set(self.targets), color_idx): #Katram target un calibrator pieskir savu krasu
            if "split" not in target.name:
                if target.name not in targ_to_color:
                    targ_to_color[target.name] = plt.cm.jet(ci)

        calib_to_color = {}
        color_idx = np.linspace(0, 1, len(self.calibrators))

        for calibrator, ci in zip(set(self.calibrators), color_idx):
            if "split" not in calibrator.name:
                if calibrator.name not in calib_to_color:
                    calib_to_color[calibrator.name] = plt.cm.brg(ci)

        self.plots_idx = 0
        self.plots = []

        week = {}

        for index in range(self.dateList.count()):
            if self.dateList.item(index).checkState() == Qt.Checked: #Dates ievieto dict week
                week[self.dateList.item(index).text()]=[self.dateList.item(index).data(Qt.UserRole)[0], self.dateList.item(index).data(Qt.UserRole)[1]]


        for daySummary, day in week.items():

            dayStart = Time(day[0])  # convert from datetime to astropy.time
            dayEnd = Time(day[1])

            timeDict = {}

            for target in self.targets:
                if daySummary in target.times:
                    timeDict[target.name] = target.times[daySummary] #Pievieno specifiskos laikus dict timeDict
                elif target.global_time != "":
                    timeDict[target.name] = target.global_time

            minalt = self.config['minaltitude']
            maxalt = self.config['maxaltitude']

            constraints = [AltitudeConstraint(minalt * u.deg, maxalt * u.deg)]

            read_out = 1 * u.second
            target_exp = 60 * u.second
            blocks = []

            for target in self.targets:
                n = target.scans_per_obs
                priority = target.priority
                if (target.obs_per_week != 0): #Ja observation vel ir janovero tad izveido ObservingBlock
                    b = ObservingBlock.from_exposures(target.target, priority, target_exp, n, read_out)
                    blocks.append(b)


            slew_rate = 2 * u.deg / u.second
            transitioner = Transitioner(slew_rate, {'filter': {'default': 5 * u.second}})

            if (self.config['calibration']): #Padod mainigos planotajam
                prior_scheduler = SequentialScheduler(constraints=constraints, observer=self.irbene, transitioner=transitioner,
                                                      calibrators=self.calibrators, config=self.config, timeDict=timeDict)

                priority_schedule = Schedule(dayStart, dayEnd, targColor=targ_to_color, calibColor=calib_to_color, minalt=minalt, maxalt=maxalt)
            else:
                prior_scheduler = SequentialScheduler(constraints=constraints, observer=self.irbene,
                                                      transitioner=transitioner,
                                                      config=self.config, timeDict=timeDict)

                priority_schedule = Schedule(dayStart, dayEnd, targColor=targ_to_color, minalt=minalt, maxalt=maxalt)

            prior_scheduler(blocks, priority_schedule)

            observations = []
            for block in priority_schedule.scheduled_blocks:
                if hasattr(block, 'target'):
                    observation = Observation(block.target.name, block.start_time.datetime,
                                              (block.start_time + block.duration).datetime)
                    observations.append(observation)

            dict_array = []
            for observation in observations: #Saplanotos block nolasa un ieraksta faila
                for target in self.targets:
                    if target.name == observation.name:
                        print(target.name, " has been observed once")
                        target.obs_per_week -= 1
                dict_array.append({
                    "obs_name": observation.name,
                    "start_time": observation.start_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "end_time": observation.end_time.strftime("%Y-%m-%d %H:%M:%S"),
                })

            json_dict = dict()
            json_dict["observations"] = dict_array
            if not os.path.isdir("observations"):
                os.mkdir("observations")
            if not os.path.isdir("observations/"):
                os.mkdir("observations")
            with open("observations/" + day[0].strftime("%Y-%m-%d-%H-%M") + ".json", 'w') as outfile:
                json.dump(json_dict, outfile, indent=4)


            sky = Plot() #Izveido grafikus
            skyCheck = sky.plot_sky_schedule(priority_schedule)
            alt = Plot(width=6)
            alt.plot_altitude_schedule(priority_schedule)

            if skyCheck is not False:
                self.plots.append([sky, alt])
            else:
                self.show_error("Empty schedule", "Schedule "+daySummary+"removing it")

        timeLeft = 0
        for target in self.targets:
            timeLeft += target.obs_per_week * target.scans_per_obs
            print(target.name, ' observations left ', target.obs_per_week, ' scan size ', target.scans_per_obs, ' priority ', target.priority)
        print('Total time left to observe ', timeLeft)

        self.showSky = False
        self.showAlt = False
        self.showBoth = True

        self.show_schedule()

    def show_schedule(self): #Atver grafiku skatu
        self.clear_window()

        sky, alt = self.plots[self.plots_idx]

        if self.showSky:
            self.layout.addWidget(sky, 0, 0, 2, 6)

        elif self.showAlt:
            self.layout.addWidget(alt, 0, 0, 2, 6)

        elif self.showBoth:
            self.layout.addWidget(sky, 0, 0, 1, 6)
            self.layout.addWidget(alt, 1, 0, 1, 6)

        self.toolbar = NavigationToolbar(alt, alt.parent)
        self.layout.addWidget(self.toolbar, 2, 0, 1, 3)

        self.radioSky = QRadioButton("Show skychart")
        self.radioAlt = QRadioButton("Show altitude")
        self.radioBoth = QRadioButton("Show both")

        self.radioSky.clicked.connect(self.changeScheduleView)
        self.radioAlt.clicked.connect(self.changeScheduleView)
        self.radioBoth.clicked.connect(self.changeScheduleView)


        self.layout.addWidget(self.radioSky, 2, 3)
        self.layout.addWidget(self.radioAlt, 2, 4)
        self.layout.addWidget(self.radioBoth, 2, 5)

        nextButton = QPushButton("Next")
        nextButton.clicked.connect(self.next_schedule)
        backButton = QPushButton("Back")
        backButton.clicked.connect(self.back_schedule)
        self.layout.addWidget(backButton, 3, 0, 1, 3)
        self.layout.addWidget(nextButton, 3, 3, 1, 3)

        startButton = QPushButton("To start")
        startButton.clicked.connect(self.to_start)
        self.layout.addWidget(startButton, 4, 0, 1, 3)

        if self.plots_idx == 0:
            backButton.hide()
        if self.plots_idx == (len(self.plots) - 1):
            nextButton.hide()

    def next_schedule(self):
        self.plots_idx += 1
        self.show_schedule()

    def changeScheduleView(self):
        radioText = self.sender().text()
        if "sky" in radioText:
            self.showSky = True
            self.showAlt = False
            self.showBoth = False
            self.show_schedule()
            self.radioSky.setChecked(True)
        elif "alt" in radioText:
            self.showSky = False
            self.showAlt = True
            self.showBoth = False
            self.show_schedule()
            self.radioAlt.setChecked(True)
        elif "both" in radioText:
            self.showSky = False
            self.showAlt = False
            self.showBoth = True
            self.show_schedule()
            self.radioBoth.setChecked(True)

    def back_schedule(self):
        self.plots_idx -= 1
        self.show_schedule()

    def save_obs(self):
        filename = self.saveFileDialog()
        if filename != "Fail":
            obsList = [self.observationList.item(i).data(Qt.UserRole) for i in range(self.observationList.count())]
            json_dict = dict()
            for obs in obsList:
                json_dict[obs.target.name]={
                    "priority": obs.priority,
                    "obs_per_week": obs.obs_per_week,
                    "scans_per_obs": obs.scans_per_obs,
                    "global_time": obs.global_time,
                    "times": obs.times,
                }
            print(json_dict)
            with open(filename, 'w') as outfile:
                json.dump(json_dict, outfile, indent=4)


    def saveFileDialog(self):
        save = QFileDialog()
        save.setDefaultSuffix(".json")
        save.setNameFilter("JSON files (*.json)")
        save.setAcceptMode(QFileDialog.AcceptSave)
        save.setOption(QFileDialog.DontUseNativeDialog)
        if save.exec_() == QFileDialog.Accepted:
            return save.selectedFiles()[0]
        else:
            return "Fail"

    def load_obs(self):
        load = QFileDialog()
        load.setDefaultSuffix(".json")
        load.setNameFilter("JSON files (*.json)")
        load.setAcceptMode(QFileDialog.AcceptOpen)
        load.setOption(QFileDialog.DontUseNativeDialog)
        if load.exec_() == QFileDialog.Accepted:
            filename = load.selectedFiles()[0]
            with open(filename) as json_file:
                obs_dict = json.load(json_file)
                self.observationList.clear()
                for key in obs_dict:
                    if key in self.targetsDict:
                        targetName = key
                        ra = self.targetsDict[targetName]["ra"]
                        dec = self.targetsDict[targetName]["dec"]
                        coord = SkyCoord(frame='icrs', ra=ra, dec=dec, obstime="J2000")
                        target = FixedTarget(coord=coord, name=targetName)
                        for date in obs_dict[key]['times']:
                            print(date)

                            # TODO Te pielikt date parbaudes, vai atkekset ja ir vai iznemt ja nav

                        data = PlannedObs(target, int(obs_dict[key]['priority']), int(obs_dict[key]['obs_per_week']),
                                          int(obs_dict[key]['scans_per_obs']), obs_dict[key]['times'],
                                          obs_dict[key]['global_time'])
                        item = QListWidgetItem(str(data), self.observationList)
                        item.setData(Qt.UserRole, data)
                        self.observationList.addItem(item)
                        self.plannedTargets.append(target.name)
                    else:
                        self.show_error("Target error", key + " not in targets, skipping it")
        else:
            print("Something went wrong")

    def load_obs_new(self):
        load = QFileDialog()
        load.setDefaultSuffix(".conf")
        load.setNameFilter("CONF files (*.conf)")
        load.setAcceptMode(QFileDialog.AcceptOpen)
        load.setOption(QFileDialog.DontUseNativeDialog)
        if load.exec_() == QFileDialog.Accepted:
            self.observationList.clear()
            filename = load.selectedFiles()[0]
            configObs = configparser.ConfigParser()
            configObs.read(filename)
            sections = configObs.sections()
            for section in sections:
                target = section.split('_')[0]
                ra = configObs[section]["RA"]
                dec = configObs[section]["DEC"]

                if target not in self.targetsDict.keys():
                    coords = {"ra": Angle(ra), "dec": Angle(dec)}
                    self.targetsDict[target] = coords
                else:
                    if Angle(ra) != Angle(self.targetsDict[target]["ra"]) or Angle(dec) != Angle(self.targetsDict[target]["dec"]):
                        qm = QMessageBox
                        ret = qm.question(self,'', target+" has different coords in the load file, would you like to overwrite the current ones?\n"+
                                                            "new coords:"+str(ra)+";   "+str(dec)+"\ncurrent coords:"+str(self.targetsDict[target]["ra"])+";   "+str(self.targetsDict[target]["dec"]), qm.Yes | qm.No)
                        if ret == qm.Yes:
                            self.targetsDict[target]["ra"] = Angle(ra)
                            self.targetsDict[target]["dec"] = Angle(dec)

                targetName = target
                ra = self.targetsDict[targetName]["ra"]
                dec = self.targetsDict[targetName]["dec"]
                coord = SkyCoord(frame='icrs', ra=ra, dec=dec, obstime="J2000")
                target = FixedTarget(coord=coord, name=targetName)

                data = PlannedObs(target, 1, 1, int(configObs[section]["n_scans"]), None, None)
                item = QListWidgetItem(str(data), self.observationList)
                item.setData(Qt.UserRole, data)
                self.observationList.addItem(item)
                self.plannedTargets.append(target.name)

        else:
            print("Something went wrong")


    def show_error(self, title, error_message):
        error_dialog = QMessageBox.critical(self, title, error_message)

    def to_start(self):
        self.clear_window()
        self.load_ui()

    def clear_window(self):
        for i in reversed(range(self.layout.count())):
            self.layout.itemAt(i).widget().setParent(None)

    def is_time_format(self, string):
        p = re.compile('^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$')
        print(string)
        res = bool(p.match(string))
        return res

    def time_check(self, time, timeStart, timeEnd):
        if not self.is_time_format(time):
            return False
        else:
            time = time.split(':')
            timeStart = timeStart.split(':')
            timeEnd = timeEnd.split(':')
            if int(time[0]) < int(timeStart[0]) or int(time[0]) > int(timeEnd[0]):
                return False
            elif int(time[0]) > int(timeStart[0]) and int(time[0]) < int(timeEnd[0]):
                return True
            elif (int(time[0]) == int(timeStart[0]) and int(time[1]) < int(timeStart[1])) or (int(time[0]) == int(timeEnd[0]) and int(time[1]) > int(timeEnd[1])):
                return False
            elif (int(time[0]) == int(timeStart[0]) and int(time[1]) >= int(timeStart[1])) or (int(time[0]) == int(timeEnd[0]) and int(time[1]) < int(timeEnd[1])):
                return True

    def deleteItemsOfLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.setParent(None)
                else:
                    self.deleteItemsOfLayout(item.layout())
コード例 #32
0
ファイル: scenario_group_dialog.py プロジェクト: LLNL/RASE
class GroupSettings(QDialog):
    """Simple Dialog to allow the user to select which groups a scenario is in.
    This information is stored in the scenario_groups table value for each scenario.

    :param parent: the parent dialog
    """
    def __init__(self, parent=None, groups=[], scens=None, del_groups=False):
        QDialog.__init__(self, parent)
        self.groups = groups
        self.scens = scens
        self.del_groups = del_groups
        self.session = Session()

        self.makeLayout()

    def makeLayout(self):
        cols_list = [grp.name for grp in self.session.query(ScenarioGroup)]
        cols_list.insert(0, cols_list.pop(cols_list.index('default_group')))
        cb_list = [QCheckBox(v.replace('&', '&&')) for v in cols_list]

        self.layout = QVBoxLayout()
        self.checklayout = QVBoxLayout()
        self.buttonlayout = QVBoxLayout()

        for cb in cb_list:
            self.checklayout.addWidget(cb)
            if cb.text() in self.groups:
                cb.setChecked(True)
            if cb.text() == 'default_group' and self.del_groups:
                cb.setEnabled(False)

        self.btn_newgroup = QPushButton('Add New Group')
        self.buttonlayout.addWidget(self.btn_newgroup)
        self.btn_newgroup.clicked.connect(self.addCheckbox)
        self.buttonBox = QDialogButtonBox(self)

        if self.del_groups:
            self.btn_deletegroup = QPushButton('Remove Group(s)')
            self.buttonlayout.addWidget(self.btn_deletegroup)
            self.btn_deletegroup.clicked.connect(self.delGroup)
            self.buttonBox.setStandardButtons(QDialogButtonBox.Close)
            self.buttonBox.rejected.connect(self.reject)
        else:
            self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                              | QDialogButtonBox.Ok)
            self.buttonBox.accepted.connect(self.accept)
            self.buttonBox.rejected.connect(self.reject)
        self.buttonlayout.addWidget(self.buttonBox)

        self.layout.addLayout(self.checklayout)
        self.layout.addLayout(self.buttonlayout)
        if not self.del_groups and self.scens and len(self.scens) > 1:
            self.info = QLabel(
                'NOTE: A group box is checked if\nany one of the selected scenarios\nis in that '
                'group. Pressing OK will\nadd all selected scenarios to the\nselected groups.'
            )
            self.layout.addWidget(self.info)
        self.setLayout(self.layout)

    def _cb_list(self):
        return [
            self.checklayout.itemAt(i).widget()
            for i in range(self.checklayout.count())
        ]

    def addCheckbox(self):
        newgroup, okPressed = QInputDialog.getText(self,
                                                   "Add New Scenario Group",
                                                   "Scenario Group name:",
                                                   QLineEdit.Normal, "")
        collist = [grp.name for grp in self.session.query(ScenarioGroup)]
        if okPressed and (newgroup != '' and newgroup not in collist):
            self.checklayout.addWidget(QCheckBox(newgroup))
            self.setLayout(self.layout)
            self.add_groups(self.session, newgroup)

    def delGroup(self):
        del_groups = [cb.text() for cb in self._cb_list() if cb.isChecked()]
        if len(del_groups) > 1:
            answer = QMessageBox(
                QMessageBox.Question, 'Delete Scenario Groups',
                'Are you sure you want to delete these scenario groups? '
                'Scenarios in these groups will not be deleted')
        else:
            answer = QMessageBox(
                QMessageBox.Question, 'Delete Scenario Group',
                'Are you sure you want to delete this scenario group? '
                'Scenarios in this group will not be deleted')
        answer.addButton(QMessageBox.Yes)
        answer.addButton(QMessageBox.No)
        ans_hold = answer.exec()
        if ans_hold == QMessageBox.Yes:
            for group in del_groups:
                self.delete_groups(self.session, group)
            for cb in self._cb_list():
                if cb.text() in del_groups:
                    self.checklayout.removeWidget(cb)
                    cb.deleteLater()

    @staticmethod
    def delete_groups(session, group):
        group_delete = session.query(ScenarioGroup).filter(
            ScenarioGroup.name == group)
        group_delete.delete()
        session.commit()

    @staticmethod
    def add_groups(session, group):
        session.add(ScenarioGroup(name=group))
        session.commit()

    @pyqtSlot()
    def accept(self):
        """
        Adds the scenario to the checked groups
        """
        self.n_groups = [cb.text() for cb in self._cb_list() if cb.isChecked()]
        if self.scens:
            for scen in self.scens:
                scen.scenario_groups.clear()
                for groupname in self.n_groups:
                    scen.scenario_groups.append(
                        self.session.query(ScenarioGroup).filter_by(
                            name=groupname).first())
            self.session.commit()
        return QDialog.accept(self)
コード例 #33
0
class Contacts(QWidget):
    def __init__(self, db):
        self.dic_wind = {}
        self.dic_button = {}
        self.dic_err_win = {}
        self.layout = None
        self.mygroupbox = QGroupBox('Contacts list')
        self.myform = QFormLayout()
        self.scroll = QScrollArea()
        self.db = db
        self.google_api = Google()
        super().__init__()

    def init_ui(self):
        sender = self.sender()
        error = None
        if sender is not None:
            if sender.text() == '&VK':
                if not self.db.db_exists():
                    error = self.db.create(download_data(sender.text()))
                else:
                    error = self.db.update_database(
                        download_data(sender.text()))
            if sender.text() == '&Facebook':
                if not self.db.db_exists():
                    error = self.db.create(download_data(sender.text()))
                else:
                    error = self.db.update_database(
                        download_data(sender.text()))

        if error is not None:
            self.dic_err_win[error] = ErrorWindow(error)
            self.dic_err_win[error].init_ui()
        else:
            for friend in self.db.get_list_users():
                button = self.create_button(friend)
                self.myform.addRow(button)

            self.mygroupbox.setLayout(self.myform)

            self.scroll.setWidget(self.mygroupbox)
            self.scroll.setWidgetResizable(True)
            self.scroll.setFixedHeight(600)
            self.layout = QVBoxLayout(self)
            self.layout.addWidget(self.scroll)

    def create_button(self, friend):
        name = friend
        button = QPushButton(name, self)
        self.dic_button[name] = button
        inf_friend = self.db.get_user_inf(friend)
        if inf_friend['picture'] != '':
            logo = inf_friend['picture']

        self.dic_wind[name] = Window(name, logo,
                                     inf_friend, self, self.google_api)
        button.clicked.connect(lambda: self.dic_wind[name].init_ui())
        return button

    def import_all_contacts(self):
        list_users = self.db.get_list_users()
        if len(list_users) != 0:
            open_new('https://contacts.google.com')
            for contact in list_users:
                contact_data = self.db.get_user_inf(contact)
                self.google_api.create_contact(
                    self.google_api.create_xml(contact_data))

    def redrawing(self):
        self.clear_window()
        self.init_ui()

    def clear_layout(self, layout):
        for i in range(layout.count()):
            if layout.itemAt(i) is not None:
                layout.itemAt(i).widget().setParent(None)

    def clear_window(self):
        for i in range(self.layout.count()):
            if self.layout.itemAt(i) is not None:
                if self.layout.itemAt(i).layout() is not None:
                    self.clear_layout(self.layout.itemAt(i).layout())
                    self.layout.itemAt(i).layout().setParent(None)
                if self.layout.itemAt(i).widget() is not None:
                    self.layout.itemAt(i).widget().setParent(None)
コード例 #34
0
ファイル: equalizer.py プロジェクト: oltulu/zvvradio
class Equalizer(QWidget):
	"""Equalizer class"""
	def __init__(self, parentWidget):
		super().__init__()
		self.parentWidget = parentWidget
		self.create_widgets()

	def create_widgets(self):
		"""Create widgets"""
		self.USER_PRESETS_PATH = os.path.join(paths.APP_FOLDER, "presets")
		if not os.path.exists(self.USER_PRESETS_PATH):
			os.mkdir(self.USER_PRESETS_PATH)
		self.settings = QSettings(paths.CONFIG_PATH, QSettings.IniFormat)
		
		#EQUALIZER
		self.eq = vlc.AudioEqualizer()
		
#vbox_main
		self.vbox_main = QVBoxLayout()
		self.vbox_main.setContentsMargins(1, 1, 1, 1)
		self.vbox_main.setSpacing(3)
		self.setLayout(self.vbox_main)

	#add hbox turn and presets
		self.hbox_presets = QHBoxLayout()
		self.vbox_main.addLayout(self.hbox_presets)
		#turn
		self.turn_eq = QCheckBox(self.tr("Eq on/off"))
		self.turn_eq.stateChanged.connect(self.on_off_eq)
		self.hbox_presets.addWidget(self.turn_eq)
		#combo presets
		self.combo_presets = QComboBox()
		self.combo_presets.setFixedHeight(32)
		self.hbox_presets.addWidget(self.combo_presets)
		default_path_presets = os.path.join(os.getcwd(), "presets")
		list_presets = os.listdir(default_path_presets)
		list_presets.sort()
		self.combo_presets.addItem(self.tr("Choose:"))
		for item in list_presets:
			self.combo_presets.addItem(item)
		user_presets_list = os.listdir(self.USER_PRESETS_PATH)
		user_presets_list.sort()
		for item in user_presets_list:
			self.combo_presets.addItem(item)
		self.combo_presets.activated.connect(self.choose_preset)
		#button_menu
		self.button_menu = QPushButton()
		self.button_menu.setFixedSize(32, 32)
		self.button_menu.setIconSize(QSize(28, 28))
		self.button_menu.setIcon(QIcon(':/more_icon.png'))
		self.button_menu.setStyleSheet(styles.get_button_style())
		self.button_menu.setCursor(Qt.PointingHandCursor)
		self.hbox_presets.addWidget(self.button_menu)
		self.menu_tools = QMenu()
		self.menu_tools.addAction(QIcon(':/accept_icon.png'), self.tr("Accept"), self.press_accept)
		self.menu_tools.addAction(QIcon(':/save_icon.png'), self.tr("Save"), self.open_widget_save)
		self.menu_tools.addAction(QIcon(':/reset_icon.png'), self.tr("Reset"), self.press_reset)
		self.button_menu.setMenu(self.menu_tools)
		
	#widget_preset_save
		self.widget_preset_save = Widget_save(self)
		self.widget_preset_save.hide()
		self.vbox_main.addWidget(self.widget_preset_save)

	#add scroll slider
		self.scroll_sliders = QScrollArea()
		self.scroll_sliders.setWidgetResizable(True)
		self.vbox_main.addWidget(self.scroll_sliders)
		#add sliders vbox
		self.widget_sliders = QWidget()
		self.scroll_sliders.setWidget(self.widget_sliders)
		self.vbox_sliders = QVBoxLayout()
		self.widget_sliders.setLayout(self.vbox_sliders)
		
		#list_sliders
		self.list_sliders = []
		
		#list_sliders_names
		self.list_slider_names = [
								"Preamp:", "31 Hz:", "62 Hz:",
								"125 Hz:", "250 Hz:", "500 Hz:",
								"1 KHz:", "2 KHz", "4 KHz:",
								"8 KHz:", "16 KHz:",
							]
		for item in self.list_slider_names:
			index = self.list_slider_names.index(item)
			self.hbox = QHBoxLayout()
			self.vbox_sliders.addLayout(self.hbox)
			self.label_name = QLabel(item + '\t')
			self.hbox.addWidget(self.label_name)
			self.slider = Slider_band()
			self.list_sliders.append(self.slider)
			self.slider.BAND_NUM = index
			self.slider.valueChanged.connect(self.change_slider_num)
			self.hbox.addWidget(self.slider)
			self.label_value = QLabel()
			self.hbox.addWidget(self.label_value)
			
		#AUTORUN
		self.check_sliders()
##############################################################################

	def press_save_new_preset(self):
		"""Press save new preset"""
		name_preset = self.widget_preset_save.line_preset_name.text()
		if name_preset:
			name_preset = "*" + name_preset + '.json'
			full_path_preset = os.path.join(self.USER_PRESETS_PATH, name_preset)
			#get values
			list_nums = []
			for slider in self.list_sliders:
				list_nums.append(slider.value())
			#save
			with open(full_path_preset, 'w', encoding='utf-8') as file_save:
				json.dump(list_nums, file_save)
			self.widget_preset_save.hide()
			self.combo_presets.addItem(name_preset)

	def open_widget_save(self):
		"""Show/hide save widget then save button pressed"""
		if self.widget_preset_save.isVisible():
			self.widget_preset_save.hide()
		else:
			self.widget_preset_save.show()

	def choose_preset(self):
		"""Choose preset"""
		if self.combo_presets.currentIndex() > 0:
			presets_path = os.path.join(os.getcwd(), "presets")
			current_text = self.combo_presets.currentText()
			if current_text[0] == "*":
				presets_path = self.USER_PRESETS_PATH
			get_preset_path = os.path.join(presets_path, current_text)
			if os.path.exists(get_preset_path):
				with open(get_preset_path, 'r', encoding='utf-8') as file_load:
					list_nums = json.load(file_load)
					for slider in self.list_sliders:
						index = self.list_sliders.index(slider)
						value = list_nums[index]
						slider.setValue(value)
						if index == 0:
							self.eq.set_preamp(value)
							self.vbox_sliders.itemAt(index).itemAt(2).widget().setText(str(value))
						else:
							if index > 0:
								self.eq.set_amp_at_index(value, index-1)
								self.vbox_sliders.itemAt(index).itemAt(2).widget().setText(str(value))
			self.press_accept()
		else:
			self.press_reset()

	def on_off_eq(self):
		"""On/Off equalizer"""
		self.check_sliders()
		self.check_equalizer()
		
	def check_sliders(self):
		"""Check sliders"""
		if self.turn_eq.isChecked():
			self.combo_presets.setEnabled(True)
			for slider in self.list_sliders:
				slider.setEnabled(True)
		else:
			self.combo_presets.setEnabled(False)
			for slider in self.list_sliders:
				slider.setEnabled(False)

	def check_equalizer(self):
		"""Check equalizer"""
		if self.turn_eq.isChecked():
			self.press_accept()
		else:
			self.parentWidget.PLAYER.set_equalizer(None)

	def press_reset(self):
		band_count = vlc.libvlc_audio_equalizer_get_band_count()
		for i in range(band_count):
			self.eq.set_amp_at_index(0.0, i)
		for item in self.list_sliders:
			item.setValue(0)
		self.combo_presets.setCurrentIndex(0)
		
	def change_slider_num(self):
		"""Change slider num"""
		if self.turn_eq.isChecked():
			slider = self.sender()
			value = slider.value()
			index = slider.BAND_NUM
			if index == 0:
				self.eq.set_preamp(value)
			else:
				self.eq.set_amp_at_index(value, index-1)
			self.press_accept()
			self.vbox_sliders.itemAt(index).itemAt(2).widget().setText(str(value))

	def press_accept(self):
		"""Press accept"""
		if self.turn_eq.isChecked():
			self.parentWidget.PLAYER.set_equalizer(self.eq)