Ejemplo n.º 1
0
    def initUI(self):
        # self.all_text = ""
        vbox = QVBoxLayout()
        total_height = 0
        for x in self.page:
            if isinstance(x, LTTextBoxHorizontal):
                txt_list = [
                    txt[:-1] if str(txt).endswith('-') else txt
                    for txt in x.get_text().split(os.linesep)
                ]
                text = " ".join(txt_list).strip()
                ed_text = QTextEdit()
                ed_text.setText(text)
                ed_text.adjustSize()

                total_height += ed_text.height()

                vbox.addWidget(ed_text)

                # ----添加翻译按钮----
                if len(text) > 5:
                    bt = self.add_translate_bt(ed_text, text, vbox)
                    # total_height += bt.height()

        self.setLayout(vbox)

        self.setMinimumSize(self.width(), total_height)
Ejemplo n.º 2
0
class MainWindow(QMainWindow):
    def __init__(self, url):
        super().__init__()
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.progress = 0

        f = QFile()
        f.setFileName(":/jquery.min.js")
        f.open(QIODevice.ReadOnly)
        self.jQuery = f.readAll().data().decode()
        self.jQuery += "\nvar qt = { 'jQuery': jQuery.noConflict(true) };"
        f.close()

        self.view = QWebEngineView(self)
        self.view.load(url)

        self.view.loadFinished.connect(self.adjustLocation)
        self.view.titleChanged.connect(self.adjustTitle)
        self.view.loadProgress.connect(self.setProgress)
        self.view.loadFinished.connect(self.finishLoading)

        self.locationEdit = QLineEdit(self)
        self.locationEdit.setSizePolicy(
            QSizePolicy.Expanding,
            self.locationEdit.sizePolicy().verticalPolicy())
        self.locationEdit.returnPressed.connect(self.changeLocation)

        toolBar = self.addToolBar(self.tr("Navigation"))
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Back))
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Forward))
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Reload))
        toolBar.addAction(self.view.pageAction(QWebEnginePage.Stop))
        toolBar.addWidget(self.locationEdit)

        viewMenu = self.menuBar().addMenu(self.tr("&View"))
        viewSourceAction = QAction(self.tr("Page Source"), self)
        viewSourceAction.triggered.connect(self.viewSource)
        viewMenu.addAction(viewSourceAction)

        effectMenu = self.menuBar().addMenu(self.tr("&Effect"))
        effectMenu.addAction(self.tr("Highlight all links"),
                             self.highlightAllLinks)

        self.rotateAction = QAction(self)
        self.rotateAction.setIcon(self.style().standardIcon(
            QStyle.SP_FileDialogDetailedView))
        self.rotateAction.setCheckable(True)
        self.rotateAction.setText(self.tr("Turn images upside down"))
        self.rotateAction.toggled.connect(self.rotateImages)
        effectMenu.addAction(self.rotateAction)

        toolsMenu = self.menuBar().addMenu(self.tr("&Tools"))
        toolsMenu.addAction(self.tr("Remove GIF images"), self.removeGifImages)
        toolsMenu.addAction(self.tr("Remove all inline frames"),
                            self.removeInlineFrames)
        toolsMenu.addAction(self.tr("Remove all object elements"),
                            self.removeObjectElements)
        toolsMenu.addAction(self.tr("Remove all embedded elements"),
                            self.removeEmbeddedElements)

        self.setCentralWidget(self.view)

    @pyqtSlot()
    def adjustLocation(self):
        self.locationEdit.setText(self.view.url().toString())

    @pyqtSlot()
    def changeLocation(self):
        url = QUrl.fromUserInput(self.locationEdit.text())
        self.view.load(url)
        self.view.setFocus()

    @pyqtSlot()
    def adjustTitle(self):
        if self.progress <= 0 or self.progress >= 100:
            self.setWindowTitle(self.view.title())
        else:
            self.setWindowTitle("%s (%2d)" %
                                (self.view.title(), self.progress))

    @pyqtSlot(int)
    def setProgress(self, p):
        self.progress = p
        self.adjustTitle()

    @pyqtSlot()
    def finishLoading(self):
        self.progress = 100
        self.adjustTitle()
        self.view.page().runJavaScript(self.jQuery)
        self.rotateImages(self.rotateAction.isChecked())

    @pyqtSlot()
    def viewSource(self):
        self.textEdit = QTextEdit()
        self.textEdit.setAttribute(Qt.WA_DeleteOnClose)
        self.textEdit.adjustSize()
        self.textEdit.move(self.geometry().center() -
                           self.textEdit.rect().center())
        self.textEdit.show()

        self.view.page().toHtml(self.textEdit.setPlainText)

    @pyqtSlot()
    def highlightAllLinks(self):
        code = "qt.jQuery('a').each( function () { qt.jQuery(this).css('background-color', 'yellow') } )"
        self.view.page().runJavaScript(code)

    @pyqtSlot(bool)
    def rotateImages(self, invert):
        code = ""
        if invert:
            code = "qt.jQuery('img').each( function () { qt.jQuery(this).css('transition', 'transform 2s'); qt.jQuery(this).css('transform', 'rotate(180deg)') } )"
        else:
            code = "qt.jQuery('img').each( function () { qt.jQuery(this).css('transition', 'transform 2s'); qt.jQuery(this).css('transform', 'rotate(0deg)') } )"
        self.view.page().runJavaScript(code)

    @pyqtSlot()
    def removeGifImages(self):
        code = "qt.jQuery('[src*=gif]').remove()"
        self.view.page().runJavaScript(code)

    @pyqtSlot()
    def removeInlineFrames(self):
        code = "qt.jQuery('iframe').remove()"
        self.view.page().runJavaScript(code)

    @pyqtSlot()
    def removeObjectElements(self):
        code = "qt.jQuery('object').remove()"
        self.view.page().runJavaScript(code)

    @pyqtSlot()
    def removeEmbeddedElements(self):
        code = "qt.jQuery('embed').remove()"
        self.view.page().runJavaScript(code)
