Esempio n. 1
0
def set_cell_widget_all(table_widget: QTableWidget, row, column):
    item = QPushButton(table_widget)
    item.setText("JOIN")
    item.setMaximumSize(83, 35)
    item.setMinimumSize(83, 32)
    item.setStyleSheet(button_stylesheet)
    table_widget.setCellWidget(row, column, item)
    table_widget.repaint()
    table_widget.adjustSize()
    item = set_button_style(item)  # update button with icon
    return item
class dicomSelectDialog(QDialog):
    def __init__(self, images, parent=None):
        super(dicomSelectDialog, self).__init__(parent)
        self.__images = images
        self.btnOK = QPushButton('OK')
        self.btnQuit = QPushButton('Cancel')
        self.table = QTableWidget(len(images), 3)
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.btnOK)
        hbox.addWidget(self.btnQuit)
        vbox = QVBoxLayout(self)
        vbox.addWidget(self.table, stretch=1)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        self.__makeTable()
        self.selectedIndex = None

        self.btnQuit.clicked.connect(self.reject)
        # self.btnOK.clicked.connect( \
        #        lambda x, self=self: self.done(self.table.currentRow()))
        self.btnOK.clicked.connect(self.btnOKClicked)

    def btnOKClicked(self, flag):
        self.selectedIndex = self.table.currentRow()
        self.accept()

    def __makeTable(self):
        labels = ['PatientID', 'SeriesDescription', 'Size']
        self.table.setHorizontalHeaderLabels(labels)
        for i, image in enumerate(self.__images):
            self.table.setItem(i, 0,\
                               QTableWidgetItem(str(image.GetMetaData('0010|0020'))))
            self.table.setItem(i, 1, \
                               QTableWidgetItem(str(image.GetMetaData('0008|103e'))))
            self.table.setItem(i, 2, \
                               QTableWidgetItem(str(image.GetSize())))
        self.table.resizeColumnsToContents()
        self.table.adjustSize()