Ejemplo n.º 3
0
class TcpPanel(QWidget):
    def __init__(self):
        super().__init__()
        self.tcpJSONFile = {"header": {"type": "none"}}
        self.translate = QCoreApplication.translate
        self.httpHeader = "none", "http"

    def createTCPSettingPanel(self):
        labelHttpHeaderType = QLabel(self.translate("TcpPanel", "Http type: "),
                                     self)
        self.comboxHttpHeaderType = QComboBox(self)
        self.btnHttpHeaderTypeClear = QPushButton(
            self.translate("TcpPanel", "Clear"), self)
        self.textHttpHeaderType = QTextEdit()

        self.comboxHttpHeaderType.addItems(self.httpHeader)
        self.btnHttpHeaderTypeClear.hide()
        self.textHttpHeaderType.hide()
        self.textHttpHeaderType.adjustSize()

        hboxhttpHeader = QHBoxLayout()
        hboxhttpHeader.addWidget(labelHttpHeaderType)
        hboxhttpHeader.addWidget(self.comboxHttpHeaderType)
        hboxhttpHeader.addWidget(self.btnHttpHeaderTypeClear)
        hboxhttpHeader.addStretch()

        vboxTCPSetting = QVBoxLayout()
        vboxTCPSetting.addLayout(hboxhttpHeader)
        vboxTCPSetting.addWidget(self.textHttpHeaderType)

        self.groupBoxTCPSetting = groupBoxTCPSetting = QGroupBox(
            self.translate("TcpPanel", "TCP Settings"), self)
        groupBoxTCPSetting.setCheckable(True)
        groupBoxTCPSetting.setChecked(False)
        groupBoxTCPSetting.adjustSize()
        groupBoxTCPSetting.setLayout(vboxTCPSetting)

        self.createTCPSettingPanelSignles()

        if (v2rayshellDebug):
            self.__debugBtn = QPushButton("__debugTest", self)
            v = QVBoxLayout()
            v.addWidget(groupBoxTCPSetting)
            v.addWidget(self.__debugBtn)
            v.addStretch()
            self.setLayout(v)
            self.__debugBtn.clicked.connect(self.__debugTest)
            self.settingtcpPanelFromJSONFile(self.tcpJSONFile, True)
            return

        return groupBoxTCPSetting

    def createTCPSettingPanelSignles(self):
        self.comboxHttpHeaderType.currentTextChanged.connect(
            self.oncomboxHttpHeaderType)
        self.btnHttpHeaderTypeClear.clicked.connect(
            self.onbtnHttpHeaderTypeClear)

    def onbtnHttpHeaderTypeClear(self):
        self.textHttpHeaderType.clear()

    def oncomboxHttpHeaderType(self, e):
        if (e == "none"):
            self.textHttpHeaderType.hide()
            self.btnHttpHeaderTypeClear.hide()

        if (e == "http"):
            self.btnHttpHeaderTypeClear.show()
            self.textHttpHeaderType.show()

    def jsonDataValitor(self, jsonData):
        try:
            data = json.loads(str(jsonData))
        except ValueError as e:
            return -1, e
        return 0, data

    def settingtcpPanelFromJSONFile(self, tcpJSONFile, openFromJSONFile=False):
        logbook.setisOpenJSONFile(openFromJSONFile)

        if (tcpJSONFile == None):
            tcpJSONFile = {}
            self.groupBoxTCPSetting.setChecked(False)
            self.textHttpHeaderType.clear()
            self.comboxHttpHeaderType.setCurrentText("none")
            return

        try:
            tcpJSONFile["header"]
        except KeyError as e:
            logbook.writeLog("transport TCP", "KeyError", e)
            tcpJSONFile["header"] = {}

        try:
            tcpJSONFile["header"]["type"]
        except KeyError as e:
            logbook.writeLog("transport TCP", "KeyError", e)
            tcpJSONFile["header"]["type"] = "none"

        if (tcpJSONFile["header"]["type"] == "http"):
            self.textHttpHeaderType.setText(
                json.dumps(tcpJSONFile["header"], indent=4, sort_keys=False))
            self.comboxHttpHeaderType.setCurrentText("http")
        elif (tcpJSONFile["header"]["type"] == "none"):
            self.textHttpHeaderType.clear()
        else:
            ### TODO pop a error message
            pass

    def createtcpSettingJSONFile(self):
        tcpJSONFile = {}
        tcpJSONFile["header"] = {}

        if (self.comboxHttpHeaderType.currentText() == "http"):
            header = self.textHttpHeaderType.toPlainText()
            checkjsonfile = self.jsonDataValitor(header)
            if (checkjsonfile[0] == -1):
                tcpJSONFile["header"]["type"] = "none"
                return tcpJSONFile

            if (checkjsonfile[0] == 0):
                header = checkjsonfile[1]
                http = False
                try:
                    ### use input text maybe no value type
                    http = (header["type"] == "http")
                except KeyError:
                    ### TODO pop a error message
                    pass
                except:
                    ### TODO pop a error message
                    pass

                if (http):
                    tcpJSONFile["header"] = header
                else:
                    tcpJSONFile["header"]["type"] = "none"
        else:
            tcpJSONFile["header"]["type"] = "none"

        return tcpJSONFile

    def cleartcpPanel(self):
        self.groupBoxTCPSetting.setChecked(False)
        self.comboxHttpHeaderType.setCurrentIndex(0)
        self.textHttpHeaderType.clear()

    def __debugTest(self):
        print(
            json.dumps(self.createtcpSettingJSONFile(),
                       indent=4,
                       sort_keys=False))
Ejemplo n.º 4
0
class AA(QMainWindow):
    def __init__(self):
        super().__init__()
        self.money = []
        self.name = []
        self.result = []
        self.test = 10
        self.initUI()

    def initUI(self):
        self.lab_name = QLabel(self)
        self.lab_name.move(10, 10)
        self.lab_name.setText('消费人姓名:')
        self.lab_name.adjustSize()

        self.lab_money = QLabel(self)
        self.lab_money.move(250, 10)
        self.lab_money.setText('消费数额:')
        self.lab_money.adjustSize()

        self.le_row0 = QLineEdit(self)
        self.le_row0.move(10, 30)
        self.le_column0 = QLineEdit(self)
        self.le_column0.move(250, 30)

        self.le_row1 = QLineEdit(self)
        self.le_row1.move(10, 70)
        self.le_column1 = QLineEdit(self)
        self.le_column1.move(250, 70)

        self.le_row2 = QLineEdit(self)
        self.le_row2.move(10, 110)
        self.le_column2 = QLineEdit(self)
        self.le_column2.move(250, 110)

        self.le_row3 = QLineEdit(self)
        self.le_row3.move(10, 150)
        self.le_column3 = QLineEdit(self)
        self.le_column3.move(250, 150)

        self.le_row4 = QLineEdit(self)
        self.le_row4.move(10, 190)
        self.le_column4 = QLineEdit(self)
        self.le_column4.move(250, 190)

        self.le_row5 = QLineEdit(self)
        self.le_row5.move(10, 230)
        self.le_column5 = QLineEdit(self)
        self.le_column5.move(250, 230)

        self.le_row6 = QLineEdit(self)
        self.le_row6.move(10, 270)
        self.le_column6 = QLineEdit(self)
        self.le_column6.move(250, 270)

        self.le_row7 = QLineEdit(self)
        self.le_row7.move(10, 310)
        self.le_column7 = QLineEdit(self)
        self.le_column7.move(250, 310)

        self.le_row8 = QLineEdit(self)
        self.le_row8.move(10, 350)
        self.le_column8 = QLineEdit(self)
        self.le_column8.move(250, 350)

        self.le_row9 = QLineEdit(self)
        self.le_row9.move(10, 390)
        self.le_column9 = QLineEdit(self)
        self.le_column9.move(250, 390)

        self.le_row10 = QLineEdit(self)
        self.le_row10.move(10, 430)
        self.le_column10 = QLineEdit(self)
        self.le_column10.move(250, 430)

        self.le_row11 = QLineEdit(self)
        self.le_row11.move(10, 470)
        self.le_column11 = QLineEdit(self)
        self.le_column11.move(250, 470)

        self.le_row12 = QLineEdit(self)
        self.le_row12.move(10, 510)
        self.le_column12 = QLineEdit(self)
        self.le_column12.move(250, 510)

        self.le_row13 = QLineEdit(self)
        self.le_row13.move(10, 550)
        self.le_column13 = QLineEdit(self)
        self.le_column13.move(250, 550)

        self.le_row14 = QLineEdit(self)
        self.le_row14.move(10, 590)
        self.le_column14 = QLineEdit(self)
        self.le_column14.move(250, 590)

        self.le_row15 = QLineEdit(self)
        self.le_row15.move(10, 630)
        self.le_column15 = QLineEdit(self)
        self.le_column15.move(250, 630)

        self.le_row16 = QLineEdit(self)
        self.le_row16.move(10, 670)
        self.le_column16 = QLineEdit(self)
        self.le_column16.move(250, 670)

        self.le_row17 = QLineEdit(self)
        self.le_row17.move(10, 710)
        self.le_column17 = QLineEdit(self)
        self.le_column17.move(250, 710)

        self.le_row18 = QLineEdit(self)
        self.le_row18.move(10, 750)
        self.le_column18 = QLineEdit(self)
        self.le_column18.move(250, 750)

        self.le_row19 = QLineEdit(self)
        self.le_row19.move(10, 790)
        self.le_column19 = QLineEdit(self)
        self.le_column19.move(250, 790)

        self.le_row0.editingFinished.connect(self.Changed_row0)
        self.le_column0.editingFinished.connect(self.Changed_column0)
        self.le_row1.editingFinished.connect(self.Changed_row1)
        self.le_column1.editingFinished.connect(self.Changed_column1)
        self.le_row2.editingFinished.connect(self.Changed_row2)
        self.le_column2.editingFinished.connect(self.Changed_column2)
        self.le_row3.editingFinished.connect(self.Changed_row3)
        self.le_column3.editingFinished.connect(self.Changed_column3)
        self.le_row4.editingFinished.connect(self.Changed_row4)
        self.le_column4.editingFinished.connect(self.Changed_column4)
        self.le_row5.editingFinished.connect(self.Changed_row5)
        self.le_column5.editingFinished.connect(self.Changed_column5)
        self.le_row6.editingFinished.connect(self.Changed_row6)
        self.le_column6.editingFinished.connect(self.Changed_column6)
        self.le_row7.editingFinished.connect(self.Changed_row7)
        self.le_column7.editingFinished.connect(self.Changed_column7)
        self.le_row8.editingFinished.connect(self.Changed_row8)
        self.le_column8.editingFinished.connect(self.Changed_column8)
        self.le_row9.editingFinished.connect(self.Changed_row9)
        self.le_column9.editingFinished.connect(self.Changed_column9)
        self.le_row10.editingFinished.connect(self.Changed_row10)
        self.le_column10.editingFinished.connect(self.Changed_column10)
        self.le_row11.editingFinished.connect(self.Changed_row11)
        self.le_column11.editingFinished.connect(self.Changed_column11)
        self.le_row12.editingFinished.connect(self.Changed_row12)
        self.le_column12.editingFinished.connect(self.Changed_column12)
        self.le_row13.editingFinished.connect(self.Changed_row13)
        self.le_column13.editingFinished.connect(self.Changed_column13)
        self.le_row14.editingFinished.connect(self.Changed_row14)
        self.le_column14.editingFinished.connect(self.Changed_column14)
        self.le_row15.editingFinished.connect(self.Changed_row15)
        self.le_column15.editingFinished.connect(self.Changed_column15)
        self.le_row16.editingFinished.connect(self.Changed_row16)
        self.le_column16.editingFinished.connect(self.Changed_column16)
        self.le_row17.editingFinished.connect(self.Changed_row17)
        self.le_column17.editingFinished.connect(self.Changed_column17)
        self.le_row18.editingFinished.connect(self.Changed_row18)
        self.le_column18.editingFinished.connect(self.Changed_column18)
        self.le_row19.editingFinished.connect(self.Changed_row19)
        self.le_column19.editingFinished.connect(self.Changed_column19)

        self.btn = QPushButton('结算', self)
        self.btn.move(400, 10)
        self.btn.clicked.connect(self.calculate)

        self.te = QTextEdit(self)
        self.te.move(400, 50)

        self.lab = QLabel(self)
        self.lab.move(800, 800)

        self.setGeometry(50, 50, 1000, 1000)
        self.setWindowTitle('欢迎使用AA制计算软件, author:Yeally ')
        self.show()

    def Changed_row0(self):
        self.name.append(self.le_row0.text())

    def Changed_column0(self):
        self.money.append(eval(self.le_column0.text()))

    def Changed_row1(self):
        self.name.append(self.le_row1.text())

    def Changed_column1(self):
        self.money.append(eval(self.le_column1.text()))

    def Changed_row2(self):
        self.name.append(self.le_row2.text())

    def Changed_column2(self):
        self.money.append(eval(self.le_column2.text()))

    def Changed_row3(self):
        self.name.append(self.le_row3.text())

    def Changed_column3(self):
        self.money.append(eval(self.le_column3.text()))

    def Changed_row4(self):
        self.name.append(self.le_row4.text())

    def Changed_column4(self):
        self.money.append(eval(self.le_column4.text()))

    def Changed_row5(self):
        self.name.append(self.le_row5.text())

    def Changed_column5(self):
        self.money.append(eval(self.le_column5.text()))

    def Changed_row6(self):
        self.name.append(self.le_row6.text())

    def Changed_column6(self):
        self.money.append(eval(self.le_column6.text()))

    def Changed_row7(self):
        self.name.append(self.le_row7.text())

    def Changed_column7(self):
        self.money.append(eval(self.le_column7.text()))

    def Changed_row8(self):
        self.name.append(self.le_row8.text())

    def Changed_column8(self):
        self.money.append(eval(self.le_column8.text()))

    def Changed_row9(self):
        self.name.append(self.le_row9.text())

    def Changed_column9(self):
        self.money.append(eval(self.le_column9.text()))

    def Changed_row10(self):
        self.name.append(self.le_row10.text())

    def Changed_column10(self):
        self.money.append(eval(self.le_column10.text()))

    def Changed_row11(self):
        self.name.append(self.le_row11.text())

    def Changed_column11(self):
        self.money.append(eval(self.le_column11.text()))

    def Changed_row12(self):
        self.name.append(self.le_row12.text())

    def Changed_column12(self):
        self.money.append(eval(self.le_column12.text()))

    def Changed_row13(self):
        self.name.append(self.le_row13.text())

    def Changed_column13(self):
        self.money.append(eval(self.le_column13.text()))

    def Changed_row14(self):
        self.name.append(self.le_row14.text())

    def Changed_column14(self):
        self.money.append(eval(self.le_column14.text()))

    def Changed_row15(self):
        self.name.append(self.le_row15.text())

    def Changed_column15(self):
        self.money.append(eval(self.le_column15.text()))

    def Changed_row16(self):
        self.name.append(self.le_row16.text())

    def Changed_column16(self):
        self.money.append(eval(self.le_column16.text()))

    def Changed_row17(self):
        self.name.append(self.le_row17.text())

    def Changed_column17(self):
        self.money.append(eval(self.le_column17.text()))

    def Changed_row18(self):
        self.name.append(self.le_row18.text())

    def Changed_column18(self):
        self.money.append(eval(self.le_column18.text()))

    def Changed_row19(self):
        self.name.append(self.le_row19.text())

    def Changed_column19(self):
        self.money.append(eval(self.le_column19.text()))

    def calculate(self):
        print(self.name, self.money)

        get = {}
        get_sort2 = []
        give_number = 0

        sum_money = sum(self.money)
        average_money = sum_money / len(self.name)

        for _ in self.money:
            if _ < average_money:
                give_number += 1
        for n, m in zip(self.name, self.money):
            gt = round(m - average_money, 3)
            get[n] = gt

        get_sort = sorted(get.items(), key=lambda x: x[1])

        for (a, b) in get_sort:
            get_sort2.append(list((a, b)))  #将列表里的元组元素转变为列表元素

        i = 0
        own = 0  #当前面的人(孙等)所给的钱不足时所欠的数
        enough = 0  #当前面的人(孙等)所给的钱还有多余的钱的多余数
        k = len(self.money)

        for i in range(give_number):

            if own != 0:
                gap = abs(get_sort2[i][1]) - own

                if gap > 0:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0], abs(own)))
                    get_sort2[i][1] += own
                    k -= 1
                    own = 0
                elif gap < 0:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0],
                            abs(get_sort2[i][1])))
                    own = own - abs(get_sort2[i][1])
                    get_sort2[i][1] += own
                    continue
                else:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0],
                            abs(get_sort2[i][1])))
                    own = own - abs(get_sort2[i][1])
                    get_sort2[i][1] += own
                    continue

            if (own == 0) and (enough == 0):

                decrease = abs(get_sort2[i][1]) - abs(get_sort2[k - 1][1])

                if decrease > 0:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0],
                            abs(get_sort2[k - 1][1])))
                    enough = decrease
                    k -= 1
                elif decrease < 0:

                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0],
                            abs(get_sort2[i][1])))
                    own = abs(decrease)
                    if own == 0:
                        k -= 1
                else:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0],
                            abs(get_sort2[i][1])))
                    own = 0
                    k -= 1

            if enough != 0:
                gap2 = abs(get_sort2[k - 1][1]) - enough
                while abs(get_sort2[k - 1][1]) - enough < 0:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0],
                            abs(get_sort2[k - 1][1])))
                    enough -= abs(get_sort2[k - 1][1])
                    get_sort2[i][1] += abs(get_sort2[k - 1][1])
                    k -= 1
                if gap2 > 0:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0], abs(enough)))
                    get_sort2[k - 1][1] -= enough
                    enough = 0
                    continue
                if gap2 == 0:
                    if k > give_number:
                        self.result.append('{}给{}{}元'.format(
                            get_sort2[i][0], get_sort2[k - 1][0], abs(enough)))
                    get_sort2[k - 1][1] -= enough
                    enough = 0
                    k -= 1
                    continue

        print(self.result)
        self.te.setPlainText(str(self.result))
        self.te.adjustSize()