Esempio n. 3
0
class TableTab(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.table = QTableWidget(self)
        self.table.horizontalHeader().hide()
        self.table.verticalHeader().hide()
        self.table.setRowCount(3)
        self.table.setColumnCount(3)
        self.table.adjustSize()
        self.setItem(0, 1, "(0,1)")
        self.setLabelItem(0, 0, "(0,0)")
        self.setLabelItem(1, 0, "(1,0)")
        self.setItem(1, 1, "(1,1)")
        self.layout.addWidget(self.table)

        interval = QTimer(self)
        interval.setInterval(100)
        interval.timeout.connect(self._interval)
        interval.start()

        self.table.itemSelectionChanged.connect(lambda: print("cellPressed"))

    def setItem(self, row, col, data):
        item = QTableWidgetItem(data)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.table.setItem(row, col, item)

    def setLabelItem(self, row, col, data):
        item = QTableWidgetItem(data)
        item.setFlags(Qt.ItemIsSelectable)
        self.table.setItem(row, col, item)

    def _interval(self):
        self.setItem(2, 0, randint(0, 100).__str__())
Esempio n. 4
0
class InboundSocksPanel(QWidget):
    def __init__(self):
        super().__init__()
        self.inboundSocksJSONFile = {
            "auth": "noauth",
            "accounts": [{
                "user": "******",
                "pass": "******"
            }],
            "udp": False,
            "ip": "127.0.0.1",
            "timeout": 300,
            "userLevel": 0
        }
        self.translate = QCoreApplication.translate
        self.labelUserSocksPanel = (self.translate("InboundSocksPanel",
                                                   "User"),
                                    self.translate("InboundSocksPanel",
                                                   "Password"))

    def createSocksSettingPanel(self):
        labelIP = QLabel(
            self.translate("InboundSocksPanel", "Local IP Address: "), self)
        self.lineEditInboundSocksIP = QLineEdit()
        labelTimeout = QLabel(self.translate("InboundSocksPanel", "Timeout: "),
                              self)
        self.spinBoxInboundSocksTimeout = QSpinBox()
        self.checkBoxInboundSocksUDP = QCheckBox(
            self.translate("InboundSocksPanel", "Enable the UDP protocol"),
            self)
        self.btnInboundSocksUserAdd = QPushButton(
            self.translate("InboundSocksPanel", "Add"), self)
        self.btnInboundSocksChange = QPushButton(
            self.translate("InboundSocksPanel", "Modify"), self)
        self.btnInboundSocksPanelClear = QPushButton(
            self.translate("InboundSocksPanel", "Clear"), self)
        self.btnInboundSocksUserDelete = QPushButton(
            self.translate("InboundSocksPanel", "Delete"), self)
        labelUserName = QLabel(self.translate("InboundSocksPanel", "User: "******"InboundSocksPanel", "Password: "******"127.0.0.1")
        self.checkBoxInboundSocksUDP.setChecked(False)

        labeluserLevel = QLabel(
            self.translate("InboundSocksPanel", "User Level: "))
        self.spinBoxInboundSocksuserLevel = QSpinBox()
        self.spinBoxInboundSocksuserLevel.setRange(0, 65535)
        self.spinBoxInboundSocksuserLevel.setValue(0)

        hboxuserLevel = QHBoxLayout()
        hboxuserLevel.addWidget(labeluserLevel)
        hboxuserLevel.addWidget(self.spinBoxInboundSocksuserLevel)
        hboxuserLevel.addStretch()

        hboxIP = QHBoxLayout()
        hboxTimeout = QHBoxLayout()
        vboxSocksSetting = QVBoxLayout()
        vboxBtnSocksUser = QVBoxLayout()

        hboxIP.addWidget(labelIP)
        hboxIP.addWidget(self.lineEditInboundSocksIP)
        hboxIP.addStretch(1)

        hboxTimeout.addWidget(labelTimeout)
        hboxTimeout.addWidget(self.spinBoxInboundSocksTimeout)
        hboxTimeout.addStretch()

        hboxUser = QHBoxLayout()
        hboxUser.addWidget(labelUserName)
        hboxUser.addWidget(self.lineEditInboundSocksUserName)
        hboxUser.addWidget(labelPassowrd)
        hboxUser.addWidget(self.lineEditInboundSocksPassword)
        hboxUser.addStretch()

        vboxBtnSocksUser.addStretch()
        vboxBtnSocksUser.addWidget(self.btnInboundSocksUserAdd)
        vboxBtnSocksUser.addWidget(self.btnInboundSocksPanelClear)
        vboxBtnSocksUser.addWidget(self.btnInboundSocksChange)
        vboxBtnSocksUser.addWidget(self.btnInboundSocksUserDelete)

        vboxSocksSetting.addLayout(hboxIP)
        vboxSocksSetting.addLayout(hboxTimeout)
        vboxSocksSetting.addLayout(hboxuserLevel)
        vboxSocksSetting.addWidget(self.checkBoxInboundSocksUDP)

        self.tableWidgetInboundSocksUser.setColumnCount(2)
        self.tableWidgetInboundSocksUser.adjustSize()
        self.tableWidgetInboundSocksUser.setHorizontalHeaderLabels(
            self.labelUserSocksPanel)
        self.tableWidgetInboundSocksUser.setSelectionMode(
            QAbstractItemView.SingleSelection)
        self.tableWidgetInboundSocksUser.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.tableWidgetInboundSocksUser.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.tableWidgetInboundSocksUser.horizontalHeader(
        ).setStretchLastSection(True)

        self.groupBoxAuth = groupBoxAuth = QGroupBox(
            self.translate("InboundSocksPanel", "Requires Authentication: "),
            self)
        groupBoxAuth.setCheckable(True)
        groupBoxAuth.setChecked(False)

        hboxInboundSocksAuthTableWidget = QHBoxLayout()
        hboxInboundSocksAuthTableWidget.addWidget(
            self.tableWidgetInboundSocksUser)
        hboxInboundSocksAuthTableWidget.addLayout(vboxBtnSocksUser)

        vboxInboundSocksAuth = QVBoxLayout()
        vboxInboundSocksAuth.addLayout(hboxUser)
        vboxInboundSocksAuth.addLayout(hboxInboundSocksAuthTableWidget)

        groupBoxAuth.setLayout(vboxInboundSocksAuth)

        vboxInboundSocksPanel = QVBoxLayout()
        vboxInboundSocksPanel.addLayout(vboxSocksSetting)
        vboxInboundSocksPanel.addWidget(groupBoxAuth)

        self.createInboundSocksPanelSignals()

        if (v2rayshellDebug):
            self.__debugBtn = QPushButton("__debugTest", self)
            vboxInboundSocksPanel.addWidget(self.__debugBtn)
            self.__debugBtn.clicked.connect(self.__debugTest)
            self.settingInboundSocksPanelFromJSONFile(
                self.inboundSocksJSONFile, True)
            self.setLayout(vboxInboundSocksPanel)
            return

        groupSocksPanel = QGroupBox(
            self.translate("InboundSocksPanel", "Socks"), self)
        groupSocksPanel.setLayout(vboxInboundSocksPanel)

        return groupSocksPanel

    def createInboundSocksPanelSignals(self):
        self.tableWidgetInboundSocksUser.itemSelectionChanged.connect(
            self.ontableWidgetInboundSocksUserSelectionChanged)
        self.btnInboundSocksPanelClear.clicked.connect(
            self.onbtnInboundSocksPanelClear)
        self.btnInboundSocksUserAdd.clicked.connect(
            self.onbtnInboundSocksUserAdd)
        self.btnInboundSocksUserDelete.clicked.connect(
            self.onbtnInboundSocksUserDelete)
        self.btnInboundSocksChange.clicked.connect(
            self.onbtnInboundSocksChange)

    def onbtnInboundSocksChange(self):
        row = self.tableWidgetInboundSocksUser.currentRow()
        self.tableWidgetInboundSocksUser.setItem(
            row, 0, QTableWidgetItem(self.lineEditInboundSocksUserName.text()))
        self.tableWidgetInboundSocksUser.setItem(
            row, 1, QTableWidgetItem(self.lineEditInboundSocksPassword.text()))

    def onbtnInboundSocksUserDelete(self):
        self.onbtnInboundSocksPanelClear()
        row = self.tableWidgetInboundSocksUser.currentRow()
        self.tableWidgetInboundSocksUser.removeRow(row)

    def onbtnInboundSocksUserAdd(self):
        if (not self.lineEditInboundSocksPassword.text()
                or not self.lineEditInboundSocksUserName.text()):
            return
        row = self.tableWidgetInboundSocksUser.rowCount()
        self.tableWidgetInboundSocksUser.setRowCount(row + 1)
        self.tableWidgetInboundSocksUser.setItem(
            row, 0, QTableWidgetItem(self.lineEditInboundSocksUserName.text()))
        self.tableWidgetInboundSocksUser.setItem(
            row, 1, QTableWidgetItem(self.lineEditInboundSocksPassword.text()))
        self.tableWidgetInboundSocksUser.resizeColumnsToContents()
        self.onbtnInboundSocksPanelClear()

    def onbtnInboundSocksPanelClear(self):
        self.lineEditInboundSocksUserName.clear()
        self.lineEditInboundSocksPassword.clear()

    def ontableWidgetInboundSocksUserSelectionChanged(self):
        self.onbtnInboundSocksPanelClear()
        row = self.tableWidgetInboundSocksUser.currentRow()
        user = self.tableWidgetInboundSocksUser.item(row, 0)
        password = self.tableWidgetInboundSocksUser.item(row, 1)

        if (user):
            self.lineEditInboundSocksUserName.setText(user.text())
        else:
            self.lineEditInboundSocksUserName.clear()
        if (password):
            self.lineEditInboundSocksPassword.setText(password.text())
        else:
            self.lineEditInboundSocksPassword.clear()

    def settingInboundSocksPanelFromJSONFile(self,
                                             inboundSocksJSONFile={},
                                             openFromJSONFile=False):
        logbook.setisOpenJSONFile(openFromJSONFile)
        self.tableWidgetInboundSocksUser.setRowCount(0)
        accountsNumber = 0
        accounts = True

        if (not inboundSocksJSONFile): inboundSocksJSONFile = {}

        try:
            inboundSocksJSONFile["auth"]
        except KeyError as e:
            logbook.writeLog("InboundSocks", "KeyError", e)
            inboundSocksJSONFile["auth"] = "noauth"

        try:
            inboundSocksJSONFile["udp"]
        except KeyError as e:
            logbook.writeLog("InboundSocks", "KeyError", e)
            inboundSocksJSONFile["udp"] = False

        try:
            inboundSocksJSONFile["ip"]
        except KeyError as e:
            logbook.writeLog("InboundSocks", "KeyError", e)
            inboundSocksJSONFile["ip"] = "127.0.0.1"

        try:
            inboundSocksJSONFile["timeout"]
        except KeyError as e:
            logbook.writeLog("InboundSocks", "KeyError", e)
            inboundSocksJSONFile["timeout"] = 300
        try:
            inboundSocksJSONFile["accounts"]
        except KeyError as e:
            logbook.writeLog("InboundSocks", "KeyError", e)
            inboundSocksJSONFile["accounts"] = []
            accounts = False

        try:
            inboundSocksJSONFile["userLevel"]
        except KeyError as e:
            logbook.writeLog("InboundSocks", "KeyError", e)
            inboundSocksJSONFile["userLevel"] = 0

        self.lineEditInboundSocksIP.setText(str(inboundSocksJSONFile["ip"]))
        self.checkBoxInboundSocksUDP.setChecked(
            bool(inboundSocksJSONFile["udp"]))

        try:
            self.spinBoxInboundSocksTimeout.setValue(
                int(inboundSocksJSONFile["timeout"]))
        except (TypeError, ValueError) as e:
            logbook.writeLog("InboundSocks", "ValueError or TypeError", e)
            self.spinBoxInboundSocksTimeout.setValue(300)

        try:
            self.spinBoxInboundSocksuserLevel.setValue(
                int(inboundSocksJSONFile["userLevel"]))
        except (TypeError, ValueError) as e:
            logbook.writeLog("InboundSocks", "ValueError or TypeError", e)
            self.spinBoxInboundSocksuserLevel.setValue(0)

        try:
            self.treasureChest.addLevel(
                self.spinBoxInboundSocksuserLevel.value())
        except Exception:
            pass

        if (accounts):
            if (inboundSocksJSONFile["auth"] == "password"):
                self.groupBoxAuth.setChecked(True)
            accountsNumber = len(inboundSocksJSONFile["accounts"])
            accounts = inboundSocksJSONFile["accounts"]
            if (accountsNumber):
                self.tableWidgetInboundSocksUser.setRowCount(accountsNumber)
                try:
                    for i in range(0, accountsNumber):
                        self.tableWidgetInboundSocksUser.setItem(
                            i, 0, QTableWidgetItem(str(accounts[i]["user"])))
                        self.tableWidgetInboundSocksUser.setItem(
                            i, 1, QTableWidgetItem(str(accounts[i]["pass"])))
                        self.tableWidgetInboundSocksUser.resizeColumnsToContents(
                        )
                except KeyError as e:
                    logbook.writeLog("InboundSocks", "KeyError", e)

    def createInboundSocksJSONFile(self):
        inboundSocksJSONFile = {}

        if (self.groupBoxAuth.isChecked()):
            inboundSocksJSONFile["auth"] = "password"
            accountsNumber = self.tableWidgetInboundSocksUser.rowCount()
            if (accountsNumber):
                accounts = []
                for i in range(0, accountsNumber):
                    account = {}
                    user = self.tableWidgetInboundSocksUser.item(i, 0)
                    password = self.tableWidgetInboundSocksUser.item(i, 1)
                    if (user and password):
                        account["user"] = user.text()
                        account["pass"] = password.text()
                        accounts.append(copy.deepcopy(account))
                inboundSocksJSONFile["accounts"] = copy.deepcopy(accounts)
        else:
            inboundSocksJSONFile["auth"] = "noauth"

        inboundSocksJSONFile["udp"] = self.checkBoxInboundSocksUDP.isChecked()
        inboundSocksJSONFile["ip"] = self.lineEditInboundSocksIP.text()
        inboundSocksJSONFile[
            "timeout"] = self.spinBoxInboundSocksTimeout.value()
        inboundSocksJSONFile[
            "userLevel"] = self.spinBoxInboundSocksuserLevel.value()

        try:
            self.treasureChest.addLevel(
                self.spinBoxInboundSocksuserLevel.value())
        except Exception:
            pass

        return inboundSocksJSONFile

    def clearinboundsocksPanel(self):
        self.tableWidgetInboundSocksUser.setRowCount(0)
        self.lineEditInboundSocksIP.clear()
        self.lineEditInboundSocksPassword.clear()
        self.lineEditInboundSocksUserName.clear()
        self.checkBoxInboundSocksUDP.setChecked(False)
        self.groupBoxAuth.setChecked(False)
        self.spinBoxInboundSocksTimeout.setValue(300)
        self.spinBoxInboundSocksuserLevel.setValue(0)

    def __debugTest(self):
        import json
        print(
            json.dumps(self.createInboundSocksJSONFile(),
                       indent=4,
                       sort_keys=False))
Esempio n. 5
0
class HttpPanel(QWidget):
    def __init__(self):
        super().__init__()
        self.httpJSONFile = {
            "timeout": 300,
            "accounts": [{
                "user": "******",
                "pass": "******"
            }],
            "allowTransparent": False,
            "userLevel": 0
        }
        self.translate = QCoreApplication.translate

        self.labelUserHttpPanel = (self.translate("HttpPanel", "User"),
                                   self.translate("HttpPanel", "Password"))

    def createHttpSettingPanel(self):
        labelTimeout = QLabel(self.translate("HttpPanel", "Timeout: "), self)
        self.spinBoxHttpTimeout = QSpinBox()

        self.spinBoxHttpTimeout.setRange(0, 999)
        self.spinBoxHttpTimeout.setValue(300)

        self.checkBoxallowTransparent = QCheckBox(
            self.translate("HttpPanel", "Allow Transparent"), self)
        self.checkBoxallowTransparent.setChecked(False)

        hboxTimeout = QHBoxLayout()
        hboxTimeout.addWidget(labelTimeout)
        hboxTimeout.addWidget(self.spinBoxHttpTimeout)
        hboxTimeout.addStretch()

        labeluserLevel = QLabel(self.translate("HttpPanel", "User Level: "))
        self.spinBoxHttpuserLevel = QSpinBox()
        self.spinBoxHttpuserLevel.setRange(0, 65535)
        self.spinBoxHttpuserLevel.setValue(0)

        hboxuserLevel = QHBoxLayout()
        hboxuserLevel.addWidget(labeluserLevel)
        hboxuserLevel.addWidget(self.spinBoxHttpuserLevel)
        hboxuserLevel.addStretch()

        btnHttpAdd = QPushButton(self.translate("HttpPanel", "Add"), self)
        btnHttpClear = QPushButton(self.translate("HttpPanel", "Clear"), self)
        btnHttpDelete = QPushButton(self.translate("HttpPanel", "Delete"),
                                    self)

        self.groupButtonHttp = QButtonGroup()
        self.groupButtonHttp.addButton(btnHttpAdd)
        self.groupButtonHttp.addButton(btnHttpClear)
        self.groupButtonHttp.addButton(btnHttpDelete)

        vboxButtonHttp = QVBoxLayout()
        vboxButtonHttp.addStretch()
        vboxButtonHttp.addWidget(btnHttpAdd)
        vboxButtonHttp.addWidget(btnHttpClear)
        vboxButtonHttp.addWidget(btnHttpDelete)

        labelHttpUser = QLabel(self.translate("HttpPanel", "User: "******"HttpPanel", "Password: "******"HttpPanel", "Requires Authentication: "), self)
        self.groupBoxHttpAuth.setCheckable(True)
        self.groupBoxHttpAuth.setChecked(False)
        self.groupBoxHttpAuth.setLayout(vboxHttpTableWidget)

        vboxHttp = QVBoxLayout()
        vboxHttp.addLayout(hboxTimeout)
        vboxHttp.addLayout(hboxuserLevel)
        vboxHttp.addWidget(self.checkBoxallowTransparent)
        vboxHttp.addWidget(self.groupBoxHttpAuth)

        self.createHttpPanelSignals()

        if (v2rayshellDebug):
            self.__debugBtn = QPushButton("__debugTest", self)
            self.__debugBtn.clicked.connect(self.__debugTest)
            vboxHttp.addWidget(self.__debugBtn)
            self.settinghttpPanelFromJSONFile(self.httpJSONFile, True)

        groupBoxHttp = QGroupBox(self.translate("HttpPanel", "Http"), self)
        groupBoxHttp.setLayout(vboxHttp)

        return groupBoxHttp

    def createHttpPanelSignals(self):
        self.groupButtonHttp.buttonClicked.connect(self.ongroupButtonHttp)
        self.tableWidgetHttp.itemSelectionChanged.connect(
            self.ontableWidgetHttpSelectionChanged)
        self.tableWidgetHttp.itemClicked.connect(
            self.ontableWidgetHttpSelectionChanged)

    def ontableWidgetHttpSelectionChanged(self):
        self.onbtnHttpClear()
        row = self.tableWidgetHttp.currentRow()
        user = self.tableWidgetHttp.item(row, 0)
        password = self.tableWidgetHttp.item(row, 1)

        if (user):
            self.lineEditHttpUser.setText(user.text())
        if (password):
            self.lineEditHttpPassword.setText(password.text())

    def ongroupButtonHttp(self, e):
        if (e.text() == self.translate("HttpPanel", "Add")):
            self.onbtnHttpAdd()
        if (e.text() == self.translate("HttpPanel", "Clear")):
            self.onbtnHttpClear()
        if (e.text() == self.translate("HttpPanel", "Delete")):
            self.onbtnHttpDelete()

    def onbtnHttpAdd(self):
        user = self.lineEditHttpUser.text()
        password = self.lineEditHttpPassword.text()
        if (not user or not password): return

        row = self.tableWidgetHttp.rowCount()
        self.tableWidgetHttp.setRowCount(row + 1)
        self.tableWidgetHttp.setItem(row, 0, QTableWidgetItem(str(user)))
        self.tableWidgetHttp.setItem(row, 1, QTableWidgetItem(str(password)))
        self.tableWidgetHttp.resizeColumnsToContents()
        self.onbtnHttpClear()

    def onbtnHttpDelete(self):
        self.onbtnHttpClear()
        if (not self.tableWidgetHttp.rowCount()): return
        row = self.tableWidgetHttp.currentRow()
        self.tableWidgetHttp.removeRow(row)

    def onbtnHttpClear(self):
        self.lineEditHttpPassword.clear()
        self.lineEditHttpUser.clear()

    def settinghttpPanelFromJSONFile(self,
                                     httpJSONFile={},
                                     openFromJSONFile=False):
        logbook.setisOpenJSONFile(openFromJSONFile)
        self.tableWidgetHttp.setRowCount(0)

        if (not httpJSONFile): httpJSONFile = {}

        try:
            httpJSONFile["timeout"]
        except KeyError as e:
            logbook.writeLog("http", "KeyError", e)
            httpJSONFile["timeout"] = 300

        try:
            httpJSONFile["allowTransparent"]
        except KeyError as e:
            logbook.writeLog("http", "KeyError", e)
            httpJSONFile["allowTransparent"] = False

        try:
            httpJSONFile["accounts"]
        except KeyError as e:
            logbook.writeLog("http", "KeyError", e)
            httpJSONFile["accounts"] = {}

        try:
            httpJSONFile["userLevel"]
        except KeyError as e:
            logbook.writeLog("http", "KeyError", e)
            httpJSONFile["userLevel"] = 0

        try:
            self.spinBoxHttpTimeout.setValue(int(self.httpJSONFile["timeout"]))
        except (ValueError, TypeError) as e:
            logbook.writeLog("http", "ValueError or TypeError", e)
            self.spinBoxHttpTimeout.setValue(300)

        try:
            self.checkBoxallowTransparent.setChecked(
                bool(httpJSONFile["allowTransparent"]))
        except (ValueError, TypeError) as e:
            logbook.writeLog("http", "ValueError or TypeError", e)
            self.checkBoxallowTransparent.setChecked(False)

        try:
            self.spinBoxHttpuserLevel.setValue(int(httpJSONFile["userLevel"]))
        except (ValueError, TypeError) as e:
            logbook.writeLog("http", "ValueError or TypeError", e)
            self.spinBoxHttpuserLevel.setValue(0)
        try:
            self.treasureChest.addLevel(self.spinBoxHttpuserLevel.value())
        except Exception:
            pass

        accountsNumber = len(httpJSONFile["accounts"])
        if (accountsNumber):
            accounts = httpJSONFile["accounts"]
            self.tableWidgetHttp.setRowCount(accountsNumber)
            self.groupBoxHttpAuth.setChecked(True)
            for i in range(accountsNumber):
                try:
                    user = accounts[i]["user"]
                except Exception:
                    user = ""
                try:
                    password = accounts[i]["pass"]
                except Exception:
                    password = ""

                self.tableWidgetHttp.setItem(i, 0, QTableWidgetItem(str(user)))
                self.tableWidgetHttp.setItem(i, 1,
                                             QTableWidgetItem(str(password)))
                self.tableWidgetHttp.resizeColumnsToContents()
        else:
            self.groupBoxHttpAuth.setChecked(False)

    def createHttpJSONFile(self):
        httpJSONFile = {}
        httpJSONFile["timeout"] = self.spinBoxHttpTimeout.value()

        if (self.groupBoxHttpAuth.isChecked()):
            httpJSONFile["accounts"] = []
            accountsNumber = self.tableWidgetHttp.rowCount()
            if (accountsNumber):
                account = {}
                for i in range(accountsNumber):
                    account["user"] = self.tableWidgetHttp.item(i, 0).text()
                    account["pass"] = self.tableWidgetHttp.item(i, 1).text()
                    httpJSONFile["accounts"].append(copy.deepcopy(account))
            else:
                del httpJSONFile["accounts"]

        httpJSONFile[
            "allowTransparent"] = self.checkBoxallowTransparent.isChecked()
        httpJSONFile["userLevel"] = self.spinBoxHttpuserLevel.value()

        try:
            self.treasureChest.addLevel(self.spinBoxHttpuserLevel.value())
        except Exception:
            pass

        return httpJSONFile

    def clearinboundHttpPanel(self):
        self.tableWidgetHttp.setRowCount(0)
        self.spinBoxHttpTimeout.setValue(300)
        self.spinBoxHttpuserLevel.setValue(0)
        self.checkBoxallowTransparent.setChecked(False)
        self.groupBoxHttpAuth.setChecked(False)

    def __debugTest(self):
        import json
        print(json.dumps(self.createHttpJSONFile(), indent=4, sort_keys=False))
Esempio n. 6
0
class WidgetCombinaciones(QWidget):
    def __init__(self, licitacion, con_descuento, parent=None):
        super().__init__(parent=parent)
        self.licitacion = licitacion
        self.caja_principal = QVBoxLayout()
        self.mostrar_descuentos = con_descuento
        self.tabla_combinaciones = QTableWidget(0,
                                                len(self.licitacion.lotes) + 4)

        self.mostrar_descuentos.setCheckState(Qt.Checked)
        self.mostrar_descuentos.stateChanged.connect(self.cambio_estado)
        self.llenar_tabla_combinaciones()
        self.tabla_combinaciones.verticalHeader().setVisible(False)
        self.tabla_combinaciones.setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.tabla_combinaciones.setHorizontalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.tabla_combinaciones.setSelectionBehavior(
            QAbstractItemView.SelectItems)
        self.tabla_combinaciones.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.tabla_combinaciones.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.tabla_combinaciones.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)
        self.installEventFilter(self)
        self.resizeColumnsToMaximumContent()

        self.caja_principal.addWidget(self.tabla_combinaciones)
        self.setLayout(self.caja_principal)

    def llenar_tabla_combinaciones(self):
        titulos = []
        titulos.append("N°")
        titulos.append("")
        for lote in self.licitacion.lotes:
            titulos.append(lote.obtener_descripcion())
        titulos.append("Valor Final")
        titulos.append("Descuento")
        self.tabla_combinaciones.setHorizontalHeaderLabels(titulos)
        self.tabla_combinaciones.horizontalHeaderItem(
            self.tabla_combinaciones.columnCount() -
            1).setToolTip("Se aplicó algún descuento?")
        self.tabla_combinaciones.horizontalHeaderItem(
            self.tabla_combinaciones.columnCount() -
            2).setToolTip("Valor final con los descuentos aplicados")
        self.tabla_combinaciones.horizontalHeaderItem(1).setIcon(
            QIcon("iconos/toggle.png"))
        self.tabla_combinaciones.horizontalHeader().sectionClicked.connect(
            self.seccion_clickeada)
        self.tabla_combinaciones.cellClicked.connect(self.item_clickeado)
        for i, combinacion in enumerate(
                self.licitacion.combinaciones_reducidas):
            fila = self.tabla_combinaciones.rowCount()
            self.tabla_combinaciones.setRowCount(fila + 1)
            item_numero = QTableWidgetItem("{0}".format(i + 1))
            self.tabla_combinaciones.setItem(fila, 0, item_numero)
            item_toggle = QTableWidgetItem(QIcon("iconos/toggle.png"), "")
            item_toggle.setTextAlignment(Qt.AlignCenter)
            item_toggle.setFlags(Qt.ItemIsEnabled)
            self.tabla_combinaciones.setItem(fila, 1, item_toggle)
            for j, lote in enumerate(self.licitacion.lotes):
                for posibilidad in combinacion.posibilidades:
                    if posibilidad.lote_contenido(lote):
                        oferta = posibilidad.oferta_de_lote(lote)
                        item_lote = QTableWidgetItemToggle(
                            posibilidad, oferta, self.mostrar_descuentos)
                        item_lote.setTextAlignment(Qt.AlignCenter)
                        self.tabla_combinaciones.setItem(
                            fila, j + 2, item_lote)
                        break
            item_valor_final = QTableWidgetItem("{0:,.3f}".format(
                combinacion.valor_con_adicional()))
            item_valor_final.setTextAlignment(Qt.AlignCenter)
            self.tabla_combinaciones.setItem(
                fila,
                self.tabla_combinaciones.columnCount() - 2, item_valor_final)
            item_con_descuento = QTableWidgetItem()
            if combinacion.valor() != combinacion.valor_con_adicional():
                item_con_descuento.setCheckState(Qt.Checked)
            else:
                item_con_descuento.setCheckState(Qt.Unchecked)
            item_con_descuento.setTextAlignment(Qt.AlignCenter)
            item_con_descuento.setFlags(Qt.ItemIsEnabled)
            self.tabla_combinaciones.setItem(
                fila,
                self.tabla_combinaciones.columnCount() - 1, item_con_descuento)

    def item_clickeado(self, fila, columna):
        if columna == 1:
            self.toggle(fila)

    def seccion_clickeada(self, indice):
        if indice == 1:
            self.toggle_all()

    def toggle(self, fila):
        for i in range(2, self.tabla_combinaciones.columnCount() - 2):
            item_lote = self.tabla_combinaciones.item(fila, i)
            if item_lote != None:
                item_lote.toggle()

    def toggle_all(self):
        for fila in range(self.tabla_combinaciones.rowCount()):
            self.toggle(fila)

    def cambio_estado(self, estado):
        self.actualizar_todo()

    def actualizar_fila(self, fila):
        for columna in range(2, self.tabla_combinaciones.columnCount() - 2):
            item_lote = self.tabla_combinaciones.item(fila, columna)
            if item_lote != None:
                item_lote.actualizar_texto()

    def actualizar_todo(self):
        for fila in range(self.tabla_combinaciones.rowCount()):
            self.actualizar_fila(fila)

    def resizeColumnsToMaximumContent(self):
        self.tabla_combinaciones.resizeColumnsToContents()
        maximo = max([
            self.tabla_combinaciones.columnWidth(i)
            for i in range(self.tabla_combinaciones.columnCount())
        ])
        for i in range(2, self.tabla_combinaciones.columnCount()):
            self.tabla_combinaciones.setColumnWidth(i, maximo + 10)
        self.tabla_combinaciones.setColumnWidth(1, 22)
        self.tabla_combinaciones.setColumnWidth(
            self.tabla_combinaciones.columnCount() - 1, 80)
        self.tabla_combinaciones.updateGeometry()
        self.tabla_combinaciones.adjustSize()
        self.adjustSize()

    def eventFilter(self, source, event):
        if (event.type() == QEvent.KeyPress
                and event.matches(QKeySequence.Copy)):
            self.copySelection()
            return True
        return super().eventFilter(source, event)

    def copySelection(self):
        selection = self.tabla_combinaciones.selectedIndexes()
        if selection:
            rows = sorted(index.row() for index in selection)
            columns = sorted(index.column() for index in selection)
            rowcount = rows[-1] - rows[0] + 1
            colcount = columns[-1] - columns[0] + 1
            table = [[''] * colcount for _ in range(rowcount)]
            for index in selection:
                row = index.row() - rows[0]
                column = index.column() - columns[0]
                table[row][column] = index.data()
            stream = StringIO()
            writer(stream, delimiter='\t').writerows(table)
            QGuiApplication.clipboard().setText(stream.getvalue())