Ejemplo n.º 5
0
class Window3(QMainWindow):  # <===
    def __init__(self):
        super().__init__()

        self.daily_df = None

        self.mac_file_path = os.path.abspath(
            os.path.join(sys.executable + "/prodotti.csv", "..", '..', '..',
                         '..', '..', "prodotti.csv"))

        today = str(datetime.datetime.today().strftime("%Y-%b-%d"))
        today = "ReportGiornaliero/" + today
        self.mac_daily_folder = os.path.abspath(
            os.path.join(sys.executable + "ReportGiornaliero/", "..", "..",
                         '..', '..', "ReportGiornaliero/"))
        self.mac_daily_path = os.path.abspath(
            os.path.join(sys.executable + today + "_prodotti.csv", "..", "..",
                         '..', '..', '..', today + "_prodotti.csv"))
        print(self.mac_daily_path)

        self.setWindowTitle("Cerca prodotti")
        self.title = "Cerca Prodotto"
        self.top = 200
        self.left = 200
        self.width = 1120
        self.height = 900
        self.df = self.load_csv()

        self.pandas_table = self.create_table()
        self.pandas_table.setGeometry(30, 30, 1020, 850)
        self.pandas_table.setBaseSize(1020, 850)
        self.line_edit = QTextEdit()
        self.line_edit.move(30, 30)
        self.line_edit.resize(1020, 30)
        self.line_edit.adjustSize()
        self.line_edit.setMinimumSize(800, 30)
        self.line_edit.setMaximumSize(1020, 30)
        self.label = QLabel()
        self.label.setText(
            "Inserire un ID valido per modificare i valori NEGOZIO e TOTALE")
        self.label_instructions = QLabel()
        self.label_instructions.setText(
            "- Il valore TOTALE viene calcolato come la somma di NEGOZIO e MAGAZZINO"
        )
        self.wid = QtWidgets.QWidget()
        self.setCentralWidget(self.wid)
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.label_instructions)
        self.layout.addWidget(self.line_edit)
        self.layout.addWidget(self.pandas_table)
        self.wid.setLayout(self.layout)
        '''self.daily_table = QPushButton("", self)
        self.daily_table.setGeometry(950, 10, 150, 30)
        self.daily_table.clicked.connect(self.do_nothing) #tentativo di gestire errore discutibile'''

        self.line_edit.setFocus()
        self.line_edit.setMinimumSize(800, 30)
        self.line_edit.setMaximumSize(1020, 30)

        Keyboard = Controller()
        Keyboard.press(Key.enter)
        Keyboard.release(Key.enter)

        is_selected = False

        if self.line_edit is None:
            self.line_edit.textChanged.connect(
                lambda what=None: self.check_existence(None))
        else:
            # se va un monumento me ce vo'!!!!! applica evento key press and release con enter nel text edit
            if not is_selected:
                is_selected = True
                enter_event = QKeyEvent(QEvent.KeyPress, Qt.Key_Enter,
                                        Qt.NoModifier)
                QCoreApplication.postEvent(self.line_edit, enter_event)
                enter_event = QKeyEvent(QEvent.KeyRelease, Qt.Key_Enter,
                                        Qt.NoModifier)
                QCoreApplication.postEvent(self.line_edit, enter_event)
            print("controllo testo:", self.line_edit.toPlainText())
            self.line_edit.textChanged.connect(
                lambda what=self.line_edit: self.check_existence(
                    what.toPlainText()))

    def do_nothing(self):
        pass

    def update_widget(self, row=None):
        self.pandas_table = self.create_table(row)
        self.pandas_table.setGeometry(30, 30, 1020, 850)
        self.pandas_table.setBaseSize(1020, 850)
        self.line_edit = QTextEdit()
        self.line_edit.move(30, 30)
        self.line_edit.resize(1020, 30)
        self.line_edit.adjustSize()
        self.line_edit.setMinimumSize(800, 30)
        self.line_edit.setMaximumSize(1020, 30)
        self.label = QLabel()
        self.label.setText(
            "Inserire un ID valido per modificare i valori NEGOZIO e TOTALE")
        self.label_instructions = QLabel()
        self.label_instructions.setText(
            "- Il valore TOTALE viene calcolato come la somma di NEGOZIO e MAGAZZINO"
        )
        self.wid = QtWidgets.QWidget()
        self.setCentralWidget(self.wid)
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.label_instructions)
        self.layout.addWidget(self.line_edit)
        self.layout.addWidget(self.pandas_table)
        self.wid.setLayout(self.layout)

        self.line_edit.setFocus()
        self.line_edit.setMinimumSize(800, 30)
        self.line_edit.setMaximumSize(1020, 30)

        self.first_run = True

        if self.line_edit is None:
            print("my text no codice 2:", self.line_edit.toPlainText())
            self.line_edit.textChanged.connect(
                lambda what=None: self.setPolishedText(None))
        else:
            self.line_edit.textChanged.connect(
                lambda what=self.line_edit: self.setPolishedText(
                    self.line_edit.toPlainText()))

    def setPolishedText(self, codice=None):
        keyboard = Controller()
        if not codice:
            pass
        elif "\n" in codice:

            self.line_edit.textChanged.connect(
                lambda what=self.line_edit: self.check_existence(
                    what.toPlainText()))
            self.line_edit.setText(
                self.line_edit.toPlainText().strip("\n").strip())
            if len(self.line_edit.toPlainText()) > 1:
                keyboard.press(Key.enter)
                keyboard.release(Key.enter)
        else:
            pass

    def create_table(self, row=None):
        # create the view
        tv = QTableView()

        # set the table model
        if row is None:
            tablemodel = PandasTable(self.load_csv())
        else:
            tablemodel = PandasTable(row)

        tv.setModel(tablemodel)
        tv.setBaseSize(995, 800)

        # hide grid
        tv.setShowGrid(False)

        vh = tv.verticalHeader()
        vh.setVisible(True)

        # set horizontal header properties
        hh = tv.horizontalHeader()
        hh.setStretchLastSection(True)

        # set row height
        tv.resizeRowsToContents()

        # enable sorting
        tv.setSortingEnabled(False)

        return tv

    def check_existence(self, text=None):
        if text is None:
            pass
        else:
            self.update_widget()

            #TODO: controllare casino immondo successo durante file drag and drop
            if self.df is None:
                self.load_df()
            else:
                if self.df.loc[self.df.CodiceProdotto == text].any().any():

                    self.df.loc[self.df.CodiceProdotto == text,
                                'QtaNegozio'] = self.df.loc[
                                    self.df.CodiceProdotto == text,
                                    'QtaNegozio'] - 1

                    # handle "nan" exception
                    try:
                        if int(self.df.loc[self.df.CodiceProdotto == text,
                                           'QtaNegozio']) < 1:

                            self.df.loc[self.df.CodiceProdotto == text,
                                        'QtaNegozio'] = 0
                            '''attivare alert'''
                            QMessageBox.about(
                                self, "ATTENZIONE",
                                "prodotto " + text + " esaurito in negozio")
                            print(self.df.loc[self.df.CodiceProdotto == text,
                                              'QtaNegozio'])

                            # salva riga con alert (e prodotto relativo) in daily report
                            self.update_daily(
                                self.df.loc[self.df.CodiceProdotto == text,
                                            'CodiceProdotto'],
                                self.df.loc[self.df.CodiceProdotto == text,
                                            'QtaNegozio'],
                                self.df.loc[self.df.CodiceProdotto == text,
                                            'QtaMagazzino'], self.df,
                                self.df.index[self.df.CodiceProdotto == text])
                    except ValueError as e:
                        if str(self.df.loc[self.df.CodiceProdotto == text,
                                           'QtaNegozio']).lower() == "nan":
                            self.df.loc[self.df.CodiceProdotto == text,
                                        'QtaNegozio'] = 0

                    try:
                        self.df.loc[self.df.CodiceProdotto == text,
                                    'QtTotale'] = self.df.loc[
                                        self.df.CodiceProdotto == text,
                                        'QtTotale'] - 1
                        if int(
                                self.df.loc[self.df.CodiceProdotto == text,
                                            'QtTotale']
                        ) != (int(self.df.loc[self.df.CodiceProdotto == text,
                                              'QtaNegozio']) +
                              int(self.df.loc[self.df.CodiceProdotto == text,
                                              'QtaMagazzino'])):
                            self.df.loc[self.df.CodiceProdotto == text,
                                        'QtTotale'] = int(self.df.loc[
                                            self.df.CodiceProdotto == text,
                                            'QtaNegozio']) + int(self.df.loc[
                                                self.df.CodiceProdotto == text,
                                                'QtaMagazzino'])
                    except ValueError as e:
                        if str(self.df.loc[self.df.CodiceProdotto == text,
                                           'QtaMagazzino']).lower() == "nan":
                            self.df.loc[self.df.CodiceProdotto == text,
                                        'QtaMagazzino'] = 0
                        if str(self.df.loc[self.df.CodiceProdotto == text,
                                           'QtTotale']).lower() == "nan":
                            self.df.loc[self.df.CodiceProdotto == text,
                                        'QtTotale'] = 0
                        else:
                            self.df.loc[self.df.CodiceProdotto == text,
                                        'QtTotale'] = 0

                    pd.set_option('display.max_columns', None)
                    self.df.to_csv(self.mac_file_path, index=False, sep="|")
                    self.update_widget(
                        row=self.df.loc[self.df.CodiceProdotto == text])
                else:
                    self.update_widget()
                    pass

    def load_csv(self):
        try:
            df = pd.read_csv(self.mac_file_path, sep="|")
            try:
                daily_df = pd.read_csv(self.mac_daily_path, sep="|")
            except Exception as e:
                print(e)
                daily_df = self.create_daily_db()
            self.daily_df = daily_df
            return df
        except FileNotFoundError as e:
            df = self.create_db()
            try:
                daily_df = pd.read_csv(self.mac_daily_path, sep="|")
            except Exception as e:
                print(e)
                daily_df = self.create_daily_db()
            self.daily_df = daily_df
            return df

    def create_daily_db(self):
        data_list = [
            "#", "initialization row", "no", 0, 0, 0, "N/A", "N/A", "N/A",
            "N/A", "N/A"
        ]
        index_list = [
            "CodiceProdotto", "Nome", "Descrizione", "QtTotale",
            "QtaMagazzino", "QtaNegozio", "Taglia", "Colore", "Stagione",
            "Anno", "Data"
        ]

        df = pd.DataFrame(columns=index_list)
        a_series = pd.Series(data_list, index=index_list)
        df = df.append(a_series, ignore_index=True)
        self.daily_df = df

        try:
            df.to_csv(self.mac_daily_path, index=False, sep="|")
        except Exception as e:
            print(self.mac_daily_folder)
            if os.path.isdir(self.mac_daily_folder):
                df.to_csv(self.mac_daily_path, index=False, sep="|")
            else:
                os.mkdir(self.mac_daily_folder, 0o755)
                df.to_csv(self.mac_daily_path, index=False, sep="|")

    def update_daily(self, codice_prodotto, qta_negozio, qta_magazzino, df,
                     index):
        zero_series = df.iloc[index].squeeze()
        self.daily_df = self.daily_df.append(zero_series, ignore_index=True)
        self.daily_df.drop_duplicates(subset="CodiceProdotto", inplace=True)
        self.daily_df.to_csv(self.mac_daily_path, index=False, sep="|")

    def create_db(self):
        if not os.path.isfile(self.mac_file_path):
            data_list = [
                "#", "initialization row", "no", 0, 0, 0, "N/A", "N/A", "N/A",
                "N/A", "N/A"
            ]
            index_list = [
                "CodiceProdotto", "Nome", "Descrizione", "QtTotale",
                "QtaMagazzino", "QtaNegozio", "Taglia", "Colore", "Stagione",
                "Anno", "Data"
            ]

            df = pd.DataFrame(columns=index_list)
            a_series = pd.Series(data_list, index=self.df.columns)
            df = df.append(a_series, ignore_index=True)
            df.to_csv(self.mac_file_path, index=False, sep="|")
            #print("initialization dir:" + self.mac_file_path)
            return df
        else:
            #print("csv exists", self.mac_file_path)
            pass

    #@QtCore.pyqtSlot()
    def windowDailyReport(self):  # <===
        self.w = WindowDailyReport()
        self.w.setWindowTitle(self.w.title)
        self.w.setGeometry(self.w.top, self.w.left, self.w.width,
                           self.w.height)
        self.w.show()

    @QtCore.pyqtSlot()
    def on_pushButtonLoad_clicked(self):
        self.df = self.load_csv()