예제 #1
0
파일: GUI.py 프로젝트: Diegojnb/JdeRobot
class MainWindow(QMainWindow):
    
    updGUI=pyqtSignal()
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setWindowTitle("Color tuner")

        self.iWidget = ImagesWidget(self)
        self.cWidget = ControlWidget(self)
        
        self.verticalLayoutWidget = QWidget(self)
        self.verticalLayoutWidget.setGeometry(QRect(20, 30, 361, 301))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.vLayout = QVBoxLayout(self.verticalLayoutWidget)
        self.vLayout.setObjectName("vLayout")
        self.vLayout.addWidget(self.iWidget)
        self.vLayout.addWidget(self.cWidget)

        self.iWidget.setVisible(True)
        self.cWidget.setVisible(True)

        self.updGUI.connect(self.updateGUI)

        #self.verticalLayoutWidget.setStyleSheet("background-color:black;")

        #self.controlCommunicator=Communicator()
        #self.imageCommunicator=Communicator()

        #self.setLayout(self.vLayout)
        self.setCentralWidget(self.verticalLayoutWidget)

        self.filt = 'Orig'


      
    def getCamera(self):
        return self.camera

    def setCamera(self,camera):
        self.camera = camera

    def getFilterName(self):
        return self.filt

    def setFilterName(self,filt):
        self.filt = filt
    
    def updateGUI(self):
        self.iWidget.imageUpdate.emit()
        #self.cWidget.controlUpdate.emit()

    def closeEvent(self, event):
        self.camera.stop()
        event.accept()
예제 #2
0
    def render_widget(self):
        height = 200
        layout = QVBoxLayout(self)
        layout.setObjectName('body')
        layout.setAlignment(Qt.AlignTop)
        header = QHBoxLayout()

        # Image
        imageWid = Picture(self.image.value, 240, 160)
        image_path = config.market.market_url + '/product/v1/allproducts/images/?path=' + self.image.value
        imageWid = ProductQML(self,
                              image=image_path,
                              img_width=240,
                              img_height=160)
        imageWid.obj.signals.click.connect(
            lambda: app.event.emit(app.events.DETAIL_UPDATE))
        header.addWidget(imageWid)

        right = QVBoxLayout()
        right.setAlignment(Qt.AlignTop)
        right.setSpacing(15)
        # Title
        title = Label(self.name)
        title.setObjectName('name')
        right.addWidget(title)

        # category
        catbox = QHBoxLayout()
        catbox.setSpacing(5)
        type_text = 'Batch' if self.ptype == 'file' else 'Streaming'
        icon = self.icon.value
        if icon:
            iconL = QLabel()
            iconL.setObjectName('icon')
            iconL.setPixmap(QPixmap(icon))
            catbox.addWidget(iconL)
        type_wid = Builder().text(type_text).name('type_text').style(
            "color: #444;font-size:14").build()
        catbox.addWidget(type_wid)
        catbox.addSpacing(10)
        category = Label(self.category)
        category.setObjectName('category')
        category.setAlignment(Qt.AlignCenter)
        category.setMaximumWidth(80)
        catbox.addWidget(category)
        catbox.addStretch(1)

        right.addLayout(catbox)

        # Timestamp and Remain Days
        tbox = QHBoxLayout()
        timestamp = QLabel(self.created.value)
        timestamp.setObjectName('timestamp')
        tbox.addWidget(timestamp)
        sales = QLabel(str(self.sales.value) + ' sales')
        sales.setObjectName('sales')
        tbox.addWidget(sales)

        tbox.addStretch(1)
        right.addLayout(tbox)

        # CPC and Sales
        hbox = QHBoxLayout()
        hbox.setObjectName('hbox1')

        cpc = QLabel(str(self.cpc.value))
        cpc.setObjectName('cpc')
        cpc_unit = QLabel('CPC')
        cpc_unit.setObjectName('cpc_unit')
        hbox.addWidget(cpc)
        hbox.addWidget(cpc_unit)

        # Buy button
        def openPurchaseDialog(_):
            self.buying(True)
            if not self.paying:
                market_hash = self.market_hash
                owner_address = self.owner_address
                purchaseDlg = PurchaseDialog(self,
                                             price=self.cpc,
                                             gas=self.gas,
                                             account=self.account,
                                             storagePath=self.storagePath,
                                             password=self.password,
                                             market_hash=market_hash,
                                             name=self.name.value,
                                             owner_address=owner_address)
                purchaseDlg.show()
        self.buy = Button.Builder(width=100, height=30).text('Buy')\
                                   .style('primary')\
                                   .click(openPurchaseDialog)\
                                   .build()
        hbox.addWidget(self.buy)
        if self.owner_address == wallet.market_client.public_key:
            self.buy.setEnabled(False)

        # Buy Loading
        self.buy_loading = Loading()
        hbox.addWidget(self.buy_loading)
        self.buy_loading.hide()

        hbox.addStretch(1)

        right.addLayout(hbox)
        header.addLayout(right)
        layout.addLayout(header)

        # Description
        desc = DetailHeader('Description')
        layout.addWidget(desc)
        desc = Label(self.description)
        desc.setWordWrap(True)
        layout.addWidget(desc)

        height += 300
        layout.addStretch(1)

        widget_ = QWidget()
        widget_.setObjectName('parent_widget')
        widget_.setLayout(layout)
        widget_.setFixedWidth(720)
        widget_.setFixedHeight(height)
        widget_.setStyleSheet(self.style())
        self.add_orders_ui(widget_)
        return widget_
예제 #3
0
class MainWindow(QWidget): #Main application GUI

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

        self.check_previous_data = 0
        self.previous_tickers = []
        self.basepath = path.dirname(__file__) #relative path

        if getattr(sys, 'frozen', False):
            # path of files changes if run as exe or script
            application_path = path.dirname(sys.executable)
        else:
            application_path = self.basepath

        try:
            historicPath = path.abspath(path.join(application_path,
                                                  "WSBhistoric_data.xlsx"))
            df = read_excel(historicPath)
            for tick in df[0]:
                self.previous_tickers.append(tick)
            self.check_previous_data = 1
            # print(self.previous_tickers)
        except: print("No previous data found")

        self.setWindowTitle("WSBFinScrape")
        self.setFixedSize(555, 620)
        self.setObjectName("myParentWidget")

        #create menu bar
        self.menubar = QMenuBar()
        self.menubar.setObjectName("menubar")
        supportMenu = self.menubar.addMenu("Support the Developer")
        supportMenu.addAction("Donate a Coffee", self.on_triggered_support)
        settingsMenu = self.menubar.addMenu("Settings")
        settingsMenu.addAction("Config", self.on_triggered_config)
        settingsMenu.addAction("Restart", self.restart)
        self.menubar.setStyleSheet("color: white;font-weight: bold;")
        self.menubar.setLayoutDirection(Qt.RightToLeft)


        # add window icon
        iconPath = path.abspath(path.join(self.basepath,"gorillaicon.jpg"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(iconPath), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.trayIcon = QSystemTrayIcon(QtGui.QIcon(iconPath), self)
        self.trayIcon.show()

        #add WSB logo
        WSBPath = path.abspath(path.join(self.basepath, "WallStreetBets.png"))
        self.WSBlabel = QLabel()
        self.WSBlabel.setAlignment(QtCore.Qt.AlignCenter |
                                   QtCore.Qt.AlignVCenter)
        self.WSBlabel.setText("")
        self.WSBlabel.setPixmap(QtGui.QPixmap(WSBPath))
        # self.label.setAlignment(Qt.AlignCenter)
        self.WSBlabel.setObjectName("label")

        # making scrollable area
        self.grid = QGridLayout()
        scrollwidget = QWidget()
        scrollwidget.setLayout(self.grid)
        scrollarea = QScrollArea()
        scrollarea.setWidgetResizable(True)
        scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scrollarea.setWidget(scrollwidget)
        self.mainLayout = QVBoxLayout()
        self.mainLayout.setObjectName("mainlayout")
        self.grid.setObjectName("gridlayout")

        self.mainLayout.addWidget(self.menubar)
        self.mainLayout.addWidget(self.WSBlabel)
        self.mainLayout.addWidget(scrollarea)

        self.setLayout(self.mainLayout)

        self.setStyleSheet("background-color: black;")

        labelstyle = "color: white; background-color: " \
                     "black; font-size: 8.2pt; font-weight: bold;"
        titleticker = QLabel("Ticker")
        titlePostCount = QLabel("#Mentions")
        titleStockPrice = QLabel("Current Price")
        titleDDcount = QLabel("#DD Posts")
        self.grid.addWidget(titlePostCount, 0, 1)
        self.grid.addWidget(titleStockPrice, 0, 2)
        self.grid.addWidget(titleticker, 0, 0)
        self.grid.addWidget(titleDDcount, 0, 3)
        titleticker.setStyleSheet(labelstyle)
        titleStockPrice.setStyleSheet(labelstyle)
        titlePostCount.setStyleSheet(labelstyle)
        titleDDcount.setStyleSheet(labelstyle)

        titlePostCount.setFixedSize(100, 30)
        titleticker.setFixedSize(160, 30)
        titleStockPrice.setFixedSize(100, 30)
        titleDDcount.setFixedSize(100, 30)

        titlePostCount.setAlignment(QtCore.Qt.AlignCenter |
                                    QtCore.Qt.AlignVCenter)
        titleStockPrice.setAlignment(QtCore.Qt.AlignCenter |
                                     QtCore.Qt.AlignVCenter)
        titleticker.setAlignment(QtCore.Qt.AlignCenter |
                                 QtCore.Qt.AlignVCenter)
        titleDDcount.setAlignment(QtCore.Qt.AlignCenter |
                                 QtCore.Qt.AlignVCenter)
        self.createTickButtons(mapping=sort_tickers)


    def createTickButtons(self, mapping):
        x = 0
        y = 0
        for key, value in mapping:
            # self.buttons.append(QPushButton(key))
            x += 1
            # y += 1
            button = QPushButton("$" + key)
            self.grid.addWidget(button, x, y)
            ticker_ob = OpenWindow()
            button.clicked.connect(partial(ticker_ob.handleTickerbutton,
                                           data=key))

            button.setFixedSize(160, 30)
            if self.check_previous_data == 1:
                if key not in self.previous_tickers:
                    button.setStyleSheet("QPushButton {border :2px solid "
                                         ";border-color: cyan; "
                                         "color: cyan; background-color: black;} "
                                         "QPushButton::pressed {background-color: "
                                         "grey;}")
                else:
                    button.setStyleSheet("QPushButton {border :2px solid "
                                     ";border-color: white; "
                                     "color: yellow; background-color: black;} "
                                     "QPushButton::pressed {background-color: "
                                     "grey;}")
            else: button.setStyleSheet("QPushButton {border :2px solid "
                                     ";border-color: white; "
                                     "color: yellow; background-color: black;} "
                                     "QPushButton::pressed {background-color: "
                                     "grey;}")

            button.setFont(QtGui.QFont('Times', 8))
            # button.set
            # self.buttons[-1].setFixedSize(40, 80)
            label = QLabel(str(value))
            self.grid.addWidget(label, x, 1)
            label.setStyleSheet("border :2px solid; color: yellow; "
                                "background-color: black;")
            label.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)

            try:
                label_DD_post = QLabel(str(count_DD_posts[key]))
                self.grid.addWidget(label_DD_post, x, 3)
                label_DD_post.setStyleSheet("border :2px solid; color: yellow; "
                                    "background-color: black;")
                label_DD_post.setAlignment(QtCore.Qt.AlignCenter |
                                      QtCore.Qt.AlignVCenter)
            except:
                label_DD_post = QLabel("0")
                self.grid.addWidget(label_DD_post, x, 3)
                label_DD_post.setStyleSheet("border :2px solid; color: yellow; "
                                            "background-color: black;")
                label_DD_post.setAlignment(QtCore.Qt.AlignCenter |
                                           QtCore.Qt.AlignVCenter)
        self.tickerPrice()
        self.dump_ticker_data()


    def tickerPrice(self):
        x = 0
        # today = datetime.date.today()
        for string_key in string_list:
            x += 1
            yest_container = float("{:.2f}".format(tickerPriceData[
                                                       string_key].iloc[0][
                                                       "Close"]))
            today_container = float("{:.2f}".format(tickerPriceData[
                                                        string_key].iloc[1][
                                                        "Close"]))
            price_label = QLabel("$ " + str(today_container))
            self.grid.addWidget(price_label, x, 2)
            price_label.setAlignment(
                QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)

            if today_container > yest_container:#Higher
                price_label.setStyleSheet("color: rgb(0,204,0); "
                                       "background-color: "
                                       "black;font-weight: bold")
            elif today_container < yest_container:#Lower
                price_label.setStyleSheet("color: rgb(255, 0, 0"
                                          "); background-color: "
                                          "black;font-weight: bold")
            #USE A SINGLE LABEL AND JUST SET STYLE SHEET
            elif today_container == yest_container:#Neutral
                price_label.setStyleSheet("color: white; background-color: "
                                          "black;font-weight: bold")
            else:
                error_label = price_label
                error_label.setText("!ERROR")
                error_label.setStyleSheet("color: grey; background-color: "
                                          "black;font-weight: bold")

        created_label = QLabel("created by Nebulezz")

        created_label.setStyleSheet("color: red; font-size: 8.2pt; "
                                    "font-weight: bold; font: italic;")
        created_label.setAlignment(
            QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
        self.mainLayout.addWidget(created_label)

    def dump_ticker_data(self):
        # create excel of tickers to check against in the future.
        ticker_dump = []
        for ticker in data_save_tickers:
            if ticker in ticker_dump:
                continue
            else:
                ticker_dump.append(ticker)
        historicDump = Series(ticker_dump)
        historicDump.to_excel('WSBhistoric_data.xlsx')


    def restart(self):#RESTARTS APPLICATION WITH INTERMEDIATE MESSAGEBOX
        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setText("Restart Application?")
        msgBox.setWindowTitle("Restart")
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

        returnValue = msgBox.exec()
        if returnValue == QMessageBox.Ok:
            execl(sys.executable, sys.executable, *sys.argv)

    @QtCore.pyqtSlot()
    def on_triggered_support(self):
        QtGui.QDesktopServices.openUrl(QtCore.QUrl("https://www.paypal.com/biz/fund?id=E34JBGHTN3DFJ"))

    @QtCore.pyqtSlot()
    def on_triggered_config(self):#TRIGGERED CONFIG MENU ACTION
        if getattr(sys, 'frozen', False):
            # path of files changes if run as exe or script
            application_path = path.dirname(sys.executable)
        else:
            application_path = self.basepath

        configPath = path.abspath(path.join(application_path,"WSBconfig.txt"))
        configRead = open(configPath, "r")
        configlist = re.findall(r'\d+', configRead.read())
        configval = configlist[0]

        def saveFile():#SAVES SELECTED NUMBER OF POSTS TO FILE
            configfile = open(configPath, "w")
            configfile.write("#Posts to read: " + str(sld.value()))
            print("Post count changed to: ", sld.value())
            configfile.close()

            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Information)
            msgBox.setText("Post Count Saved!")
            msgBox.setWindowTitle("Info")
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec()



        #CREATES DIALOG FOR CHANGING SETTINGS
        whoDialog = QDialog(self)
        whoDialog.setWindowTitle("Number of Posts to Read?")
        whoDialog.setFixedSize(350, 230)
        whoDialog.setContentsMargins(5, 0, 5, 5)
        whoDialog.setStyleSheet("color: white;")
        mainlayout = QGridLayout()  # mainlayout for diallog box
        whoDialog.setLayout(mainlayout)  # set mainlayout of dialog
        verticalLayoutWidget = QWidget()

        info_label = QLabel("WARNING! Increasing the post read amount "
                            "will increase app load time.")
        changes_label = QLabel("Restart app to see changes take affect.")
        saveButton = QPushButton("Save")
        saveButton.setStyleSheet("QPushButton {color: white; "
                                 "background-color: black; "
                                 "padding :5px; font-size: 9pt; border: 2px "
                                 "solid; border-color: white;}"
                                 "QPushButton::pressed {background-color: grey;}")
        number_label = QLabel(str(configval))
        number_label.setStyleSheet("color: white; background-color: black; "
                                 "padding :5px; font-size: 9pt;")
        number_label.setAlignment(
            QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)

        #CREATES A SLIDER FOR PICKING POST NUMBER
        sld = QSlider(Qt.Horizontal)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setMinimum(100)
        sld.setMaximum(1000)
        sld.setTickPosition(QSlider.TicksAbove)
        sld.setTickInterval(100)
        sld.setSingleStep(10)
        sld.setValue(int(configval))

        number_label.setWordWrap(True)
        info_label.setWordWrap(True)
        # changes_label.setWordWrap(True)
        mainlayout.addWidget(verticalLayoutWidget)
        mainlayout.addWidget(info_label, 0, 0, 2, 0)
        mainlayout.addWidget(number_label, 2, 2)
        mainlayout.addWidget(saveButton, 2, 3)
        mainlayout.addWidget(sld, 3, 0, 2, 0)
        mainlayout.addWidget(changes_label, 4, 0, 2, 0)

        def updateValue(value):
            number_label.setText(str(value))

        sld.valueChanged.connect(updateValue)#UPDATES LABEL WITH SLIDER VALUE
        saveButton.clicked.connect(saveFile)#CONNECTS TO SAVE FUNCTION
        whoDialog.exec_()
예제 #4
0
class SearchWidget(QWidget):
    checkBoxList = []
    webs = WEB_NAME

    def __init__(self, tabtab):
        super().__init__()
        self.tabtab = tabtab
        self.set_searchLayout()
        self.set_searchLabel()
        self.set_searchEdit()
        self.set_searchButton()
        self.set_urlBox()

        self.searchLayout.setStretch(0, 2)
        self.searchLayout.setStretch(1, 3)
        self.searchLayout.setStretch(2, 2)
        self.searchLayout.setStretch(3, 2)

        self.set_text()

    def set_searchLayout(self):
        self.searchLayout = QVBoxLayout(self)
        self.searchLayout.setContentsMargins(0, 30, 0, 0)
        self.searchLayout.setSpacing(10)
        self.searchLayout.setObjectName("searchLayout")

    def searchLayout_add(self, obj):
        self.searchLayout.addWidget(
            obj, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop)

    def set_searchLabel(self):
        self.searchLabel = QLabel(self)
        self.searchLabel.setEnabled(True)
        self.searchLabel.setMinimumSize(QtCore.QSize(200, 100))
        self.searchLabel.setMaximumSize(QtCore.QSize(600, 100))
        self.searchLabel.setSizeIncrement(QtCore.QSize(0, 0))
        font = QtGui.QFont()
        font.setPointSize(37)
        self.searchLabel.setFont(font)
        self.searchLabel.setObjectName("searchLabel")
        self.searchLayout_add(self.searchLabel)

    def set_searchEdit(self):
        self.searchEdit = QLineEdit(self)
        self.searchEdit.setMinimumSize(QtCore.QSize(300, 30))
        self.searchEdit.setMaximumSize(QtCore.QSize(600, 50))
        self.searchEdit.setAlignment(QtCore.Qt.AlignLeading
                                     | QtCore.Qt.AlignLeft
                                     | QtCore.Qt.AlignVCenter)
        self.searchEdit.setObjectName("searchEdit")
        self.searchLayout_add(self.searchEdit)

    def set_searchButton(self):
        self.searchButton = QPushButton(self)
        self.searchButton.setMinimumSize(QtCore.QSize(100, 30))
        self.searchButton.setMaximumSize(QtCore.QSize(300, 35))
        self.searchButton.setObjectName("searchButton")
        self.searchLayout_add(self.searchButton)

        # 绑定搜索按钮事件
        self.searchButton.clicked.connect(self.click_button)

    def click_button(self):
        self.searchButton.setText(_translate("MainWindow", "搜索中..."))
        search_word = self.searchEdit.text().strip()
        print('点击了按钮,开始搜索:{}'.format(search_word))
        r = Request()
        tabtab = self.tabtab
        # 遍历选中的web
        for i in range(min(len(self.webs), 10)):
            box = self.checkBoxList[i]
            if box.isChecked():
                print(box.text(), '开始搜索')
                queue = r.createSearchThread(box.text(), search_word)
                tabtab.add_ResultWidget_fuck(box.text(), queue)

    def set_urlBox(self):
        self.urlBox = QGroupBox(self)
        self.urlBox.setObjectName("urlBox")
        self.gridLayout = QGridLayout(self.urlBox)
        self.gridLayout.setObjectName("gridLayout")

        for y in range(2):
            for x in range(5):
                checkBox = QCheckBox(self.urlBox)
                checkBox.setObjectName("checkBox_{}_{}".format(x, y))
                self.gridLayout.addWidget(checkBox, y, x, 1, 1)
                self.checkBoxList.append(checkBox)
        self.searchLayout_add(self.urlBox)

    def set_text(self):
        self.searchLabel.setText(_translate("MainWindow", "小说下载器"))
        self.searchButton.setText(_translate("MainWindow", "搜索"))
        self.urlBox.setTitle(_translate("MainWindow", "选择搜索网站"))
        webs = self.webs
        webs_len = len(webs)
        for i in range(10):
            if i < webs_len:
                self.checkBoxList[i].setText(_translate("MainWindow", webs[i]))
                self.checkBoxList[i].setChecked(True)  # 选中它!
            else:
                self.checkBoxList[i].setText(_translate("MainWindow", 'null'))
                self.checkBoxList[i].setEnabled(False)
예제 #5
0
class EditorMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setupUi(self)
        self.retranslateUi(self)

        self.level = None
        path = get_default_path()
        if path is None:
            self.default_path = ""
        else:
            self.default_path = path

        self.dragging = False
        self.last_x = None
        self.last_y = None
        self.dragged_time = None
        self.deleting_item = False # Hack for preventing focusing on next item after deleting the previous one

        self.moving = False

        self.resetting = False

        self.entity_list_widget.currentItemChanged.connect(self.action_listwidget_change_selection)
        self.button_zoom_in.pressed.connect(self.zoom_in)
        self.button_zoom_out.pressed.connect(self.zoom_out)
        self.button_remove_entity.pressed.connect(self.remove_position)
        self.button_move_entity.pressed.connect(self.move_entity)
        self.button_clone_entity.pressed.connect(self.action_clone_entity)
        self.button_show_passengers.pressed.connect(self.action_passenger_window)
        self.button_edit_xml.pressed.connect(self.action_open_xml_editor)
        self.button_edit_base_xml.pressed.connect(self.action_open_basexml_editor)
        self.lineedit_angle.editingFinished.connect(self.action_lineedit_changeangle)


        self.bw_map_screen.mouse_clicked.connect(self.get_position)
        self.bw_map_screen.entity_clicked.connect(self.entity_position)
        self.bw_map_screen.mouse_dragged.connect(self.mouse_move)
        self.bw_map_screen.mouse_released.connect(self.mouse_release)
        self.bw_map_screen.mouse_wheel.connect(self.mouse_wheel_scroll_zoom)


        status = self.statusbar
        self.bw_map_screen.setMouseTracking(True)

        self.passenger_window = BWPassengerWindow()
        self.passenger_window.passengerlist.currentItemChanged.connect(self.passengerwindow_action_choose_entity)

        self.xmlobject_textbox = BWEntityXMLEditor()
        self.xmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_object_xml)
        self.xmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)


        self.basexmlobject_textbox = BWEntityXMLEditor(windowtype="XML Base Object")
        self.basexmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_base_object_xml)
        self.basexmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)

        self.types_visible = {}
        self.terrain_image = None

        status.showMessage("Ready")

        self.xml_windows = {}
        print("We are now ready!")

    def reset(self):
        self.resetting = True
        self.statusbar.clearMessage()
        self.dragged_time = None
        self.moving = False
        self.dragging = False
        self.last_x = None
        self.last_y = None
        self.dragged_time = None

        self.moving = False

        self.entity_list_widget.clearSelection()
        self.entity_list_widget.clear()

        self.bw_map_screen.reset()
        self.clear_visibility_toggles()

        for window in (self.passenger_window, self.xmlobject_textbox, self.basexmlobject_textbox):
            window.close()
            window.reset()

        for id in self.xml_windows:
            self.destroy_xml_editor(id)

        self.resetting = False

        print("reset done")

    def destroy_xml_editor(self, id):
        pass

    @catch_exception
    def open_xml_editor(self, objectid, offsetx=0, offsety=0):
        selected = objectid
        if self.level is not None and selected in self.level.obj_map:
            delete = []
            for objid, window in self.xml_windows.items():
                if not window.isVisible() and objid != selected:
                    window.destroy()
                    delete.append(objid)
            for objid in delete:
                del self.xml_windows[objid]

            if selected == self.basexmlobject_textbox.entity or selected == self.xmlobject_textbox.entity:
                pass # No need to make a new window
            elif selected in self.xml_windows and self.xml_windows[selected].isVisible():
                self.xml_windows[selected].activateWindow()
                self.xml_windows[selected].update()

            else:
                xml_window = BWEntityXMLEditor()

                def xmleditor_save_object_unlimited():
                    self.statusbar.showMessage("Saving object changes...")
                    try:
                        xmlnode = xml_window.get_content()
                        #assert self.bw_map_screen.current_entity == self.basexmlobject_textbox.entity
                        assert xml_window.entity == xmlnode.get("id")  # Disallow changing the id of the base object

                        self.level.remove_object(xmlnode.get("id"))
                        self.level.add_object(xmlnode)

                        self.statusbar.showMessage("Saved base object {0} as {1}".format(
                            xml_window.entity, self.level.obj_map[xmlnode.get("id")].name))
                    except:
                        self.statusbar.showMessage("Saving object failed")
                        traceback.print_exc()

                xml_window.button_xml_savetext.pressed.connect(xmleditor_save_object_unlimited)
                xml_window.triggered.connect(self.action_open_xml_editor_unlimited)


                obj = self.level.obj_map[selected]
                xml_window.set_title(obj.name)

                xml_window.set_content(obj._xml_node)
                #xml_window.move(QPoint(xml_editor_owner.pos().x()+20, xml_editor_owner.pos().y()+20))
                xml_window.move(QPoint(offsetx, offsety))

                xml_window.show()
                xml_window.update()
                self.xml_windows[selected] = xml_window



    @catch_exception
    def action_open_xml_editor_unlimited(self, xml_editor_owner):
        selected = xml_editor_owner.textbox_xml.textCursor().selectedText()
        self.open_xml_editor(selected,
                             offsetx=xml_editor_owner.pos().x()+20,
                             offsety=xml_editor_owner.pos().y()+20)

    @catch_exception
    def action_open_basexml_editor(self):
        """
        if not self.basexmlobject_textbox.isVisible():
            self.basexmlobject_textbox.destroy()
            self.basexmlobject_textbox = BWEntityXMLEditor(windowtype="XML Base Object")
            self.basexmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_base_object_xml)
            self.basexmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)
            self.basexmlobject_textbox.show()

        self.basexmlobject_textbox.activateWindow()"""
        if self.level is not None and self.bw_map_screen.current_entity is not None:
            obj = self.level.obj_map[self.bw_map_screen.current_entity]
            if not obj.has_attr("mBase"):
                pass
            else:
                baseobj = self.level.obj_map[obj.get_attr_value("mBase")]
                #self.basexmlobject_textbox.set_title(baseobj.id)
                self.open_xml_editor(baseobj.id)

    def xmleditor_action_save_base_object_xml(self):
        self.statusbar.showMessage("Saving base object changes...")
        try:
            xmlnode = self.basexmlobject_textbox.get_content()
            #assert self.bw_map_screen.current_entity == self.basexmlobject_textbox.entity
            assert self.basexmlobject_textbox.entity == xmlnode.get("id")  # Disallow changing the id of the base object

            self.level.remove_object(xmlnode.get("id"))
            self.level.add_object(xmlnode)

            self.statusbar.showMessage("Saved base object {0} as {1}".format(
                self.basexmlobject_textbox.entity, self.level.obj_map[xmlnode.get("id")].name))
        except:
            self.statusbar.showMessage("Saving base object failed")
            traceback.print_exc()

    def action_open_xml_editor(self):
        """
        if not self.xmlobject_textbox.isVisible():
            self.xmlobject_textbox.destroy()
            self.xmlobject_textbox = BWEntityXMLEditor()
            self.xmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_object_xml)
            self.xmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)
            self.xmlobject_textbox.show()

        self.xmlobject_textbox.activateWindow()"""
        if self.level is not None and self.bw_map_screen.current_entity is not None:
            entityobj = self.level.obj_map[self.bw_map_screen.current_entity]
            self.open_xml_editor(objectid=entityobj.id)

            update_mapscreen(self.bw_map_screen, self.level.obj_map[entityobj.id])
            self.bw_map_screen.update()

        """self.xmlobject_textbox.set_title(entityobj.id)

            self.xmlobject_textbox.set_content(entityobj._xml_node)

            self.xmlobject_textbox.update()"""

    def xmleditor_action_save_object_xml(self):
        self.statusbar.showMessage("Saving object changes...")
        try:
            xmlnode = self.xmlobject_textbox.get_content()
            #assert self.bw_map_screen.current_entity == self.xmlobject_textbox.entity
            assert self.xmlobject_textbox.entity == xmlnode.get("id") or xmlnode.get("id") not in self.level.obj_map

            if self.passenger_window.isVisible():
                self.passenger_window.close()

            if self.xmlobject_textbox.entity != xmlnode.get("id"):
                #obj = self.level.obj_map[xmlnode.get("id")]
                self.level.remove_object(self.xmlobject_textbox.entity)
                print("adding", xmlnode.get("id"), xmlnode.get("id") in self.level.obj_map )
                self.level.add_object(xmlnode)

                pos = self.get_entity_item_pos(self.xmlobject_textbox.entity)
                item = self.entity_list_widget.takeItem(pos)
                self.entity_list_widget.removeItemWidget(item)
                self.add_item_sorted(xmlnode.get("id"))

                self.bw_map_screen.rename_entity(self.xmlobject_textbox.entity, xmlnode.get("id"))
                assert xmlnode.get("id") in self.level.obj_map
                self.xmlobject_textbox.entity = xmlnode.get("id")
                self.xmlobject_textbox.set_title(xmlnode.get("id"))

            else:
                self.level.remove_object(xmlnode.get("id"))
                self.level.add_object(xmlnode)

            update_mapscreen(self.bw_map_screen, self.level.obj_map[xmlnode.get("id")])

            self.statusbar.showMessage("Saved object {0} as {1}".format(
                self.xmlobject_textbox.entity, self.level.obj_map[xmlnode.get("id")].name))
            self.bw_map_screen.update()

        except:
            self.statusbar.showMessage("Saving object failed")
            traceback.print_exc()

    def action_clone_entity(self):
        entities = []
        if self.bw_map_screen.current_entity is not None:
            entities.append(self.bw_map_screen.current_entity)
        elif len(self.bw_map_screen.selected_entities) > 0:
            entities.extend(self.bw_map_screen.selected_entities.keys())

        if len(entities) > 0:
            dont_clone = {}
            for entity in entities:
                obj = self.level.obj_map[entity]
                if obj.has_attr("mPassenger"):
                    passengers = obj.get_attr_elements("mPassenger")
                    for passenger in passengers:
                        if passenger != "0":
                            dont_clone[passenger] = True
            select = []
            for entity in entities:
                if entity in dont_clone:
                    continue

                obj = self.level.obj_map[entity]

                xml_node = deepcopy(obj._xml_node)
                try:
                    cloned_id = self.level.generate_unique_id(entity)
                    xml_node.set("id", cloned_id)
                    self.level.add_object(xml_node)

                    bw_x, bw_y, angle = object_get_position(self.level, cloned_id)
                    x, y = bw_coords_to_image_coords(bw_x, bw_y)

                    self.add_item_sorted(cloned_id)

                    self.bw_map_screen.add_entity(x, y, cloned_id, obj.type)

                    clonedobj = self.level.obj_map[cloned_id]
                    select.append(cloned_id)
                    update_mapscreen(self.bw_map_screen, clonedobj)
                    if clonedobj.has_attr("mPassenger"):
                        orig_x = bw_x
                        orig_y = bw_y
                        passengers = clonedobj.get_attr_elements("mPassenger")

                        passengers_added = []

                        for i, passenger in enumerate(passengers):
                            if passenger != "0":
                                obj = self.level.obj_map[passenger]
                                xml_node = deepcopy(obj._xml_node)

                                clonedpassenger_id = self.level.generate_unique_id(passenger)
                                xml_node.set("id", clonedpassenger_id)
                                #print("orig passenger: {0}, new passenger: {1}, alreadyexists: {2}".format(
                                #    passenger, clonedpassenger_id, clonedpassenger_id in self.level.obj_map
                                #))
                                #print(type(passenger), type(clonedpassenger_id))

                                self.level.add_object(xml_node)
                                #x, y = object_get_position(self.level, newid)
                                x = orig_x + (i+1)*8
                                y = orig_y + (i+1)*8
                                #print(orig_x, orig_y, x, y)
                                object_set_position(self.level, clonedpassenger_id, x, y)
                                x, y = bw_coords_to_image_coords(x, y)

                                self.add_item_sorted(clonedpassenger_id)
                                self.bw_map_screen.add_entity(x, y, clonedpassenger_id, obj.type)
                                update_mapscreen(self.bw_map_screen, self.level.obj_map[clonedpassenger_id])
                                passengers_added.append(passenger)
                                clonedobj.set_attr_value("mPassenger", clonedpassenger_id, i)
                                select.append(clonedpassenger_id)
                        #print("passengers added:", passengers_added)
                    self.bw_map_screen.selected_entities = {}
                    if len(select) == 1:
                        ent = select[0]
                        self.set_entity_text(ent)
                        self.bw_map_screen.choose_entity(ent)
                    else:
                        for ent in select:
                            self.bw_map_screen.selected_entities[ent] = True
                        self.set_entity_text_multiple(self.bw_map_screen.selected_entities)
                    self.bw_map_screen.update()
                except:
                    traceback.print_exc()

    def add_item_sorted(self, entity):
        max_count = self.entity_list_widget.count()
        entityobj = self.level.obj_map[entity]
        index = 0
        entity_item = BWEntityEntry(entity, "{0}[{1}]".format(entity, entityobj.type))

        # Similar to loading a level, we add the entity in a sorted way by
        # creating this string and comparing it for every item in the list.
        entity_string = get_type(entityobj.type)+entityobj.type+entityobj.id

        inserted = False

        for i in range(max_count):
            curritem = self.entity_list_widget.item(i)
            currobj = self.level.obj_map[curritem.xml_ref]
            currstring = get_type(currobj.type)+currobj.type+currobj.id

            # The list is already sorted, so if we find an item bigger than
            # the one we are inserting, we know the position we have to insert the item in.
            # String comparison should be alpabetically.
            if currstring > entity_string:
                self.entity_list_widget.insertItem(i, entity_item)
                inserted = True
                break

        # If we couldn't insert the item, i.e. there are no items at all
        # or all items are smaller than the item we add, we just add it at the end.
        if not inserted:
            self.entity_list_widget.addItem(entity_item)

    def get_entity_item_pos(self, entityid):
        for i in range(self.entity_list_widget.count()):
            item = self.entity_list_widget.item(i)

            if item.xml_ref == entityid:
                return i

        return None

    def action_passenger_window(self):
        #if self.passenger_window.isVisible()
        print("window is visible: ", self.passenger_window.isVisible())
        #self.passenger_window.reset()

        if not self.passenger_window.isVisible():
            self.passenger_window.destroy()
            self.passenger_window = BWPassengerWindow()
            self.passenger_window.passengerlist.currentItemChanged.connect(self.passengerwindow_action_choose_entity)
            self.passenger_window.show()

        self.passenger_window.activateWindow()
        if self.bw_map_screen.current_entity is not None:
            self.passenger_window.reset()
            entityobj = self.level.obj_map[self.bw_map_screen.current_entity]
            self.passenger_window.set_title(entityobj.id)
            if entityobj.has_attr("mPassenger"):
                for i, passenger in enumerate(entityobj.get_attr_elements("mPassenger")):
                    if passenger in self.level.obj_map:
                        passengerobj = self.level.obj_map[passenger]
                        list_item_name = "{0}[{1}]".format(passenger, passengerobj.type)
                    elif passenger == "0":
                        list_item_name = "{0}<none>".format(passenger)
                    else:
                        list_item_name = "{0}<missing>".format(passenger)
                    self.passenger_window.add_passenger(list_item_name, passenger)
            self.passenger_window.update()

    def passengerwindow_action_choose_entity(self, current, previous):
        try:
            if current is not None and current.xml_ref in self.level.obj_map:
                self.set_entity_text(current.xml_ref)
                self.bw_map_screen.choose_entity(current.xml_ref)
            elif current is not None:
                self.statusbar.showMessage("No such entity: {0}".format(current.xml_ref), 1000*2)
        except:
            traceback.print_exc()

    def move_entity(self):
        if not self.dragging:
            if not self.moving:
                self.moving = True
                currtext = self.button_move_entity.text()
                self.button_move_entity.setText("Stop [Move Entity]")
            else:
                self.moving = False

                currtext = "Move Entity"
                self.button_move_entity.setText(currtext)

    def button_load_level(self):
        try:
            print("ok", self.default_path)
            self.xmlPath = ""
            filepath, choosentype = QFileDialog.getOpenFileName(
                self, "Open File",
                self.default_path,
                BW_LEVEL+";;"+BW_COMPRESSED_LEVEL+";;All files (*)")
            print("doooone")
            if filepath:
                print("resetting")
                self.reset()
                print("done")
                print("chosen type:",choosentype)

                # Some BW levels are clear XML files, some are compressed with GZIP
                # We decide between the two either based on user choice or end of filepath
                if choosentype == BW_COMPRESSED_LEVEL or filepath.endswith(".gz"):
                    print("OPENING AS COMPRESSED")
                    file_open = gzip.open
                else:
                    file_open = open

                with file_open(filepath, "rb") as f:
                    try:
                        self.level = BattWarsLevel(f)
                        self.default_path = filepath
                        set_default_path(filepath)

                        self.setup_visibility_toggles()

                        for obj_id, obj in sorted(self.level.obj_map.items(),
                                                  key=lambda x: get_type(x[1].type)+x[1].type+x[1].id):
                            #print("doing", obj_id)
                            if get_position_attribute(obj) is None:
                                continue
                            #if not obj.has_attr("Mat"):
                            #    continue
                            x, y, angle = object_get_position(self.level, obj_id)
                            assert type(x) != str
                            x, y = bw_coords_to_image_coords(x, y)

                            item = BWEntityEntry(obj_id, "{0}[{1}]".format(obj_id, obj.type))
                            self.entity_list_widget.addItem(item)

                            self.bw_map_screen.add_entity(x, y, obj_id, obj.type, update=False)
                            #if obj.type == "cMapZone":
                            update_mapscreen(self.bw_map_screen, obj)

                        print("ok")
                        self.bw_map_screen.update()
                        path_parts = path.split(filepath)
                        self.setWindowTitle("BW-MapEdit - {0}".format(path_parts[-1]))

                    except Exception as error:
                        print("error", error)
                        traceback.print_exc()
        except Exception as er:
            print("errrorrr", er)
            traceback.print_exc()
        print("loaded")

    def button_save_level(self):
        if self.level is not None:
            filepath, choosentype = QFileDialog.getSaveFileName(
                self, "Save File",
                self.default_path,
                BW_LEVEL+";;"+BW_COMPRESSED_LEVEL+";;All files (*)")
            print(filepath, "saved")

            if filepath:
                # Simiar to load level
                if choosentype == BW_COMPRESSED_LEVEL or filepath.endswith(".gz"):
                    file_open = gzip.open
                else:
                    file_open = open
                try:
                    with file_open(filepath, "wb") as f:
                        self.level._tree.write(f)
                except Exception as error:
                    print("COULDN'T SAVE:", error)
                    traceback.print_exc()

                self.default_path = filepath
        else:
            pass # no level loaded, do nothing

    def entity_position(self, event, entity):
        try:
            # Make it possible to select objects in move mode, but don't make it too easy to lose
            # a selection.
            if not (self.moving and len(self.bw_map_screen.selected_entities) > 1):
                print("got entity:",entity, self.bw_map_screen.entities[entity][2])
                print(entity_get_model(self.level, entity))
                self.set_entity_text(entity)
                self.bw_map_screen.choose_entity(entity)
                pos = self.get_entity_item_pos(entity)
                print("searching:",pos)
                try:
                    self.entity_list_widget.select_item(pos)
                except:
                    traceback.print_exc()
                self.bw_map_screen.selected_entities = {}

                self.bw_map_screen.update()

        except:
            traceback.print_exc()

    def remove_position(self):
        #self.bw_map_screen.entities.pop()
        try:
            # Remove the entity from the map, the list widget and the level data
            self.deleting_item = True
            entities = []
            if self.bw_map_screen.current_entity is not None:
                entities.append(self.bw_map_screen.current_entity)
            elif len(self.bw_map_screen.selected_entities) > 0:
                entities.extend(self.bw_map_screen.selected_entities.keys())
                self.bw_map_screen.selected_entities = {}
                self.set_entity_text_multiple(self.bw_map_screen.selected_entities)
            if len(entities) > 0:
                for entity in entities:
                    pos = self.get_entity_item_pos(entity)
                    item = self.entity_list_widget.takeItem(pos)
                    assert item.xml_ref == entity
                    #self.entity_list_widget.clearSelection()
                    self.entity_list_widget.clearFocus()
                    self.entity_list_widget.removeItemWidget(item)
                    self.level.remove_object(entity)
                    self.bw_map_screen.remove_entity(entity)

                self.bw_map_screen.update()
        except:
            traceback.print_exc()
            raise

    #@catch_exception
    def get_position(self, event):
        self.dragging = True
        self.last_x = event.x()
        self.last_y = event.y()
        self.dragged_time = default_timer()

        mouse_x = event.x()/self.bw_map_screen.zoom_factor
        mouse_y = event.y()/self.bw_map_screen.zoom_factor

        if event.buttons() == QtCore.Qt.LeftButton:

            if not self.moving:
                self.bw_map_screen.set_selectionbox_start((event.x(), event.y()))
            else:
                if self.bw_map_screen.current_entity is not None:
                    newx, newy = image_coords_to_bw_coords(mouse_x, mouse_y)
                    object_set_position(self.level, self.bw_map_screen.current_entity,
                                        newx, newy)
                    self.bw_map_screen.move_entity(self.bw_map_screen.current_entity,
                                                   mouse_x, mouse_y)
                    self.set_entity_text(self.bw_map_screen.current_entity)

                    update_mapscreen(self.bw_map_screen, self.level.obj_map[self.bw_map_screen.current_entity])

                elif len(self.bw_map_screen.selected_entities) > 0:
                    for entity in self.bw_map_screen.selected_entities:
                        first_entity = entity
                        break
                    #first_entity = self.bw_map_screen.selected_entities.keys()[0]
                    x, y, entitytype, metadata = self.bw_map_screen.entities[first_entity]
                    startx = endx = x
                    starty = endy = y

                    for entity in self.bw_map_screen.selected_entities:
                        x, y, dontneed, dontneed = self.bw_map_screen.entities[entity]
                        if x < startx:
                            startx = x
                        if x > endx:
                            endx = x
                        if y < starty:
                            starty = y
                        if y > endy:
                            endy = y
                    middle_x = (startx+endx) / 2
                    middle_y = (starty+endy) / 2

                    delta_x = mouse_x - middle_x
                    delta_y = mouse_y - middle_y

                    for entity in self.bw_map_screen.selected_entities:
                        x, y, dontneed, dontneed = self.bw_map_screen.entities[entity]

                        newx, newy = image_coords_to_bw_coords(x+delta_x, y+delta_y)
                        object_set_position(self.level, entity,
                                            newx, newy)
                        self.bw_map_screen.move_entity(entity,
                                                       x+delta_x, y+delta_y)
                        #self.set_entity_text(self.bw_map_screen.current_entity)

                        update_mapscreen(self.bw_map_screen, self.level.obj_map[entity])

            self.bw_map_screen.update()

    @catch_exception
    def mouse_move(self, event):
        x, y = image_coords_to_bw_coords(event.x()/self.bw_map_screen.zoom_factor,
                                         event.y()/self.bw_map_screen.zoom_factor)
        self.statusbar.showMessage("x: {0} y: {1}".format(round(x, 5), round(y, 5)))

        if self.dragging and default_timer() - self.dragged_time > 0.1:
            if event.buttons() == QtCore.Qt.RightButton:
                delta_x = (event.x()-self.last_x)/8
                delta_y = (event.y()-self.last_y)/8
                #print("hi",event.x(), event.y())

                vertbar = self.scrollArea.verticalScrollBar()
                horizbar = self.scrollArea.horizontalScrollBar()

                vertbar.setSliderPosition(vertbar.value()-delta_y)
                horizbar.setSliderPosition(horizbar.value()-delta_x)

            elif event.buttons() == QtCore.Qt.LeftButton:
                self.bw_map_screen.set_selectionbox_end((event.x(), event.y()))
                if len(self.bw_map_screen.selected_entities) > 0 or self.bw_map_screen.current_entity is None:
                    self.bw_map_screen.choose_entity(None)
                    self.set_entity_text_multiple(self.bw_map_screen.selected_entities)
                self.bw_map_screen.update()

    def mouse_release(self, event):
        self.dragging = False
        if self.bw_map_screen.selectionbox_end is not None:
            self.bw_map_screen.clear_selection_box()
            self.bw_map_screen.update()

    def set_entity_text_multiple(self, entities):
        self.label_object_id.setText("{0} objects selected".format(len(entities)))
        MAX = 15
        listentities = [self.level.obj_map[x].name for x in sorted(entities.keys())][0:MAX]
        listentities.sort()
        if len(entities) > MAX:
            listentities.append("... and {0} more".format(len(entities) - len(listentities)))
        self.label_position.setText("\n".join(listentities[:5]))
        self.label_model_name.setText("\n".join(listentities[5:10]))
        self.label_4.setText("\n".join(listentities[10:]))#15]))
        self.label_5.setText("")#("\n".join(listentities[12:16]))

    def set_entity_text(self, entityid):
        try:
            obj = self.level.obj_map[entityid]
            if obj.has_attr("mBase"):
                base = self.level.obj_map[obj.get_attr_value("mBase")]
                self.label_object_id.setText("{0}\n[{1}]\nBase: {2}\n[{3}]".format(
                    entityid, obj.type, base.id, base.type))
            else:
                self.label_object_id.setText("{0}\n[{1}]".format(entityid, obj.type))
            self.label_model_name.setText("Model: {0}".format(entity_get_model(self.level, entityid)))
            x, y, angle = object_get_position(self.level, entityid)
            self.label_position.setText("x: {0}\ny: {1}".format(x, y))
            self.lineedit_angle.setText(str(round(angle,2)))
            self.label_4.setText("Army: {0}".format(entity_get_army(self.level, entityid)))
            if not obj.has_attr("mPassenger"):
                self.label_5.setText("Icon Type: \n{0}".format(entity_get_icon_type(self.level, entityid)))
            else:

                passengers = 0
                for passenger in obj.get_attr_elements("mPassenger"):
                    if passenger != "0":
                        passengers += 1
                self.label_5.setText("Icon Type: \n{0}\n\nPassengers: {1}".format(
                    entity_get_icon_type(self.level, entityid), passengers))
        except:
            traceback.print_exc()

    def action_listwidget_change_selection(self, current, previous):
        #QtWidgets.QListWidgetItem.
        if not self.resetting and current is not None:
            print("ok")
            print("hi", current.text(), current.xml_ref)

            self.set_entity_text(current.xml_ref)
            self.bw_map_screen.choose_entity(current.xml_ref)

            posx, posy, typename, metadata = self.bw_map_screen.entities[current.xml_ref]
            zf = self.bw_map_screen.zoom_factor
            try:
                if not self.deleting_item:
                    x_margin = min(100, 50*zf)
                    y_margin = min(100, 50*zf)
                    self.scrollArea.ensureVisible(posx*zf, posy*zf,
                                                  xMargin=x_margin, yMargin=y_margin)
                else:
                    self.deleting_item = False
            except:
                traceback.print_exc()

    def zoom_out(self, noslider=False):

        horizbar = self.scrollArea.horizontalScrollBar()
        vertbar = self.scrollArea.verticalScrollBar()

        print(horizbar.maximum(), vertbar.maximum())

        if horizbar.maximum() > 0:
            widthratio = horizbar.value()/horizbar.maximum()
        else:
            widthratio = 0

        if vertbar.maximum() > 0:
            heightratio = vertbar.value()/vertbar.maximum()
        else:
            heightratio = 0

        #oldzf = self.bw_map_screen.zoom_factor / (0.1+1)
        #diff = oldzf - self.bw_map_screen.zoom_factor
        zf = self.bw_map_screen.zoom_factor
        self.bw_map_screen.zoom(calc_zoom_out_factor(zf))#diff)

        #
        if not noslider:
            horizbar.setSliderPosition(horizbar.maximum()*widthratio)
            vertbar.setSliderPosition(vertbar.maximum()*heightratio)
            self.bw_map_screen.update()

        self.statusbar.showMessage("Zoom: {0}x".format(self.bw_map_screen.zoom_factor))

    def zoom_in(self, noslider=False):
        horizbar = self.scrollArea.horizontalScrollBar()
        vertbar = self.scrollArea.verticalScrollBar()

        if horizbar.maximum() > 0:
            widthratio = horizbar.value()/horizbar.maximum()
        else:
            widthratio = 0

        if vertbar.maximum() > 0:
            heightratio = vertbar.value()/vertbar.maximum()
        else:
            heightratio = 0

        zf = self.bw_map_screen.zoom_factor
        self.bw_map_screen.zoom(calc_zoom_in_factor(zf))#zf)

        #

        print("wedidit?")
        if not noslider:
            horizbar.setSliderPosition(horizbar.maximum()*widthratio)
            vertbar.setSliderPosition(vertbar.maximum()*heightratio)
            self.bw_map_screen.update()

        self.statusbar.showMessage("Zoom: {0}x".format(self.bw_map_screen.zoom_factor))

    @catch_exception
    def mouse_wheel_scroll_zoom(self, wheel_event):
        print("scrolling", wheel_event)
        print("Scroll", wheel_event.x(), wheel_event.y(), wheel_event.angleDelta().y())#, wheel_event.delta())

        wheel_delta = wheel_event.angleDelta().y()
        zf = self.bw_map_screen.zoom_factor
        norm_x = wheel_event.x()/zf
        norm_y = wheel_event.y()/zf
        if wheel_delta > 0:
            if zf <= 10:
                self.zoom_in(True)

                zf = self.bw_map_screen.zoom_factor

                xmargin = self.scrollArea.viewport().width()//2 - 200
                ymargin = self.scrollArea.viewport().height()//2 - 200
                self.scrollArea.ensureVisible(norm_x*zf, norm_y*zf, xmargin, ymargin)
                self.bw_map_screen.update()
            else:
                self.zoom_in()
        elif wheel_delta < 0:
            self.zoom_out()



    def action_lineedit_changeangle(self):
        if not self.resetting and self.bw_map_screen.current_entity is not None:
            print("ok")
            current = self.bw_map_screen.current_entity
            currx, curry, angle = object_get_position(self.level, current)

            newangle = self.lineedit_angle.text().strip()
            print(newangle, newangle.isdecimal())
            try:
                angle = float(newangle)
                object_set_position(self.level, current, currx, curry, angle=angle)
                currentobj = self.level.obj_map[current]
                update_mapscreen(self.bw_map_screen, currentobj)
                self.bw_map_screen.update()
            except:
                traceback.print_exc()

    def button_terrain_load_action(self):
        try:
            print("ok", self.default_path)
            filepath, choosentype = QFileDialog.getOpenFileName(
                self, "Open File",
                self.default_path,
                "BW terrain files (*.out *out.gz);;All files (*)")
            print("doooone")
            if filepath:
                if filepath.endswith(".gz"):
                    file_open = gzip.open
                else:
                    file_open = open

                with file_open(filepath, "rb") as f:
                    try:
                        terrain = BWArchiveBase(f)
                        if self.level is not None:
                            waterheight = get_water_height(self.level)
                        else:
                            waterheight = None

                        image, light_image = parse_terrain_to_image(terrain, waterheight)
                        self.bw_map_screen.set_terrain(image, light_image)
                    except:
                        traceback.print_exc()
        except:
            traceback.print_exc()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(820, 760)
        MainWindow.setMinimumSize(QSize(720, 560))
        MainWindow.setWindowTitle("BW-MapEdit")
        #MainWindow.setWindowTitle("Nep-Nep")


        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)

        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")


        self.scrollArea = QScrollArea(self.centralwidget)
        self.scrollArea.setWidgetResizable(True)

        self.bw_map_screen = BWMapViewer(self.centralwidget)
        self.scrollArea.setWidget(self.bw_map_screen)
        self.horizontalLayout.addWidget(self.scrollArea)

        #self.horizontalLayout.addWidget(self.bw_map_screen)

        self.entity_list_widget = BWEntityListWidget(self.centralwidget)
        self.entity_list_widget.setMaximumSize(QSize(300, 16777215))
        self.entity_list_widget.setObjectName("entity_list_widget")
        self.horizontalLayout.addWidget(self.entity_list_widget)

        spacerItem = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.horizontalLayout.addItem(spacerItem)

        self.vertLayoutWidget = QWidget(self.centralwidget)
        self.vertLayoutWidget.setMaximumSize(QSize(250, 1200))
        self.verticalLayout = QVBoxLayout(self.vertLayoutWidget)
        self.verticalLayout.setObjectName("verticalLayout")
        #self.verticalLayout.
        self.button_clone_entity = QPushButton(self.centralwidget)
        self.button_clone_entity.setObjectName("button_clone_entity")
        self.verticalLayout.addWidget(self.button_clone_entity)

        self.button_remove_entity = QPushButton(self.centralwidget)
        self.button_remove_entity.setObjectName("button_remove_entity")
        self.verticalLayout.addWidget(self.button_remove_entity)

        self.button_move_entity = QPushButton(self.centralwidget)
        self.button_move_entity.setObjectName("button_move_entity")
        self.verticalLayout.addWidget(self.button_move_entity)

        self.button_show_passengers = QPushButton(self.centralwidget)
        self.button_show_passengers.setObjectName("button_move_entity")
        self.verticalLayout.addWidget(self.button_show_passengers)


        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")

        self.button_zoom_in = QPushButton(self.centralwidget)
        self.button_zoom_in.setObjectName("button_zoom_in")
        self.gridLayout.addWidget(self.button_zoom_in, 0, 0, 0, 1)

        self.button_zoom_out = QPushButton(self.centralwidget)
        self.button_zoom_out.setObjectName("button_zoom_out")
        self.gridLayout.addWidget(self.button_zoom_out, 0, 1, 0, 1)

        self.button_edit_xml = QPushButton(self.centralwidget)
        self.button_edit_xml.setObjectName("button_edit_xml")

        self.button_edit_base_xml = QPushButton(self.centralwidget)
        self.button_edit_base_xml.setObjectName("button_edit_base_xml")


        self.verticalLayout.addLayout(self.gridLayout)
        self.verticalLayout.addWidget(self.button_edit_xml)
        self.verticalLayout.addWidget(self.button_edit_base_xml)

        spacerItem1 = QSpacerItem(10, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem1)

        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")


        self.lineedit_angle = QLineEdit(self.centralwidget)
        self.lineedit_angle.setObjectName("lineedit_angle")
        self.lineedit_angle.setPlaceholderText("Angle")

        self.label_object_id = QLabel(self.centralwidget)
        self.label_object_id.setObjectName("label_object_id")
         #TextSelectableByCursor

        self.label_position = QLabel(self.centralwidget)
        self.label_position.setObjectName("label_position")

        self.label_model_name = QLabel(self.centralwidget)
        self.label_model_name.setObjectName("label_model_name")

        self.label_4 = QLabel(self.centralwidget)
        self.label_4.setObjectName("label_4")

        self.label_5 = QLabel(self.centralwidget)
        self.label_5.setObjectName("label_5")

        for label in (self.label_object_id, self.label_position, self.label_model_name, self.label_4, self.label_5):
            label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)

        self.verticalLayout_2.addWidget(self.lineedit_angle)
        self.verticalLayout_2.addWidget(self.label_object_id)
        self.verticalLayout_2.addWidget(self.label_position)
        self.verticalLayout_2.addWidget(self.label_model_name)
        self.verticalLayout_2.addWidget(self.label_4)
        self.verticalLayout_2.addWidget(self.label_5)


        self.verticalLayout.addLayout(self.verticalLayout_2)

        self.horizontalLayout.addWidget(self.vertLayoutWidget)

        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 820, 29))
        self.menubar.setObjectName("menubar")
        self.file_menu = QMenu(self.menubar)
        self.file_menu.setObjectName("menuLoad")



        self.file_load_action = QAction("Load", self)
        self.file_load_action.triggered.connect(self.button_load_level)
        self.file_menu.addAction(self.file_load_action)
        self.file_save_action = QAction("Save", self)
        self.file_save_action.triggered.connect(self.button_save_level)
        self.file_menu.addAction(self.file_save_action)

        self.visibility_menu = MenuDontClose(self.menubar)#QMenu(self.menubar)
        self.visibility_menu.setObjectName("visibility")



        #self.visibility_menu.addAction(self.toggle_action)
        self.visibility_actions = []

        self.terrain_menu = QMenu(self.menubar)
        self.terrain_menu.setObjectName("terrain")

        self.terrain_load_action = QAction("Load Terrain", self)
        self.terrain_load_action.triggered.connect(self.button_terrain_load_action)
        self.terrain_menu.addAction(self.terrain_load_action)
        self.terrain_display_actions = []
        self.setup_terrain_display_toggles()

        #self.menuLoad_2 = QMenu(self.menubar)
        #self.menuLoad_2.setObjectName("menuLoad_2")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.file_menu.menuAction())
        #self.menubar.addAction(self.menuLoad_2.menuAction())
        self.menubar.addAction(self.visibility_menu.menuAction())
        self.menubar.addAction(self.terrain_menu.menuAction())
        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)


    def make_terrain_toggle(self, show_mode):
        def terraintoggle(toggled):
            print("I am", show_mode, "and I was pressed")
            if toggled is True:
                for action, toggle, mode in self.terrain_display_actions:
                    if mode != show_mode:
                        action.setChecked(False)
                self.bw_map_screen.set_show_terrain_mode(show_mode)
            elif toggled is False:
                self.bw_map_screen.set_show_terrain_mode(SHOW_TERRAIN_NO_TERRAIN)
            else:
                print("This shouldn't be possible", toggled, type(toggled))
            self.bw_map_screen.update()
        return terraintoggle

    def setup_terrain_display_toggles(self):
        for mode, name in ((SHOW_TERRAIN_REGULAR, "Show Heightmap"),
                            (SHOW_TERRAIN_LIGHT, "Show Lightmap")):
            toggle = self.make_terrain_toggle(mode)
            toggle_action = QAction(name, self)
            toggle_action.setCheckable(True)
            if mode == SHOW_TERRAIN_REGULAR:
                toggle_action.setChecked(True)
            else:
                toggle_action.setChecked(False)
            toggle_action.triggered.connect(toggle)
            self.terrain_menu.addAction(toggle_action)
            self.terrain_display_actions.append((toggle_action, toggle, mode))

    def clear_terrain_toggles(self):
        try:
            for action, func, mode in self.terrain_display_actions:
                self.terrain_menu.removeAction(action)
            self.terrain_display_actions = []
        except:
            traceback.print_exc()

    def make_toggle_function(self, objtype):
        def toggle(toggled):
            print("i was pressed")
            my_type = copy(objtype)
            self.types_visible[my_type] = toggled
            self.bw_map_screen.set_visibility(self.types_visible)
            self.bw_map_screen.update()
        return toggle

    def setup_visibility_toggles(self):
        for objtype in sorted(self.level.objtypes_with_positions):

            toggle = self.make_toggle_function(objtype)


            toggle_action = QAction(copy(objtype), self)
            toggle_action.setCheckable(True)
            toggle_action.setChecked(True)
            toggle_action.triggered.connect(toggle)
            self.types_visible[objtype] = True

            self.visibility_menu.addAction(toggle_action)
            self.visibility_actions.append((toggle_action, toggle))

        toggle_all = QAction("Toggle All", self)
        toggle_all.triggered.connect(self.toggle_visiblity_all)

        self.visibility_menu.addAction(toggle_all)
        self.visibility_actions.append((toggle_all, self.toggle_visiblity_all))

    def toggle_visiblity_all(self):
        for action, func in self.visibility_actions:
            if action.isCheckable():
                objtype = action.text()
                toggle = self.types_visible[objtype]
                self.types_visible[objtype] = not toggle
                action.setChecked(not toggle)
                self.bw_map_screen.set_visibility(self.types_visible)
        self.bw_map_screen.update()

    def clear_visibility_toggles(self):
        try:
            for action, func in self.visibility_actions:
                self.visibility_menu.removeAction(action)
            self.visibility_actions = []
            self.types_visible = {}
        except:
            traceback.print_exc()

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        self.button_clone_entity.setText(_translate("MainWindow", "Clone Entity"))
        self.button_remove_entity.setText(_translate("MainWindow", "Delete Entity"))
        self.button_move_entity.setText(_translate("MainWindow", "Move Entity"))
        self.button_zoom_in.setText(_translate("MainWindow", "Zoom In"))
        self.button_zoom_out.setText(_translate("MainWindow", "Zoom Out"))
        self.button_show_passengers.setText(_translate("MainWindow", "Show Passengers"))
        self.button_edit_xml.setText("Edit Object XML")
        self.button_edit_base_xml.setText("Edit Base Object XML")

        self.label_model_name.setText(_translate("MainWindow", "TextLabel1"))
        self.label_object_id.setText(_translate("MainWindow", "TextLabel2"))
        self.label_position.setText(_translate("MainWindow", "TextLabel3"))
        self.label_4.setText(_translate("MainWindow", "TextLabel4"))
        self.label_5.setText(_translate("MainWindow", "TextLabel5"))
        self.file_menu.setTitle(_translate("MainWindow", "File"))
        self.visibility_menu.setTitle(_translate("MainWindow", "Visibility"))
        self.terrain_menu.setTitle("Terrain")
예제 #6
0
class ImageDetailArea(QWidget):

    # signal
    imageLoaded = pyqtSignal()
    imageCleared = pyqtSignal()

    # static strings
    strings = {
        'filename': 'filename: %s (%s)',
        'size': 'size: %d x %d',
        'component': 'Components (%d in total)',
        'quantization': 'Quantization tables (%d in total)',
        'huffman': 'Huffman tables (%d for DC, %d for AC)',
        'showedComponentsInfo': [
            'dc_tbl_no',
            'ac_tbl_no',
            'quant_tbl_no',
            'h_samp_factor',
            'v_samp_factor',
            ],
    }

    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        # title
        self.lb_title = QLabel(self)
        self.lb_title.setAlignment(Qt.AlignCenter)
        self.lb_title.setObjectName("lb_title")
        self.verticalLayout.addWidget(self.lb_title)
        # filename && size
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.lb_filename = QLabel(self)
        self.lb_filename.setObjectName("lb_filename")
        self.horizontalLayout.addWidget(self.lb_filename)
        self.lb_size = QLabel(self)
        self.lb_size.setObjectName("lb_size")
        self.horizontalLayout.addWidget(self.lb_size)
        self.verticalLayout.addLayout(self.horizontalLayout)
        # image preview
        self.lb_image = ImageLabel(self)
        self.lb_image.setMinimumSize(QSize(250, 250))
        self.lb_image.setAlignment(Qt.AlignCenter)
        self.lb_image.setObjectName("lb_image")
        self.verticalLayout.addWidget(self.lb_image)
        # components
        self.lb_components = QLabel(self)
        self.lb_components.setObjectName("lb_components")
        self.verticalLayout.addWidget(self.lb_components)
        self.treeWidget_components = AdaptiveTreeWidget(self)
        self.treeWidget_components.setUniformRowHeights(True)
        self.treeWidget_components.setObjectName("treeWidget_components")
        self.treeWidget_components.setColumnCount(3)
        self.treeWidget_components.headerItem().setTextAlignment(
            0, Qt.AlignLeft | Qt.AlignVCenter
        )
        self.treeWidget_components.headerItem().setTextAlignment(
            1, Qt.AlignLeft | Qt.AlignVCenter
        )
        self.treeWidget_components.headerItem().setText(0, "ID")
        self.treeWidget_components.headerItem().setText(1, "Property")
        self.treeWidget_components.headerItem().setText(2, "Value")
        self.treeWidget_components.header().setSectionResizeMode(
            QHeaderView.ResizeToContents
        )
        self.verticalLayout.addWidget(self.treeWidget_components)
        # quant tables
        self.lb_quantTbls = QLabel(self)
        self.lb_quantTbls.setObjectName("lb_quantTbls")
        self.verticalLayout.addWidget(self.lb_quantTbls)
        self.treeWidget_quantTbls = AdaptiveTreeWidget(self)
        self.treeWidget_quantTbls.setObjectName("treeWidget_quantTbls")
        self.treeWidget_quantTbls.setColumnCount(3)
        self.treeWidget_quantTbls.headerItem().setTextAlignment(
            0, Qt.AlignLeft | Qt.AlignVCenter
        )
        self.treeWidget_quantTbls.headerItem().setTextAlignment(
            1, Qt.AlignLeft | Qt.AlignVCenter
        )
        self.treeWidget_quantTbls.headerItem().setText(0, "ID")
        self.treeWidget_quantTbls.headerItem().setText(1, "Property")
        self.treeWidget_quantTbls.headerItem().setText(2, "Value")
        self.verticalLayout.addWidget(self.treeWidget_quantTbls)
        # huffman tables
        self.lb_huffTbls = QLabel(self)
        self.lb_huffTbls.setObjectName("lb_huffTbls")
        self.verticalLayout.addWidget(self.lb_huffTbls)
        self.treeWidget_huffTbls = AdaptiveTreeWidget(self)
        self.treeWidget_huffTbls.setObjectName("treeWidget_huffTbls")
        self.treeWidget_huffTbls.setColumnCount(3)
        self.treeWidget_huffTbls.headerItem().setTextAlignment(
            0, Qt.AlignLeft | Qt.AlignVCenter
        )
        self.treeWidget_huffTbls.headerItem().setTextAlignment(
            1, Qt.AlignLeft | Qt.AlignVCenter
        )
        self.treeWidget_huffTbls.headerItem().setText(0, "ID")
        self.treeWidget_huffTbls.headerItem().setText(1, "Property")
        self.treeWidget_huffTbls.headerItem().setText(2, "Value")
        self.verticalLayout.addWidget(self.treeWidget_huffTbls)

        self.setTitle('( None )')
        self.clear()

    def setTitle(self, title):
        self.lb_title.setText(title)

    def clear(self):
        self.image = None
        self.lb_filename.setText(
            self.strings['filename'] % ('', 'NO image loaded')
        )
        self.lb_size.setText(
            self.strings['size'] % (0, 0)
        )
        self.lb_image.clear()
        self.lb_components.setText(
            self.strings['component'] % 0
        )
        self.treeWidget_components.clear()
        self.lb_quantTbls.setText(
            self.strings['quantization'] % 0
        )
        self.treeWidget_quantTbls.clear()
        self.lb_huffTbls.setText(
            self.strings['huffman'] % (0, 0)
        )
        self.treeWidget_huffTbls.clear()
        self.imageCleared.emit()

    def setImage(self, image):
        self.clear()
        self.image = image
        self.lb_filename.setText(
            self.strings['filename'] % (image.filename, 'original')
        )
        self.lb_size.setText(
            self.strings['size'] % image.size
        )
        self.lb_image.setImageMemSrc(image, 300, 300)
        # components
        for comp in image.comp_infos:
            topItem = QTreeWidgetItem(
                self.treeWidget_components,
                [str(comp['component_id']), '', '']
            )
            for key in self.strings['showedComponentsInfo']:
                QTreeWidgetItem(topItem, ['', key, str(comp[key])])
        self.lb_components.setText(
            self.strings['component'] % len(image.comp_infos)
        )
        # quantization tables
        self.lb_quantTbls.setText(
            self.strings['quantization'] % len(image.quant_tbls)
        )
        for i, quant_tbl in enumerate(image.quant_tbls):
            topItem = QTreeWidgetItem(
                self.treeWidget_quantTbls,
                [str(i), '', '']
            )
            for key in quant_tbl:
                QTreeWidgetItem(topItem, ['', key, str(quant_tbl[key])])
        # huffman tables
        self.lb_huffTbls.setText(
            self.strings['huffman'] % (
                len(image.dc_huff_tbls),
                len(image.ac_huff_tbls)
            )
        )
        for i, hufftbl in enumerate(image.dc_huff_tbls):
            topItem = QTreeWidgetItem(
                self.treeWidget_huffTbls,
                [str(i), 'type', 'DC']
            )
            for key in hufftbl:
                QTreeWidgetItem(topItem, ['', key, str(hufftbl[key])])
        for i, hufftbl in enumerate(image.ac_huff_tbls):
            topItem = QTreeWidgetItem(
                self.treeWidget_huffTbls,
                [str(i), 'type', 'AC']
            )
            for key in hufftbl:
                QTreeWidgetItem(topItem, ['', key, str(hufftbl[key])])
        self.imageLoaded.emit()
예제 #7
0
class ThemeTabWidget(QTabWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("QTabWidget#tabWidget::tab-bar {alignment:center;}")
        self.setObjectName("tabWidget")
        self.setCurrentIndex(0)

        self.colorSchemePath = "/usr/share/color-schemes"

        self.createTabWidgetStyle()
        self.createTabWindowStyle()
        self.createTabColorScheme()
        self.createTabDesktopTheme()
        #self.createTabMouseCursor()
        self.createTabIconSet()


    def createTabWidgetStyle(self):
        self.tabWidgetStyle = QWidget()
        self.tabWidgetStyle.setObjectName("tabWidgetStyle")

        self.verticalLayout = QVBoxLayout(self.tabWidgetStyle)
        self.verticalLayout.setObjectName("verticalLayout")

        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.labelWidgetStyle = QLabel(self.tabWidgetStyle)
        self.labelWidgetStyle.setText(self.tr("Widget Style:"))
        self.labelWidgetStyle.setObjectName("labelWidgetStyle")
        self.horizontalLayout.addWidget(self.labelWidgetStyle)

        self.comboBoxWidgetStyle = QComboBox(self.tabWidgetStyle)
        self.comboBoxWidgetStyle.setObjectName("comboBoxWidgetStyle")
        self.comboBoxWidgetStyle.addItem(self.tr("Breeze"))
        self.comboBoxWidgetStyle.addItem(self.tr("Oxygen"))
        self.comboBoxWidgetStyle.addItem(self.tr("Fusion"))
        self.horizontalLayout.addWidget(self.comboBoxWidgetStyle)

        self.verticalLayout.addLayout(self.horizontalLayout)

        self.verticalLayout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))


        self.previewWidgetStyle = PreviewWidgetStyle(self.tabWidgetStyle)
        self.previewWidgetStyle.tabWidget.setStyle(QStyleFactory.create("Breeze"))

        self.verticalLayout.addWidget(self.previewWidgetStyle)


        self.addTab(self.tabWidgetStyle, self.tr("Widget Style"))

        self.comboBoxWidgetStyle.currentTextChanged.connect(self.previewStyle)

    def previewStyle(self, text):
        self.previewWidgetStyle.tabWidget.setStyle(QStyleFactory.create(text))

    def createTabWindowStyle(self):
        self.tabWindowStyle = QWidget()
        self.tabWindowStyle.setObjectName("tabWindowStyle")

        self.verticalLayout_6 = QVBoxLayout(self.tabWindowStyle)
        self.verticalLayout_6.setObjectName("verticalLayout_6")

        self.listWidgetWindowStyle = QListWidget(self.tabWindowStyle)
        self.listWidgetWindowStyle.setResizeMode(QListView.Adjust)
        self.listWidgetWindowStyle.setIconSize(QSize(340, 105))
        self.listWidgetWindowStyle.setViewMode(QListView.IconMode)
        self.listWidgetWindowStyle.setObjectName("listWidgetWindowStyle")

        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/data/images/breeze-window.png"))
        item.setIcon(icon)
        item.setText("Breeze")
        item.setStyleText = "org.kde.breeze"
        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon1 = QIcon()
        icon1.addPixmap(QPixmap(":/data/images/oxygen-window.png"))
        item.setIcon(icon1)
        item.setText("Oxygen")
        item.setStyleText = "org.kde.oxygen"

        self.verticalLayout_6.addWidget(self.listWidgetWindowStyle)

        self.addTab(self.tabWindowStyle, self.tr("Window Style"))

    def createTabColorScheme(self):
        self.tabColorScheme = QWidget()
        self.tabColorScheme.setObjectName("tabColorScheme")

        self.verticalLayout_2 = QVBoxLayout(self.tabColorScheme)
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.listWidgetColorScheme = QListWidget(self.tabColorScheme)
        self.listWidgetColorScheme.setObjectName("listWidgetColorScheme")
        self.verticalLayout_2.addWidget(self.listWidgetColorScheme)

        self.previewWidgetColor = PreviewWidgetColor(self.tabColorScheme)
        self.verticalLayout_2.addWidget(self.previewWidgetColor)

        self.addTab(self.tabColorScheme, self.tr("Color Scheme"))

        color_list = os.listdir(self.colorSchemePath)
        color_list.sort()

        for color in color_list:
            item = QListWidgetItem(self.listWidgetColorScheme)
            item.setText(color.split(".")[0])
            item.colorSchemeName = color


        self.listWidgetColorScheme.itemClicked.connect(self.previewColorScheme)

    def previewColorScheme(self, item):
        css = iniToCss(os.path.join(self.colorSchemePath,item.colorSchemeName))
        self.previewWidgetColor.previewGroupBox.setStyleSheet(css)

    def createTabDesktopTheme(self):
        self.tabDesktopTheme = QWidget()
        self.tabDesktopTheme.setObjectName("tabDesktopTheme")

        self.gridLayout = QGridLayout(self.tabDesktopTheme)
        self.gridLayout.setObjectName("gridLayout")

        self.listWidgetDesktopTheme = QListWidget(self.tabDesktopTheme)
        self.listWidgetDesktopTheme.setObjectName("listWidgetDesktopTheme")
        self.listWidgetDesktopTheme.setViewMode(QListView.IconMode)
        self.listWidgetDesktopTheme.setIconSize(QSize(660, 70))
        self.gridLayout.addWidget(self.listWidgetDesktopTheme, 0, 0, 1, 1)

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        icon = QIcon(QPixmap(":/data/images/air-panel.png").scaled(QSize(660, 70), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(660, 70))
        item.setIcon(icon)
        item.panelText = "air"

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/breeze-panel.png").scaled(QSize(660, 70), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(660, 70))
        item.setIcon(icon)
        item.panelText = "default"

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/breeze-dark-panel.png").scaled(QSize(660, 70), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(660, 70))
        item.setIcon(icon)
        item.panelText = "breeze-dark"

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/oxygen-panel.png").scaled(QSize(660, 70), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(660, 70))
        item.setIcon(icon)
        item.panelText = "oxygen"

        self.addTab(self.tabDesktopTheme, self.tr("Desktop Theme"))

    """def createTabMouseCursor(self):
        self.tabMouseCursor = QWidget()
        self.tabMouseCursor.setObjectName("tabMouseCursor")

        self.verticalLayout_4 = QVBoxLayout(self.tabMouseCursor)
        self.verticalLayout_4.setObjectName("verticalLayout_4")

        self.listWidgetMouseCursor = QListWidget(self.tabMouseCursor)
        self.listWidgetMouseCursor.setObjectName("listWidgetMouseCursor")

        self.verticalLayout_4.addWidget(self.listWidgetMouseCursor)
        self.addTab(self.tabMouseCursor, self.tr("Mouse Cursor"))"""

    def createTabIconSet(self):
        self.tabIconSet = QWidget()
        self.tabIconSet.setObjectName("tabIconSet")

        self.verticalLayout_3 = QVBoxLayout(self.tabIconSet)
        self.verticalLayout_3.setObjectName("verticalLayout_3")

        self.listWidgetIconSet = QListWidget(self.tabIconSet)
        self.listWidgetIconSet.setResizeMode(QListView.Adjust)
        self.listWidgetIconSet.setObjectName("listWidgetIconSet")
        self.listWidgetIconSet.setViewMode(QListView.IconMode)
        self.listWidgetIconSet.setIconSize(QSize(370, 64))

        item = QListWidgetItem(self.listWidgetIconSet)
        item.setIcon(QIcon(":/data/images/oxygen-set.png"))
        item.setText("Oxygen")

        item = QListWidgetItem(self.listWidgetIconSet)
        item.setIcon(QIcon(":/data/images/breeze-set.png"))
        item.setText("Breeze")

        self.verticalLayout_3.addWidget(self.listWidgetIconSet)

        self.addTab(self.tabIconSet, self.tr("Icon Set"))
예제 #8
0
파일: tabwidget.py 프로젝트: KaOSx/kaptan
class ThemeTabWidget(QTabWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("QTabWidget#tabWidget::tab-bar {alignment:center;}")
        self.setObjectName("tabWidget")
        self.setCurrentIndex(0)

        self.colorSchemePath = "/usr/share/color-schemes"

        self.createTabWidgetStyle()
        self.createTabWindowStyle()
        self.createTabColorScheme()
        self.createTabDesktopTheme()
        #self.createTabMouseCursor()
        self.createTabIconSet()


    def createTabWidgetStyle(self):
        self.tabWidgetStyle = QWidget()
        self.tabWidgetStyle.setObjectName("tabWidgetStyle")

        self.verticalLayout = QVBoxLayout(self.tabWidgetStyle)
        self.verticalLayout.setObjectName("verticalLayout")

        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.labelWidgetStyle = QLabel(self.tabWidgetStyle)
        self.labelWidgetStyle.setText(self.tr("Widget Style:"))
        self.labelWidgetStyle.setObjectName("labelWidgetStyle")
        self.horizontalLayout.addWidget(self.labelWidgetStyle)

        self.comboBoxWidgetStyle = QComboBox(self.tabWidgetStyle)
        self.comboBoxWidgetStyle.setObjectName("comboBoxWidgetStyle")
        self.comboBoxWidgetStyle.addItem(self.tr("QtCurve"))
        self.comboBoxWidgetStyle.addItem(self.tr("Breeze"))
        self.comboBoxWidgetStyle.addItem(self.tr("Oxygen"))
        self.comboBoxWidgetStyle.addItem(self.tr("Fusion"))
        self.horizontalLayout.addWidget(self.comboBoxWidgetStyle)

        self.verticalLayout.addLayout(self.horizontalLayout)

        self.verticalLayout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))


        self.previewWidgetStyle = PreviewWidgetStyle(self.tabWidgetStyle)
        self.previewWidgetStyle.tabWidget.setStyle(QStyleFactory.create("QtCurve"))

        self.verticalLayout.addWidget(self.previewWidgetStyle)


        self.addTab(self.tabWidgetStyle, self.tr("Widget Style"))

        self.comboBoxWidgetStyle.currentTextChanged.connect(self.previewStyle)

    def previewStyle(self, text):
        self.previewWidgetStyle.tabWidget.setStyle(QStyleFactory.create(text))

    def createTabWindowStyle(self):
        self.tabWindowStyle = QWidget()
        self.tabWindowStyle.setObjectName("tabWindowStyle")

        self.verticalLayout_6 = QVBoxLayout(self.tabWindowStyle)
        self.verticalLayout_6.setObjectName("verticalLayout_6")

        self.listWidgetWindowStyle = QListWidget(self.tabWindowStyle)
        self.listWidgetWindowStyle.setResizeMode(QListView.Adjust)
        self.listWidgetWindowStyle.setIconSize(QSize(700, 147))
        self.listWidgetWindowStyle.setViewMode(QListView.IconMode)
        self.listWidgetWindowStyle.setObjectName("listWidgetWindowStyle")

        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/data/images/breeze_deco.png"))
        item.setIcon(icon)
        item.setText("Breeze")
        item.setStyleText = "org.kde.breeze"
        item.themeText = ""
        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/data/images/midna-flat_deco.png"))
        item.setIcon(icon)
        item.setText("Midna Flat")
        item.setStyleText = "org.kde.kwin.aurorae"
        item.themeText = "__aurorae__svg__MidnaFlatNarrow"
        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/data/images/midna-dark_deco.png"))
        item.setIcon(icon)
        item.setText("Midna Dark")
        item.setStyleText = "org.kde.kwin.aurorae"
        item.themeText = "__aurorae__svg__MidnaDark"
        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon = QIcon()
        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/data/images/midna-grey_deco.png"))
        item.setIcon(icon)
        item.setText("Midna Gray")
        item.setStyleText = "org.kde.kwin.aurorae"
        item.themeText = "__aurorae__svg__MidnaFlatWideGray"
        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/data/images/midna-wide_deco.png"))
        item.setIcon(icon)
        item.setText("Midna Wide")
        item.setStyleText = "org.kde.kwin.aurorae"
        item.themeText = "__aurorae__svg__MidnaFlatWideBlue"
        item = QListWidgetItem(self.listWidgetWindowStyle)
        icon1 = QIcon()
        icon1.addPixmap(QPixmap(":/data/images/oxygen_deco.png"))
        item.setIcon(icon1)
        item.setText("Oxygen")
        item.setStyleText = "org.kde.oxygen"
        item.themeText = ""

        self.verticalLayout_6.addWidget(self.listWidgetWindowStyle)

        self.addTab(self.tabWindowStyle, self.tr("Window Style"))

    def createTabColorScheme(self):
        self.tabColorScheme = QWidget()
        self.tabColorScheme.setObjectName("tabColorScheme")

        self.verticalLayout_2 = QVBoxLayout(self.tabColorScheme)
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.listWidgetColorScheme = QListWidget(self.tabColorScheme)
        self.listWidgetColorScheme.setObjectName("listWidgetColorScheme")
        self.verticalLayout_2.addWidget(self.listWidgetColorScheme)

        color_list = os.listdir(self.colorSchemePath)
        color_list.sort(key = len)

        for color in color_list:
            item = QListWidgetItem(self.listWidgetColorScheme)
            item.setText(color.split(".")[0])
            item.colorSchemeName = color

        self.listWidgetColorScheme.itemClicked.connect(self.previewColorScheme)
        self.listWidgetColorScheme.setCurrentRow(0)

        self.previewWidgetColor = PreviewWidgetColor(self.tabColorScheme)
        self.verticalLayout_2.addWidget(self.previewWidgetColor)

        self.addTab(self.tabColorScheme, self.tr("Color Scheme"))

    def previewColorScheme(self, item):
        css = iniToCss(os.path.join(self.colorSchemePath, item.colorSchemeName))
        self.previewWidgetColor.previewGroupBox.setStyleSheet(css[0])
        self.previewWidgetColor.previewTextBrowser.setHtml("""<style>#unclicked {color : rgb(%s);}
        #clicked {color : rgb(%s);}</style>"""%(css[1][0],css[1][1]) +
        self.tr("""<p>Normal text <a id='unclicked' href='#'>link</a> <a id='clicked' href='#'>visited</a></p>"""))

    def createTabDesktopTheme(self):
        self.tabDesktopTheme = QWidget()
        self.tabDesktopTheme.setObjectName("tabDesktopTheme")
        
        self.verticalLayout_4 = QVBoxLayout(self.tabDesktopTheme)
        self.verticalLayout_4.setObjectName("verticalLayout_4")

        self.listWidgetDesktopTheme = QListWidget(self.tabDesktopTheme)
        self.listWidgetDesktopTheme.setObjectName("listWidgetDesktopTheme")
        self.listWidgetDesktopTheme.setViewMode(QListView.IconMode)
        self.listWidgetDesktopTheme.setIconSize(QSize(240, 145))
        self.listWidgetDesktopTheme.setResizeMode(QListView.Adjust)

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        icon = QIcon(QPixmap(":/data/images/air_panel.png").scaled(QSize(240, 145), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(240, 145))
        item.setIcon(icon)
        item.panelText = "air"

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/breeze_panel.png").scaled(QSize(240, 145), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(240, 145))
        item.setIcon(icon)
        item.panelText = "default"

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/breeze-dark_panel.png").scaled(QSize(240, 145), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(240, 145))
        item.setIcon(icon)
        item.panelText = "breeze-dark"

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/midna_panel.png").scaled(QSize(240, 145), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(240, 145))
        item.setIcon(icon)
        item.panelText = "midna"
        
        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/midna-dark_panel.png").scaled(QSize(240, 145), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(240, 145))
        item.setIcon(icon)
        item.panelText = "midna_dark"

        item = QListWidgetItem(self.listWidgetDesktopTheme)
        item.setTextAlignment(Qt.AlignHCenter)
        icon = QIcon(QPixmap(":/data/images/oxygen_panel.png").scaled(QSize(240, 145), Qt.IgnoreAspectRatio, Qt.FastTransformation))
        item.setSizeHint(QSize(240, 145))
        item.setIcon(icon)
        item.panelText = "oxygen"
        
        self.verticalLayout_4.addWidget(self.listWidgetDesktopTheme)

        self.addTab(self.tabDesktopTheme, self.tr("Desktop Theme"))

    def createTabIconSet(self):
        self.tabIconSet = QWidget()
        self.tabIconSet.setObjectName("tabIconSet")

        self.verticalLayout_3 = QVBoxLayout(self.tabIconSet)
        self.verticalLayout_3.setObjectName("verticalLayout_3")

        self.listWidgetIconSet = QListWidget(self.tabIconSet)
        self.listWidgetIconSet.setResizeMode(QListView.Adjust)
        self.listWidgetIconSet.setObjectName("listWidgetIconSet")
        self.listWidgetIconSet.setViewMode(QListView.IconMode)
        self.listWidgetIconSet.setIconSize(QSize(370, 64))
        
        item = QListWidgetItem(self.listWidgetIconSet)
        item.setIcon(QIcon(":/data/images/midna-set.png"))
        item.setText("Midna")
        
        item = QListWidgetItem(self.listWidgetIconSet)
        item.setIcon(QIcon(":/data/images/midna-dark-set.png"))
        item.setText("MidnaDark")
        
        item = QListWidgetItem(self.listWidgetIconSet)
        item.setIcon(QIcon(":/data/images/breeze-set.png"))
        item.setText("Breeze")

        item = QListWidgetItem(self.listWidgetIconSet)
        item.setIcon(QIcon(":/data/images/oxygen-set.png"))
        item.setText("Oxygen")

        self.verticalLayout_3.addWidget(self.listWidgetIconSet)

        self.addTab(self.tabIconSet, self.tr("Icon Set"))
class PikminSideWidget(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        parent = args[0]

        self.parent = parent
        self.setMaximumSize(QSize(700, 1500))
        self.setMinimumWidth(300)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setAlignment(Qt.AlignTop)

        font = QFont()
        font.setFamily("Consolas")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(9)

        self.verticalLayout.setObjectName("verticalLayout")

        self.button_add_object = QPushButton(parent)

        self.button_remove_object = QPushButton(parent)
        self.button_ground_object = QPushButton(parent)
        #self.button_move_object = QPushButton(parent)
        #self.button_edit_object = QPushButton(parent)

        #self.button_add_object.setDisabled(True)
        #self.button_remove_object.setDisabled(True)

        self.button_add_object.setText("Add Object")
        self.button_remove_object.setText("Remove Object(s)")
        self.button_ground_object.setText("Ground Object(s)")

        self.button_add_object.setToolTip("Hotkey: Ctrl+A")
        self.button_remove_object.setToolTip("Hotkey: Delete")
        self.button_ground_object.setToolTip("Hotkey: G")


        self.button_add_object.setCheckable(True)
        #self.button_move_object.setCheckable(True)

        #self.lineedit_coordinatex = QLineEdit(parent)
        #self.lineedit_coordinatey = QLineEdit(parent)
        #self.lineedit_coordinatez = QLineEdit(parent)
        #self.verticalLayout.addStretch(10)
        #self.lineedit_rotationx = QLineEdit(parent)
        #self.lineedit_rotationy = QLineEdit(parent)
        #self.lineedit_rotationz = QLineEdit(parent)
        self.verticalLayout.addWidget(self.button_add_object)
        self.verticalLayout.addWidget(self.button_remove_object)
        self.verticalLayout.addWidget(self.button_ground_object)
        #self.verticalLayout.addWidget(self.button_move_object)
        self.verticalLayout.addStretch(20)

        self.name_label = QLabel(parent)
        self.name_label.setFont(font)
        self.name_label.setWordWrap(True)
        self.name_label.setMinimumSize(self.name_label.width(), 30)
        #self.identifier_label = QLabel(parent)
        #self.identifier_label.setFont(font)
        #self.identifier_label.setMinimumSize(self.name_label.width(), 50)
        #self.identifier_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.verticalLayout.addWidget(self.name_label)
        #self.verticalLayout.addWidget(self.identifier_label)

        """self.verticalLayout.addWidget(self.lineedit_coordinatex)
        self.verticalLayout.addWidget(self.lineedit_coordinatey)
        self.verticalLayout.addWidget(self.lineedit_coordinatez)

        self.verticalLayout.addLayout(self._make_labeled_lineedit(self.lineedit_coordinatex, "X:   "))
        self.verticalLayout.addLayout(self._make_labeled_lineedit(self.lineedit_coordinatey, "Y:   "))
        self.verticalLayout.addLayout(self._make_labeled_lineedit(self.lineedit_coordinatez, "Z:   "))
        self.verticalLayout.addStretch(10)
        self.verticalLayout.addLayout(self._make_labeled_lineedit(self.lineedit_rotationx, "RotX:"))
        self.verticalLayout.addLayout(self._make_labeled_lineedit(self.lineedit_rotationy, "RotY:"))
        self.verticalLayout.addLayout(self._make_labeled_lineedit(self.lineedit_rotationz, "RotZ:"))"""
        #self.verticalLayout.addStretch(10)
        self.comment_label = QLabel(parent)
        self.comment_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.comment_label.setWordWrap(True)
        self.comment_label.setFont(font)
        self.verticalLayout.addWidget(self.comment_label)
        #self.verticalLayout.addStretch(500)

        self.objectlist = []

        self.object_data_edit = None

        self.reset_info()

    def _make_labeled_lineedit(self, lineedit, label):
        font = QFont()
        font.setFamily("Consolas")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)

        layout = QHBoxLayout()
        label = QLabel(label, self)
        label.setFont(font)
        layout.addWidget(label)
        layout.addWidget(lineedit)
        return layout

    def reset_info(self, info="None selected"):
        self.name_label.setText(info)
        #self.identifier_label.setText("")
        self.comment_label.setText("")

        if self.object_data_edit is not None:
            self.object_data_edit.deleteLater()
            del self.object_data_edit
            self.object_data_edit = None

        self.objectlist = []

    def update_info(self):
        if self.object_data_edit is not None:
            self.object_data_edit.update_data()

    def set_info(self, obj, update3d, usedby=[]):
        if usedby:
            self.name_label.setText("Selected: {}\nUsed by: {}".format(type(obj).__name__,
                                    ", ".join(usedby)))
        else:
            self.name_label.setText("Selected: {}".format(type(obj).__name__))
        #self.identifier_label.setText(obj.get_identifier())
        if self.object_data_edit is not None:
            #self.verticalLayout.removeWidget(self.object_data_edit)
            self.object_data_edit.deleteLater()
            del self.object_data_edit
            self.object_data_edit = None
            print("should be removed")

        editor = choose_data_editor(obj)
        if editor is not None:

            self.object_data_edit = editor(self, obj)
            self.verticalLayout.addWidget(self.object_data_edit)
            self.object_data_edit.emit_3d_update.connect(update3d)

        self.objectlist = []
        self.comment_label.setText("")

    def set_objectlist(self, objs):
        self.objectlist = []
        objectnames = []

        for obj in objs:
            if len(objectnames) < 25:
                objectnames.append(obj.name)
            self.objectlist.append(obj)

        objectnames.sort()
        if len(objs) > 0:
            text = "Selected objects:\n" + (", ".join(objectnames))
            diff = len(objs) - len(objectnames)
            if diff == 1:
                text += "\nAnd {0} more object".format(diff)
            elif diff > 1:
                text += "\nAnd {0} more objects".format(diff)

        else:
            text = ""

        self.comment_label.setText(text)
예제 #10
0
class Setting_Ui(QWidget):
    def __init__(self, persepolis_setting):
        super().__init__()
        icon = QtGui.QIcon()

        # add support for other languages
        locale = str(persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        self.setWindowIcon(
            QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg')))
        self.setWindowTitle(
            QCoreApplication.translate("setting_ui_tr", 'Preferences'))

        # set ui direction
        ui_direction = persepolis_setting.value('ui_direction')

        if ui_direction == 'rtl':
            self.setLayoutDirection(Qt.RightToLeft)

        elif ui_direction in 'ltr':
            self.setLayoutDirection(Qt.LeftToRight)

        global icons
        icons = ':/' + str(persepolis_setting.value('settings/icons')) + '/'

        self.verticalLayout_2 = QVBoxLayout(self)
        self.setting_tabWidget = QTabWidget(self)
        # download_options_tab
        self.download_options_tab = QWidget()
        self.layoutWidget = QWidget(self.download_options_tab)
        self.download_options_verticalLayout = QVBoxLayout(self.layoutWidget)
        self.download_options_verticalLayout.setContentsMargins(21, 21, 0, 0)
        self.download_options_verticalLayout.setObjectName(
            "download_options_verticalLayout")
        self.horizontalLayout_5 = QHBoxLayout()
        # tries_label
        self.tries_label = QLabel(self.layoutWidget)
        self.horizontalLayout_5.addWidget(self.tries_label)
        # tries_spinBox
        self.tries_spinBox = QSpinBox(self.layoutWidget)
        self.tries_spinBox.setMinimum(1)

        self.horizontalLayout_5.addWidget(self.tries_spinBox)
        self.download_options_verticalLayout.addLayout(self.horizontalLayout_5)
        self.horizontalLayout_4 = QHBoxLayout()
        # wait_label
        self.wait_label = QLabel(self.layoutWidget)
        self.horizontalLayout_4.addWidget(self.wait_label)
        # wait_spinBox
        self.wait_spinBox = QSpinBox(self.layoutWidget)
        self.horizontalLayout_4.addWidget(self.wait_spinBox)

        self.download_options_verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_3 = QHBoxLayout()
        # time_out_label
        self.time_out_label = QLabel(self.layoutWidget)
        self.horizontalLayout_3.addWidget(self.time_out_label)
        # time_out_spinBox
        self.time_out_spinBox = QSpinBox(self.layoutWidget)
        self.horizontalLayout_3.addWidget(self.time_out_spinBox)

        self.download_options_verticalLayout.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_2 = QHBoxLayout()
        # connections_label
        self.connections_label = QLabel(self.layoutWidget)
        self.horizontalLayout_2.addWidget(self.connections_label)
        # connections_spinBox
        self.connections_spinBox = QSpinBox(self.layoutWidget)
        self.connections_spinBox.setMinimum(1)
        self.connections_spinBox.setMaximum(16)
        self.horizontalLayout_2.addWidget(self.connections_spinBox)

        self.download_options_verticalLayout.addLayout(self.horizontalLayout_2)
        # rpc_port_label
        self.rpc_port_label = QLabel(self.layoutWidget)
        self.rpc_horizontalLayout = QHBoxLayout()
        self.rpc_horizontalLayout.addWidget(self.rpc_port_label)
        # rpc_port_spinbox
        self.rpc_port_spinbox = QSpinBox(self.layoutWidget)
        self.rpc_port_spinbox.setMinimum(1024)
        self.rpc_port_spinbox.setMaximum(65535)
        self.rpc_horizontalLayout.addWidget(self.rpc_port_spinbox)

        self.download_options_verticalLayout.addLayout(
            self.rpc_horizontalLayout)

        # wait_queue
        wait_queue_horizontalLayout = QHBoxLayout()

        self.wait_queue_label = QLabel(self.layoutWidget)
        wait_queue_horizontalLayout.addWidget(self.wait_queue_label)

        self.wait_queue_time = QDateTimeEdit(self.layoutWidget)
        self.wait_queue_time.setDisplayFormat('H:mm')
        wait_queue_horizontalLayout.addWidget(self.wait_queue_time)

        self.download_options_verticalLayout.addLayout(
            wait_queue_horizontalLayout)

        # change aria2 path
        aria2_path_verticalLayout = QVBoxLayout()

        self.aria2_path_checkBox = QCheckBox(self.layoutWidget)
        aria2_path_verticalLayout.addWidget(self.aria2_path_checkBox)

        aria2_path_horizontalLayout = QHBoxLayout()

        self.aria2_path_lineEdit = QLineEdit(self.layoutWidget)
        aria2_path_horizontalLayout.addWidget(self.aria2_path_lineEdit)

        self.aria2_path_pushButton = QPushButton(self.layoutWidget)
        aria2_path_horizontalLayout.addWidget(self.aria2_path_pushButton)

        aria2_path_verticalLayout.addLayout(aria2_path_horizontalLayout)

        self.download_options_verticalLayout.addLayout(
            aria2_path_verticalLayout)

        self.setting_tabWidget.addTab(self.download_options_tab, "")
        # save_as_tab
        self.save_as_tab = QWidget()

        self.layoutWidget1 = QWidget(self.save_as_tab)

        self.save_as_verticalLayout = QVBoxLayout(self.layoutWidget1)
        self.save_as_verticalLayout.setContentsMargins(20, 30, 0, 0)

        self.download_folder_horizontalLayout = QHBoxLayout()
        # download_folder_label
        self.download_folder_label = QLabel(self.layoutWidget1)
        self.download_folder_horizontalLayout.addWidget(
            self.download_folder_label)
        # download_folder_lineEdit
        self.download_folder_lineEdit = QLineEdit(self.layoutWidget1)
        self.download_folder_horizontalLayout.addWidget(
            self.download_folder_lineEdit)
        # download_folder_pushButton
        self.download_folder_pushButton = QPushButton(self.layoutWidget1)
        self.download_folder_horizontalLayout.addWidget(
            self.download_folder_pushButton)

        self.save_as_verticalLayout.addLayout(
            self.download_folder_horizontalLayout)
        self.temp_horizontalLayout = QHBoxLayout()
        # temp_download_label
        self.temp_download_label = QLabel(self.layoutWidget1)
        self.temp_horizontalLayout.addWidget(self.temp_download_label)
        # temp_download_lineEdit
        self.temp_download_lineEdit = QLineEdit(self.layoutWidget1)
        self.temp_horizontalLayout.addWidget(self.temp_download_lineEdit)
        # temp_download_pushButton
        self.temp_download_pushButton = QPushButton(self.layoutWidget1)
        self.temp_horizontalLayout.addWidget(self.temp_download_pushButton)

        self.save_as_verticalLayout.addLayout(self.temp_horizontalLayout)

        # create subfolder checkBox
        self.subfolder_checkBox = QCheckBox(self.layoutWidget1)
        self.save_as_verticalLayout.addWidget(self.subfolder_checkBox)

        self.setting_tabWidget.addTab(self.save_as_tab, "")
        # notifications_tab
        self.notifications_tab = QWidget()
        self.layoutWidget2 = QWidget(self.notifications_tab)
        self.verticalLayout_4 = QVBoxLayout(self.layoutWidget2)
        self.verticalLayout_4.setContentsMargins(21, 21, 0, 0)
        # enable_notifications_checkBox
        self.enable_notifications_checkBox = QCheckBox(self.layoutWidget2)
        self.verticalLayout_4.addWidget(self.enable_notifications_checkBox)
        # sound_frame
        self.sound_frame = QFrame(self.layoutWidget2)
        self.sound_frame.setFrameShape(QFrame.StyledPanel)
        self.sound_frame.setFrameShadow(QFrame.Raised)

        self.verticalLayout = QVBoxLayout(self.sound_frame)
        # volume_label
        self.volume_label = QLabel(self.sound_frame)
        self.verticalLayout.addWidget(self.volume_label)
        # volume_dial
        self.volume_dial = QDial(self.sound_frame)
        self.volume_dial.setProperty("value", 100)
        self.verticalLayout.addWidget(self.volume_dial)

        self.verticalLayout_4.addWidget(self.sound_frame)
        self.setting_tabWidget.addTab(self.notifications_tab, "")
        # style_tab
        self.style_tab = QWidget()
        self.layoutWidget3 = QWidget(self.style_tab)
        self.verticalLayout_3 = QVBoxLayout(self.layoutWidget3)
        self.verticalLayout_3.setContentsMargins(21, 21, 0, 0)
        self.horizontalLayout_8 = QHBoxLayout()
        # style_label
        self.style_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_8.addWidget(self.style_label)
        # style_comboBox
        self.style_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_8.addWidget(self.style_comboBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_8)
        self.horizontalLayout_7 = QHBoxLayout()
        # language_combox
        self.lang_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_7.addWidget(self.lang_label)
        self.lang_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_7.addWidget(self.lang_comboBox)

        # language_label
        self.verticalLayout_3.addLayout(self.horizontalLayout_7)
        self.horizontalLayout_7 = QHBoxLayout()
        self.lang_label.setText(
            QCoreApplication.translate("setting_ui_tr", "language :"))
        # color_label
        self.color_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_7.addWidget(self.color_label)
        # color_comboBox
        self.color_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_7.addWidget(self.color_comboBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_7)
        # icon_label
        self.horizontalLayout_12 = QHBoxLayout()
        self.icon_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_12.addWidget(self.icon_label)

        # icon_comboBox
        self.icon_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_12.addWidget(self.icon_comboBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_12)

        # icons_size_comboBox
        self.icons_size_horizontalLayout = QHBoxLayout()
        self.icons_size_label = QLabel(self.layoutWidget3)
        self.icons_size_horizontalLayout.addWidget(self.icons_size_label)

        self.icons_size_comboBox = QComboBox(self.layoutWidget3)
        self.icons_size_horizontalLayout.addWidget(self.icons_size_comboBox)

        self.verticalLayout_3.addLayout(self.icons_size_horizontalLayout)

        self.horizontalLayout_6 = QHBoxLayout()
        # notification_label
        self.horizontalLayout_13 = QHBoxLayout()
        self.notification_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_13.addWidget(self.notification_label)
        # notification_comboBox
        self.notification_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_13.addWidget(self.notification_comboBox)
        self.verticalLayout_3.addLayout(self.horizontalLayout_13)
        # font_checkBox
        self.font_checkBox = QCheckBox(self.layoutWidget3)
        self.horizontalLayout_6.addWidget(self.font_checkBox)
        # fontComboBox
        self.fontComboBox = QFontComboBox(self.layoutWidget3)
        self.horizontalLayout_6.addWidget(self.fontComboBox)
        # font_size_label
        self.font_size_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_6.addWidget(self.font_size_label)
        # font_size_spinBox
        self.font_size_spinBox = QSpinBox(self.layoutWidget3)
        self.font_size_spinBox.setMinimum(1)
        self.horizontalLayout_6.addWidget(self.font_size_spinBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
        self.setting_tabWidget.addTab(self.style_tab, "")
        self.verticalLayout_2.addWidget(self.setting_tabWidget)
        self.horizontalLayout = QHBoxLayout()
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        # Enable system tray icon
        self.enable_system_tray_checkBox = QCheckBox(self.layoutWidget3)
        self.verticalLayout_3.addWidget(self.enable_system_tray_checkBox)
        # after_download dialog
        self.after_download_checkBox = QCheckBox()
        self.verticalLayout_3.addWidget(self.after_download_checkBox)

        # show_menubar_checkbox
        self.show_menubar_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.show_menubar_checkbox)

        # show_sidepanel_checkbox
        self.show_sidepanel_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.show_sidepanel_checkbox)

        # hide progress window
        self.show_progress_window_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.show_progress_window_checkbox)

        # add persepolis to startup
        self.startup_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.startup_checkbox)

        # keep system awake
        self.keep_awake_checkBox = QCheckBox()
        self.verticalLayout_3.addWidget(self.keep_awake_checkBox)

        # columns_tab
        self.columns_tab = QWidget()
        layoutWidget4 = QWidget(self.columns_tab)

        column_verticalLayout = QVBoxLayout(layoutWidget4)
        column_verticalLayout.setContentsMargins(21, 21, 0, 0)

        # creating checkBox for columns
        self.show_column_label = QLabel()
        self.column0_checkBox = QCheckBox()
        self.column1_checkBox = QCheckBox()
        self.column2_checkBox = QCheckBox()
        self.column3_checkBox = QCheckBox()
        self.column4_checkBox = QCheckBox()
        self.column5_checkBox = QCheckBox()
        self.column6_checkBox = QCheckBox()
        self.column7_checkBox = QCheckBox()
        self.column10_checkBox = QCheckBox()
        self.column11_checkBox = QCheckBox()
        self.column12_checkBox = QCheckBox()

        column_verticalLayout.addWidget(self.show_column_label)
        column_verticalLayout.addWidget(self.column0_checkBox)
        column_verticalLayout.addWidget(self.column1_checkBox)
        column_verticalLayout.addWidget(self.column2_checkBox)
        column_verticalLayout.addWidget(self.column3_checkBox)
        column_verticalLayout.addWidget(self.column4_checkBox)
        column_verticalLayout.addWidget(self.column5_checkBox)
        column_verticalLayout.addWidget(self.column6_checkBox)
        column_verticalLayout.addWidget(self.column7_checkBox)
        column_verticalLayout.addWidget(self.column10_checkBox)
        column_verticalLayout.addWidget(self.column11_checkBox)
        column_verticalLayout.addWidget(self.column12_checkBox)

        self.setting_tabWidget.addTab(self.columns_tab, '')

        # youtube_tab
        self.youtube_tab = QWidget()
        self.layoutWidgetYTD = QWidget(self.youtube_tab)
        self.youtube_layout = QVBoxLayout(self.layoutWidgetYTD)
        self.youtube_layout.setContentsMargins(20, 30, 0, 0)

        self.youtube_verticalLayout = QVBoxLayout()

        # Whether to enable video link capturing.
        self.enable_ytd_checkbox = QCheckBox(self.layoutWidgetYTD)
        self.youtube_layout.addWidget(self.enable_ytd_checkbox)

        # If we should hide videos with no audio
        self.hide_no_audio_checkbox = QCheckBox(self.layoutWidgetYTD)
        self.youtube_verticalLayout.addWidget(self.hide_no_audio_checkbox)

        # If we should hide audios without video
        self.hide_no_video_checkbox = QCheckBox(self.layoutWidgetYTD)
        self.youtube_verticalLayout.addWidget(self.hide_no_video_checkbox)

        self.max_links_horizontalLayout = QHBoxLayout()

        # max_links_label
        self.max_links_label = QLabel(self.layoutWidgetYTD)

        self.max_links_horizontalLayout.addWidget(self.max_links_label)
        # max_links_spinBox
        self.max_links_spinBox = QSpinBox(self.layoutWidgetYTD)
        self.max_links_spinBox.setMinimum(1)
        self.max_links_spinBox.setMaximum(16)
        self.max_links_horizontalLayout.addWidget(self.max_links_spinBox)
        self.youtube_verticalLayout.addLayout(self.max_links_horizontalLayout)

        self.youtube_dl_path_horizontalLayout = QHBoxLayout()

        self.youtube_frame = QFrame(self.youtube_tab)
        self.youtube_frame.setLayout(self.youtube_verticalLayout)

        self.youtube_layout.addWidget(self.youtube_frame)

        self.setting_tabWidget.addTab(self.youtube_tab, "")

        # defaults_pushButton
        self.defaults_pushButton = QPushButton(self)
        self.horizontalLayout.addWidget(self.defaults_pushButton)
        # cancel_pushButton
        self.cancel_pushButton = QPushButton(self)
        self.cancel_pushButton.setIcon(QIcon(icons + 'remove'))
        self.horizontalLayout.addWidget(self.cancel_pushButton)
        # ok_pushButton
        self.ok_pushButton = QPushButton(self)
        self.ok_pushButton.setIcon(QIcon(icons + 'ok'))
        self.horizontalLayout.addWidget(self.ok_pushButton)

        self.verticalLayout_2.addLayout(self.horizontalLayout)
        self.setting_tabWidget.setCurrentIndex(3)

        self.setWindowTitle(
            QCoreApplication.translate("setting_ui_tr", "Preferences"))

        self.tries_label.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Set number of tries if download failed.</p></body></html>"
            ))
        self.tries_label.setText(
            QCoreApplication.translate("setting_ui_tr", "Number of tries : "))
        self.tries_spinBox.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Set number of tries if download failed.</p></body></html>"
            ))

        self.wait_label.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Set the seconds to wait between retries. Download manager will  retry  downloads  when  the  HTTP  server  returns  a  503 response.</p></body></html>"
            ))
        self.wait_label.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Wait between retries (seconds) : "))
        self.wait_spinBox.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Set the seconds to wait between retries. Download manager will  retry  downloads  when  the  HTTP  server  returns  a  503 response.</p></body></html>"
            ))

        self.time_out_label.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Set timeout in seconds. </p></body></html>"
            ))
        self.time_out_label.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Time out (seconds) : "))
        self.time_out_spinBox.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Set timeout in seconds. </p></body></html>"
            ))

        self.connections_label.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>"
            ))
        self.connections_label.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Number of connections : "))
        self.connections_spinBox.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>"
            ))

        self.rpc_port_label.setText(
            QCoreApplication.translate("setting_ui_tr", "RPC port number : "))
        self.rpc_port_spinbox.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p> Specify a port number for JSON-RPC/XML-RPC server to listen to. Possible Values: 1024 - 65535 Default: 6801 </p></body></html>"
            ))

        self.wait_queue_label.setText(
            QCoreApplication.translate(
                "setting_ui_tr", 'Wait between every downloads in queue:'))

        self.aria2_path_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       'Change aria2 default path'))
        self.aria2_path_pushButton.setText(
            QCoreApplication.translate("setting_ui_tr", 'Change'))
        aria2_path_tooltip = QCoreApplication.translate(
            "setting_ui_tr",
            "<html><head/><body><p>Attention: Wrong path may have caused problem! Do it carefully or don't change default setting!</p></body></html>"
        )
        self.aria2_path_checkBox.setToolTip(aria2_path_tooltip)
        self.aria2_path_lineEdit.setToolTip(aria2_path_tooltip)
        self.aria2_path_pushButton.setToolTip(aria2_path_tooltip)

        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.download_options_tab),
            QCoreApplication.translate("setting_ui_tr", "Download Options"))

        self.download_folder_label.setText(
            QCoreApplication.translate("setting_ui_tr", "Download Folder : "))
        self.download_folder_pushButton.setText(
            QCoreApplication.translate("setting_ui_tr", "Change"))

        self.temp_download_label.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Temporary Download Folder : "))
        self.temp_download_pushButton.setText(
            QCoreApplication.translate("setting_ui_tr", "Change"))

        self.subfolder_checkBox.setText(
            QCoreApplication.translate(
                "setting_ui_tr",
                "Create subfolders for Music,Videos,... in default download folder"
            ))

        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.save_as_tab),
            QCoreApplication.translate("setting_ui_tr", "Save as"))

        self.enable_notifications_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Enable notification sounds"))

        self.volume_label.setText(
            QCoreApplication.translate("setting_ui_tr", "Volume : "))

        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.notifications_tab),
            QCoreApplication.translate("setting_ui_tr", "Notifications"))

        self.style_label.setText(
            QCoreApplication.translate("setting_ui_tr", "Style : "))
        self.color_label.setText(
            QCoreApplication.translate("setting_ui_tr", "Color scheme : "))
        self.icon_label.setText(
            QCoreApplication.translate("setting_ui_tr", "Icons : "))

        self.icons_size_label.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "ToolBar's icons size : "))

        self.notification_label.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Notification type : "))

        self.font_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", "Font : "))
        self.font_size_label.setText(
            QCoreApplication.translate("setting_ui_tr", "Size : "))

        self.enable_system_tray_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Enable system tray icon."))
        self.after_download_checkBox.setText(
            QCoreApplication.translate(
                "setting_ui_tr",
                "Show download complete dialog,when download has finished."))

        self.show_menubar_checkbox.setText(
            QCoreApplication.translate("setting_ui_tr", "Show menubar."))
        self.show_sidepanel_checkbox.setText(
            QCoreApplication.translate("setting_ui_tr", "Show side panel."))
        self.show_progress_window_checkbox.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Show download's progress window"))

        self.startup_checkbox.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       "Run Persepolis at startup"))

        self.keep_awake_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", "Keep system awake!"))
        self.keep_awake_checkBox.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>This option is preventing system from going to sleep.\
            This is necessary if your power manager is suspending system automatically. </p></body></html>"
            ))

        self.wait_queue_time.setToolTip(
            QCoreApplication.translate(
                "setting_ui_tr",
                "<html><head/><body><p>Format HH:MM</p></body></html>"))

        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.style_tab),
            QCoreApplication.translate("setting_ui_tr", "Preferences"))

        # columns_tab
        self.show_column_label.setText(
            QCoreApplication.translate("setting_ui_tr", 'Show this columns:'))
        self.column0_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'File Name'))
        self.column1_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Status'))
        self.column2_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Size'))
        self.column3_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Downloaded'))
        self.column4_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Percentage'))
        self.column5_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Connections'))
        self.column6_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Transfer rate'))
        self.column7_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Estimated time left'))
        self.column10_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'First try date'))
        self.column11_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Last try date'))
        self.column12_checkBox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Category'))

        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.columns_tab),
            QCoreApplication.translate("setting_ui_tr",
                                       "Columns customization"))

        # Video Finder options tab
        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.youtube_tab),
            QCoreApplication.translate("setting_ui_tr",
                                       "Video Finder Options"))

        self.enable_ytd_checkbox.setText(
            QCoreApplication.translate("setting_ui_tr", 'Enable Video Finder'))

        self.hide_no_audio_checkbox.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       'Hide videos with no audio'))

        self.hide_no_video_checkbox.setText(
            QCoreApplication.translate("setting_ui_tr",
                                       'Hide audios with no video'))
        self.max_links_label.setText(
            QCoreApplication.translate(
                "setting_ui_tr", 'Maximum number of links to capture :<br/>'
                '<small>(If browser sends multiple video links at a time)</small>'
            ))

        # window buttons
        self.defaults_pushButton.setText(
            QCoreApplication.translate("setting_ui_tr", "Defaults"))
        self.cancel_pushButton.setText(
            QCoreApplication.translate("setting_ui_tr", "Cancel"))
        self.ok_pushButton.setText(
            QCoreApplication.translate("setting_ui_tr", "OK"))
예제 #11
0
파일: page1.py 프로젝트: Soomali/keysounder
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.scrollArea = QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QRect(559, 10, 231, 541))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QWidget()
        self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 229, 539))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.verticalLayoutWidget = QWidget(self.scrollAreaWidgetContents)
        self.verticalLayoutWidget.setGeometry(QRect(0, 0, 231, 541))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.frame = QFrame(self.centralwidget)
        self.frame.setGeometry(QRect(20, 10, 521, 541))
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.start = QPushButton(self.frame)
        self.start.setGeometry(QRect(370, 440, 111, 51))
        self.start.setObjectName("start")
        self.stop = QPushButton(self.frame)
        self.stop.setGeometry(QRect(230, 440, 111, 51))
        self.stop.setObjectName("stop")
        self.add_key = QPushButton(self.frame)
        self.add_key.setGeometry(QRect(400, 180, 75, 23))
        self.add_key.setObjectName("add_key")
        self.key_edit = QLineEdit(self.frame)
        self.key_edit.setGeometry(QRect(50, 80, 171, 21))
        self.key_edit.setObjectName("key_edit")
        self.music_choose = QPushButton(self.frame)
        self.music_choose.setGeometry(QRect(260, 80, 211, 23))
        self.music_choose.setObjectName("music_choose")
        self.label = QLabel(self.frame)
        self.label.setGeometry(QRect(50, 60, 47, 13))
        self.label.setObjectName("label")
        self.frame2 = QFrame(self.centralwidget)
        self.frame2.setGeometry(QRect(0, 0, 0, 0))
        self.frame2.setFrameShape(QFrame.StyledPanel)
        self.frame2.setFrameShadow(QFrame.Raised)
        self.frame2.setObjectName("frame")
        self.key_edit2 = QLineEdit(self.frame2)
        self.key_edit2.setGeometry(QRect(50, 80, 171, 21))
        self.key_edit2.setObjectName("key_edit2")
        self.music_choose2 = QPushButton(self.frame2)
        self.music_choose2.setGeometry(QRect(260, 80, 211, 23))
        self.music_choose2.setObjectName("music_choose2")
        self.label2 = QLabel(self.frame2)
        self.label2.setGeometry(QRect(50, 60, 47, 13))
        self.label2.setObjectName("label")
        self.update = QPushButton(self.frame2)
        self.update.setGeometry(QRect(400, 140, 75, 23))
        self.update.setObjectName("update")
        self.delete_2 = QPushButton(self.frame2)
        self.delete_2.setGeometry(QRect(400, 170, 75, 23))
        self.delete_2.setObjectName("delete_2")
        self.pushButton = QPushButton(self.frame2)
        self.pushButton.setGeometry(QRect(30, 450, 101, 61))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "KeySounder"))
        self.start.setText(_translate("MainWindow", "start keysounder"))
        self.stop.setText(_translate("MainWindow", "stop keysounder"))
        self.add_key.setText(_translate("MainWindow", "add"))
        self.music_choose.setText(_translate("MainWindow",
                                             "No music selected"))
        self.label.setText(_translate("MainWindow", "key"))
        self.pushButton.setText(_translate("MainWindow", "go back"))
        self.delete_2.setText(_translate("MainWindow", "delete"))
        self.update.setText(_translate("MainWindow", "update"))
        self.music_choose2.setText(
            _translate("MainWindow", "No music selected"))
        self.label2.setText(_translate("MainWindow", "key"))
예제 #12
0
class CypherEditGridWidget(QWidget, Ui_cypherEditGridWidget):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None, fileName=None, fileText=None, mode=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(CypherEditGridWidget, self).__init__(parent)
        self.setupUi(self)
        self.parent = parent
        self.settings = QSettings()
        self.initUI()
        self.initScintilla()
        self.helper = Helper()
        self.mode = mode
        self.tabType = "CYPHER"
        self.tabName = fileName
        self.tabIndex = None  # this is the index into the tabWidget of the tab this widget is on
        self.fileName = fileName
        self.fileText = fileText
        self.resultSet = None

        # create a neocon object for this file tab
        self.neoDriver = NeoDriver(name=self.parent.pageItem.neoConName,
                                   promptPW=self.parent.pageItem.promptPW)

        # add the data grid widget.
        self.dataGridGeneric = DataGridGeneric()
        self.dataGrid = DataGridWidget(self,
                                       neoCon=self.neoDriver,
                                       genCypher=self.dataGridGeneric)
        self.nodeGridLayout = QVBoxLayout(self.frmDataGrid)
        self.nodeGridLayout.setObjectName("nodeGridLayout")
        self.nodeGridLayout.setContentsMargins(1, 1, 1, 1)
        self.nodeGridLayout.setSpacing(1)
        self.nodeGridLayout.addWidget(self.dataGrid)

        if self.mode == MODENEW:
            if not self.fileText is None:
                self.loadText()

        if self.mode == MODEEDIT:
            self.loadFile()

        # position the splitter
        self.show(
        )  # you have to do this to force all the widgets sizes to update
        half = int((self.frmEditnGrid.height() / 2))
        self.splitter.setSizes([half, half])

    def logMsg(self, msg):

        if logging:
            logging.info(msg)

    def initUI(self, ):
        #initialize state of commit buttons and dropdown
        self.btnCommit.setEnabled(False)
        self.btnRollBack.setEnabled(False)
        self.cmbAutoCommit.setCurrentIndex(0)

    def initScintilla(self):
        # add and initialize the control to self.frmEditor
        self.editor = QsciScintilla()
        self.editor.setLexer(None)
        self.editor.setUtf8(True)  # Set encoding to UTF-8
        self.editor.setWrapMode(QsciScintilla.WrapNone)
        self.editor.setEolVisibility(False)
        self.editor.setIndentationsUseTabs(False)
        self.editor.setTabWidth(4)
        self.editor.setIndentationGuides(True)
        self.editor.setAutoIndent(True)
        self.editor.setMarginType(0, QsciScintilla.NumberMargin)
        self.editor.setMarginWidth(0, "00000")
        self.editor.setMarginsForegroundColor(QColor("#ffffffff"))
        self.editor.setMarginsBackgroundColor(QColor("#00000000"))
        self.verticalLayout_2.addWidget(self.editor)
        # setup the lexer
        self.lexer = CypherLexer(self.editor)
        self.editor.setLexer(self.lexer)
        self.setScintillaFontSize()
        self.editor.SendScintilla(self.editor.SCI_GETCURRENTPOS, 0)
        self.editor.setCaretForegroundColor(QColor("#ff0000ff"))
        self.editor.setCaretLineVisible(True)
        self.editor.setCaretLineBackgroundColor(QColor("#1f0000ff"))
        self.editor.setCaretWidth(2)
        self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

    def setScintillaFontSize(self, ):
        # set font size to value saved in settings
        try:
            fontSize = int(self.settings.value("Lexer/FontSize", "10"))
        except:
            fontSize = 10
        finally:
            for style in range(5):
                self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE,
                                          style, fontSize)
            self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 34,
                                      fontSize)
            self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 35,
                                      fontSize)

#####################################################################################
# methods related to the cypher file
#####################################################################################

    def loadText(self, ):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.editor.append(self.fileText)
        self.editor.setModified(True)
        QApplication.restoreOverrideCursor()

    def loadFile(self, ):
        file = QFile(self.fileName)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(
                self, "NodeMaker", "Cannot read file %s:\n%s." %
                (self.fileName, file.errorString()))
            return False

        instr = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.editor.append(instr.readAll())
        self.editor.setModified(False)
        QApplication.restoreOverrideCursor()

    def save(self, ):
        if self.mode == MODENEW:
            self.saveAs()
        else:
            self.saveIt()

    def saveAs(self, ):
        # first test to see if the file has changed

        # get filename to save as
        #
        dlg = QFileDialog()
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        dlg.setDefaultSuffix("cyp")
        dlg.setNameFilters([
            "Cypher Query (*.cyp *.cypher)", "Cypher Query (*.cyp)",
            "Cypher Query (*.cypher)", "all files (*.*)"
        ])
        dlg.setDirectory(self.parent.settings.value("Default/ProjPath"))
        if dlg.exec_():
            fileNames = dlg.selectedFiles()
            if fileNames:
                self.fileName = fileNames[0]
                # save the file
                self.saveIt()

    def saveIt(self, ):
        file = QFile(self.fileName)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, "NodeEra", "Cannot write file %s:\n%s." %
                (self.fileName, file.errorString()))
            return

        outstr = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outstr << self.editor.text()
        head, tail = ntpath.split(QFileInfo(self.fileName).fileName())
        self.parent.tabCypher.setTabText(self.parent.tabCypher.currentIndex(),
                                         tail)
        self.mode = MODEEDIT
        QApplication.restoreOverrideCursor()

    def close(self, ):
        #        print("editngrid close {}".format(self.fileName))
        # see if there is an open transaction and cancel the close
        self.checkOpenTxn()
        # see if text has changed and save the file if the user wants to
        if self.editor.isModified():
            # see if the user wants to save it
            if self.fileName is None:
                # these are unsaved cypher files so they have no filename yet
                displayName = self.parent.tabCypher.tabText(self.tabIndex)
            else:
                displayName = self.fileName
            if self.helper.saveChangedObject("Cypher File", displayName):
                self.save()
        return True

##############################################################
# Button methods
##############################################################

    @pyqtSlot()
    def on_btnRun_clicked(self):
        """
        Run the query at the cursor.
        """
        self.runFileCursor()

    def runFileCursor(self):

        self.logMsg("User requests run Cypher in Cursor")
        # parse the text editor and get the index to the cypher command the cursor is pointing at
        currentCypherIndex = self.getSelectedCypher()
        # check if cursor in a query
        if currentCypherIndex is None:
            self.helper.displayErrMsg(
                "Run Query",
                "You must position cursor within the Cypher query.")
            QApplication.restoreOverrideCursor()
            return

        # get the cypher statement to be executed
        startOffset = self.cypherList[currentCypherIndex][0]
        self.dataGrid.cypher = self.cypherList[currentCypherIndex][1]

        # prompt the user for parameter values if any
        userCanceled = False
        if len(self.cypherParms[currentCypherIndex][1]) > 0:
            #            print("Parms:{}".format(self.cypherParms[currentCypherIndex][1]))
            # display dialog to gather parms
            d = CypherParmEntryDlg(
                parent=self, parms=self.cypherParms[currentCypherIndex][1])
            if d.exec_():
                self.dataGrid.parmData = d.parmDict
            else:
                userCanceled = True
                self.dataGrid.parmData = None
#            print("Parm Dictionary:{}".format(self.dataGrid.parmData))
        else:
            self.dataGrid.parmData = None

        # see if the user canceled the query rather than enter parameters
        if userCanceled:
            self.helper.displayErrMsg("Run Query", "User Canceled Query.")
            QApplication.restoreOverrideCursor()
            return

        # make sure the cypher is not just spaces, or nothing but a semicolon
        if (self.dataGrid.cypher.isspace() or len(self.dataGrid.cypher) == 0
                or self.dataGrid.cypher.strip() == ";"):
            self.helper.displayErrMsg(
                "Run Query",
                "You must position cursor within the Cypher query.")
        else:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            self.dataGrid.refreshGrid()
            QApplication.restoreOverrideCursor()
        # see if there was a syntax error and position cursor
        try:
            offset = self.dataGrid.neoCon.cypherLogDict["offset"]
            if offset > -1:
                self.editor.SendScintilla(QsciScintilla.SCI_GOTOPOS,
                                          offset + startOffset)
        except:
            pass
        finally:
            ###  hack needed on mac os to force scintilla to show cursor and highlighted line
            self.helper.displayErrMsg("Run Query With Cursor",
                                      "Query Complete")

    def getSelectedCypher(self):
        '''
        Build a list of cypher commands from the text in the editor
        '''
        # get position of cursor which is a zero based offset, it seems to return zero if editor hasn't been clicked on yet
        try:
            position = self.editor.SendScintilla(
                QsciScintilla.SCI_GETCURRENTPOS, 0)
        except:
            position = 0
        # initialize cypherList
        self.cypherList = []
        self.cypherParms = []
        parmList = []
        currentCypherIndex = None
        # get the full text from the editor
        text = self.editor.text()
        # make sure there is something in the text
        if len(text) < 1:
            return currentCypherIndex

        #	Walk through all the characters in text, and store start offset and end offset of each command
        startOffset = 0
        endOffset = 0
        foundCypher = False  # tracks if we have found at least one character that is potentially a non-comment cypher command
        inComment = False  # tracks if we're looking at comment characters
        inParm = False  # tracks if we're looking at parameter characters
        inCypher = False  # tracks if we've found a non comment character while scanning
        newParm = ""
        for chrCtr in range(0, len(text)):
            #            print("before: chrCtr:{} char: {} ord:{} inComment:{} inParm:{} inCypher:{}".format(chrCtr, text[chrCtr], ord(text[chrCtr]), inComment, inParm, inCypher))

            # see if we're in a comment ( this doesn't work for multiline comments)
            if chrCtr + 1 < len(text) and text[chrCtr] == '/':
                inParm = False
                if text[chrCtr + 1] == "/":
                    inComment = True
                    inCypher = False
            # see if end of line
            elif ord(text[chrCtr]) in [13, 10]:
                inParm = False
                if chrCtr + 1 < len(text):
                    if not text[chrCtr + 1] in [13, 10]:
                        # end of line ends the comment
                        inComment = False

            elif text[chrCtr] == "$":
                if not inComment:
                    foundCypher = True
                    inParm = True
            elif text[chrCtr] == " ":
                if not inComment:
                    foundCypher = True
                inParm = False
            elif (text[chrCtr] == ";" and inComment == False):
                foundCypher = True
                inParm = False
                endOffset = chrCtr
                # save each command in the list
                self.cypherList.append(
                    [startOffset, text[startOffset:endOffset + 1]])
                self.cypherParms.append([startOffset, parmList])
                parmList = []
                # HAPPY PATH - see if this is the command where the cursor is located
                if (position >= startOffset and position <= endOffset):
                    currentCypherIndex = len(self.cypherList) - 1
                # set the next starting offset
                startOffset = chrCtr + 1
                endOffset = startOffset
            elif inComment == False:
                foundCypher = True
                inCypher = True

            if inParm:
                newParm = newParm + text[chrCtr]
            else:
                if len(newParm) > 0:
                    #                    print("Parameter: {}".format(newParm))
                    parmList.append(newParm)
                    newParm = ""

#            print("after: chrCtr:{} char: {} ord:{} inComment:{} inParm:{} inCypher:{}".format(chrCtr, text[chrCtr], ord(text[chrCtr]), inComment, inParm, inCypher))

# at this point all characters have been processed, must deal with edge cases, no final semicolon etc
        if len(
                self.cypherList
        ) == 0:  # we never found a semi colon so the entire file is one cypher statement
            # return the entire text file
            self.cypherList.append([0, text])
            self.cypherParms.append([0, parmList])
            parmList = []

            currentCypherIndex = 0
        else:  # we found some characters after the last semi colon.
            lastCypher = ""
            try:
                lastCypher = text[startOffset:len(text)]
                if lastCypher.isspace(
                ) == True:  # if there is only whitespace after the last semicolon then return the last found cypher
                    if currentCypherIndex is None:
                        currentCypherIndex = len(self.cypherList) - 1
                elif len(
                        lastCypher
                ) < 1:  # there are no characters after the last semicolon, but cursor is positioned past it then return the last found cypher
                    if currentCypherIndex is None:
                        currentCypherIndex = len(self.cypherList) - 1
                elif inCypher == False and foundCypher == False:  # none of the characters are outside a comment so return last found cypher
                    if currentCypherIndex is None:
                        currentCypherIndex = len(self.cypherList) - 1
                else:
                    self.cypherList.append(
                        [startOffset, lastCypher]
                    )  # since some characters are present, add them as the last cypher command
                    self.cypherParms.append([startOffset, parmList])
                    parmList = []

                    if currentCypherIndex is None:
                        currentCypherIndex = len(self.cypherList) - 1
            except:
                if currentCypherIndex is None:
                    currentCypherIndex = len(
                        self.cypherList
                    ) - 1  # return the last cypher command found if any error

#        print("cypher list: {}".format(self.cypherList))
        return currentCypherIndex

    @pyqtSlot()
    def on_btnRunScript_clicked(self):
        """
        this button will run all the cypher commands in the file one at a time.
        """

        self.runFileAsScript()

    def runFileAsScript(self, ):
        '''
        run each cypher command in the file one at a time.
        '''
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.logMsg("User requests run Cypher file as a script")
        # parse the text editor into cypher commands, we don't care which one the cursor is in
        self.getSelectedCypher()
        if len(self.cypherList) < 1:
            self.helper.displayErrMsg(
                "Run File As Script", "The file has no cypher commands in it.")
        for cypherCmd in self.cypherList:
            # this is the starting offset of the cypher command in the entire file
            cypherOffset = cypherCmd[0]
            self.dataGrid.cypher = cypherCmd[1]
            # set editor selection to the cypher command
            self.editor.SendScintilla(QsciScintilla.SCI_SETSEL, cypherOffset,
                                      cypherOffset + len(self.dataGrid.cypher))
            # skip any cypher is not just spaces, or nothing but a semicolon
            if (self.dataGrid.cypher.isspace()
                    or len(self.dataGrid.cypher) == 0
                    or self.dataGrid.cypher.strip() == ";"):
                #self.helper.displayErrMsg("Run Query",  "You must position cursor within the Cypher query.")
                pass
            else:
                self.dataGrid.refreshGrid()
                QApplication.processEvents()
            # see if there was a syntax error and position cursor
            try:
                offset = self.dataGrid.neoCon.cypherLogDict["offset"]
                if offset > -1:
                    self.editor.SendScintilla(QsciScintilla.SCI_GOTOPOS,
                                              offset + cypherOffset)
            except:
                pass
            # set editor selection to the end of the file
            self.editor.SendScintilla(QsciScintilla.SCI_SETSEL,
                                      len(self.editor.text()),
                                      len(self.editor.text()))

        QApplication.restoreOverrideCursor()

    @pyqtSlot()
    def on_btnCommit_clicked(self):
        """
        User clicks on the Commit button.  Commit the TXN.
        """
        self.doCommit()

    def doCommit(self):
        self.logMsg("User request Commit the transaction")
        if not self.neoDriver is None:
            rc, msg = self.neoDriver.commitTxn()
            self.logMsg("Commit Complete - {}".format(msg))

    @pyqtSlot()
    def on_btnRollBack_clicked(self):
        """
        User clicks on the Rollback button.  Rollback the TXN.
        """
        self.doRollBack()

    def doRollBack(self):
        self.logMsg("User request Rollback the transaction")
        if not self.neoDriver is None:
            rc, msg = self.neoDriver.rollbackTxn()
            self.logMsg("Rollback Complete - {}".format(msg))

    def zoomIn(self, ):
        """
        increase Font Size
        """
        #        self.editor.SendScintilla(QsciScintilla.SCI_ZOOMIN)
        #        currentFontSize = self.editor.SendScintilla(QsciScintilla.SCI_STYLEGETSIZE, 0)
        #        self.settings.setValue("Lexer/FontSize", currentFontSize)
        # get style 0 font size - all styles use same size
        currentFontSize = self.editor.SendScintilla(
            QsciScintilla.SCI_STYLEGETSIZE, 0)
        currentFontSize = currentFontSize + 2
        if currentFontSize < 24:
            self.settings.setValue("Lexer/FontSize", currentFontSize)
            for style in range(255):
                self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE,
                                          style, currentFontSize)
#            self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 34, currentFontSize)
#            self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 35, currentFontSize)

    def zoomOut(self, ):
        """
        decrease font size
        """
        #        self.editor.SendScintilla(QsciScintilla.SCI_ZOOMOUT)
        #        currentFontSize = self.editor.SendScintilla(QsciScintilla.SCI_STYLEGETSIZE, 0)
        #        self.settings.setValue("Lexer/FontSize", currentFontSize)

        # get style 0 font size - all styles use same size
        currentFontSize = self.editor.SendScintilla(
            QsciScintilla.SCI_STYLEGETSIZE, 0)
        currentFontSize = currentFontSize - 2
        if currentFontSize > 4:
            self.settings.setValue("Lexer/FontSize", currentFontSize)
            for style in range(255):  # was 5
                self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE,
                                          style, currentFontSize)
#            self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 34, currentFontSize)
#            self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 35, currentFontSize)

    def checkOpenTxn(self):
        '''
        check if current txn is still open.  
        if autocommit is false then ask the user to commit or rollback
        if autocommit is true then do the commit
        '''
        if not (self.neoDriver is None):
            if not (self.neoDriver.tx is None):
                if self.neoDriver.tx.closed() is False:
                    if self.neoDriver.autoCommit is True:
                        self.doCommit()
                    else:
                        # prompt user to commit or rollback the current transaction
                        msgBox = QMessageBox()
                        msgBox.setIcon(QMessageBox.Warning)
                        msgBox.setText(
                            "You have an uncommitted transaction. Do you want to commit? (click Yes to commit, No to rollback"
                        )
                        msgBox.setWindowTitle("Commit or Rollback")
                        msgBox.setStandardButtons(QMessageBox.Yes
                                                  | QMessageBox.No)
                        result = msgBox.exec_()
                        if result == QMessageBox.Yes:
                            self.doCommit()
                        else:
                            self.doRollBack()

    @pyqtSlot(int)
    def on_cmbAutoCommit_currentIndexChanged(self, index):
        """
        User has changed the auto commit dropdown.
        
        @param index DESCRIPTION
        @type int
        """
        self.logMsg("User request transaction mode changed to {}".format(
            self.cmbAutoCommit.currentText()))
        if self.cmbAutoCommit.currentText() == "Auto Commit On":
            self.checkOpenTxn()
            if not (self.neoDriver is None):
                self.neoDriver.setAutoCommit(True)
            self.btnCommit.setEnabled(False)
            self.btnRollBack.setEnabled(False)
        if self.cmbAutoCommit.currentText() == "Auto Commit Off":
            self.checkOpenTxn()
            if not (self.neoDriver is None):
                self.neoDriver.setAutoCommit(False)
            self.btnCommit.setEnabled(True)
            self.btnRollBack.setEnabled(True)
예제 #13
0
class MainWidget(QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.typing_box = QLineEdit()
        self.peer_list = QListWidget()
        self.message_list = QVBoxLayout()
        self.init_ui()

    def init_ui(self):
        main_box = QHBoxLayout()
        hsplitter = QSplitter(Qt.Horizontal)

        self.init_peer_list()
        hsplitter.addWidget(self.peer_list)

        message_box = self.create_message_box()
        hsplitter.addWidget(message_box)
        hsplitter.setChildrenCollapsible(False)
        hsplitter.setSizes([1000, 3000])

        main_box.addWidget(hsplitter, 1)
        main_box.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_box)

    def init_peer_list(self):
        pass
        self.peer_list.setObjectName("peerList")
        self.peer_list.setMinimumSize(300, 400)
        self.peer_list.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    def create_message_box(self):
        container = QWidget()
        container.setObjectName("messageContainer")
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        container.setLayout(layout)

        typingContainer = QWidget()
        typingContainer.setObjectName("typingContainer")
        typingLayout = QHBoxLayout()
        typingContainer.setLayout(typingLayout)
        typingLayout.addWidget(self.typing_box)
        self.typing_box.setPlaceholderText("Write a message...")
        self.typing_box.setObjectName("typingBox")

        self.message_list.setObjectName("messageBox")
        self.message_list.setSpacing(0)
        self.message_list.setContentsMargins(0, 0, 0, 0)

        self.message_scroll_area = QScrollArea()
        bar = self.message_scroll_area.verticalScrollBar()
        bar.rangeChanged.connect(self.range_changed)
        self.message_scroll_area.setWidgetResizable(True)
        client = QWidget()
        client.setMaximumWidth(800)
        self.message_scroll_area.setWidget(client)
        self.message_scroll_area.setAlignment(Qt.AlignCenter)
        client.setLayout(self.message_list)

        self.message_list.addStretch()

        layout.addWidget(self.message_scroll_area, stretch=1)
        layout.addWidget(typingContainer, stretch=0, alignment=Qt.AlignBottom)

        return container

    def range_changed(self, min, max):
        self.message_scroll_area.verticalScrollBar().setValue(max)

    def add_item(self, item):
        widget_item = QListWidgetItem(self.peer_list)
        widget_item.setSizeHint(item.sizeHint())
        self.peer_list.addItem(widget_item)
        self.peer_list.setItemWidget(widget_item, item)
예제 #14
0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(180, 70)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
        Form.setSizePolicy(sizePolicy)
        Form.setMinimumSize(QSize(180, 70))
        Form.setMaximumSize(QSize(180, 80))
        Form.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.toolButton_2 = QToolButton(Form)
        self.toolButton_2.setEnabled(False)
        self.toolButton_2.setMinimumSize(QSize(30, 30))
        self.toolButton_2.setMaximumSize(QSize(30, 30))
        self.toolButton_2.setStyleSheet(
            "background-color: rgba(255, 255, 255, 0);")
        icon = QIcon()
        icon.addPixmap(QPixmap("robotImages/small.png"), QIcon.Normal,
                       QIcon.Off)
        icon.addPixmap(QPixmap("robotImages/small.png"), QIcon.Disabled,
                       QIcon.Off)
        self.toolButton_2.setIcon(icon)
        self.toolButton_2.setIconSize(QSize(30, 30))
        self.toolButton_2.setCheckable(False)
        self.toolButton_2.setObjectName("toolButton_2")
        self.horizontalLayout.addWidget(self.toolButton_2)
        self.pushButton = QPushButton(Form)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setMinimumSize(QSize(130, 0))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.toolButton = QToolButton(Form)
        self.toolButton.setEnabled(False)
        self.toolButton.setMinimumSize(QSize(30, 30))
        self.toolButton.setMaximumSize(QSize(30, 30))
        self.toolButton.setStyleSheet(
            "background-color: rgba(255, 255, 255, 0);")
        icon1 = QIcon()
        icon1.addPixmap(QPixmap("robotImages/smallRed.png"), QIcon.Normal,
                        QIcon.Off)
        icon1.addPixmap(QPixmap("robotImages/smallRed.png"), QIcon.Disabled,
                        QIcon.Off)
        self.toolButton.setIcon(icon1)
        self.toolButton.setIconSize(QSize(30, 30))
        self.toolButton.setCheckable(False)
        self.toolButton.setObjectName("toolButton")
        self.horizontalLayout_2.addWidget(self.toolButton)
        self.progressBar = QProgressBar(Form)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.progressBar.sizePolicy().hasHeightForWidth())
        self.progressBar.setSizePolicy(sizePolicy)
        self.progressBar.setMinimumSize(QSize(130, 0))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout_2.addWidget(self.progressBar)
        self.verticalLayout.addLayout(self.horizontalLayout_2)

        self.retranslateUi(Form)
        QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QApplication.translate("Form", "Form"))
        self.toolButton_2.setText(QApplication.translate("Form", "..."))
        self.pushButton.setText(QApplication.translate("Form", "PushButton"))
        self.toolButton.setText(QApplication.translate("Form", "..."))
class EditorMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setupUi(self)
        self.retranslateUi(self)

        self.pikmin_routes = RouteTxt()
        self.pikminroutes_screen.pikmin_routes = self.pikmin_routes
        self.collision = None
        self.current_coordinates = None

        self.button_delete_waypoints.pressed.connect(
            self.action_button_delete_wp)
        self.button_ground_waypoints.pressed.connect(
            self.action_button_ground_wp)
        self.button_move_waypoints.pressed.connect(self.action_button_move_wp)
        self.button_add_waypoint.pressed.connect(self.action_button_add_wp)
        self.button_connect_waypoints.pressed.connect(
            self.action_button_connect_wp)

        self.pikminroutes_screen.customContextMenuRequested.connect(
            self.mapview_showcontextmenu)

        QtWidgets.QShortcut(Qt.Key_M,
                            self).activated.connect(self.action_button_move_wp)
        QtWidgets.QShortcut(Qt.Key_G, self).activated.connect(
            self.action_button_ground_wp)
        QtWidgets.QShortcut(Qt.CTRL + Qt.Key_A,
                            self).activated.connect(self.action_button_add_wp)
        QtWidgets.QShortcut(Qt.Key_C, self).activated.connect(
            self.action_button_connect_wp)
        QtWidgets.QShortcut(Qt.Key_Delete, self).activated.connect(
            self.action_button_delete_wp)

        self.button_delete_waypoints.setToolTip("Shortcut: Delete")
        self.button_move_waypoints.setToolTip("Shortcut: M")
        self.button_ground_waypoints.setToolTip("Shortcut: G")
        self.button_add_waypoint.setToolTip("Shortcut: Ctrl+A")
        self.button_connect_waypoints.setToolTip("Shortcut: C")

        self.lineedit_xcoordinate.editingFinished.connect(
            self.action_lineedit_change_x)
        self.lineedit_ycoordinate.editingFinished.connect(
            self.action_lineedit_change_y)
        self.lineedit_zcoordinate.editingFinished.connect(
            self.action_lineedit_change_z)
        self.lineedit_radius.editingFinished.connect(
            self.action_lineedit_change_radius)

        self.pikminroutes_screen.connect_update.connect(
            self.action_connect_waypoints)
        self.pikminroutes_screen.move_points.connect(
            self.action_move_waypoints)
        self.pikminroutes_screen.create_waypoint.connect(
            self.action_create_waypoint)
        self.disable_lineedits()
        self.last_render = None
        self.current_route_path = None

        try:
            self.configuration = read_config()
            print("config loaded")
        except FileNotFoundError as e:
            print(e)
            print("creating file...")
            self.configuration = make_default_config()
        #self.ground_wp_when_moving = self.configuration["ROUTES EDITOR"].getboolean("groundwaypointswhenmoving")

        self.pathsconfig = self.configuration["default paths"]
        self.editorconfig = self.configuration["routes editor"]
        self.pikminroutes_screen.editorconfig = self.editorconfig

        print("We are now ready!")

    def reset(self):
        self.current_position = None
        self.resetting = True
        self.statusbar.clearMessage()
        self.dragged_time = None
        self.moving = False
        self.dragging = False
        self.last_x = None
        self.last_y = None
        self.dragged_time = None

        self.moving = False
        self.pikminroutes_screen.reset(keep_collision=True)
        self.current_route_path = None

        self.resetting = False
        self.button_delete_waypoints.setDisabled(False)
        self.button_add_waypoint.setPushed(False)
        self.button_connect_waypoints.setPushed(False)
        self.button_move_waypoints.setPushed(False)
        self.disable_lineedits()

        print("reset done")

    def button_load_level(self):
        try:
            print("ok", self.pathsconfig["routes"])

            filepath, choosentype = QFileDialog.getOpenFileName(
                self, "Open File", self.pathsconfig["routes"],
                PIKMIN2PATHS + ";;All files (*)")
            print("doooone")
            if filepath:
                print("resetting")
                self.reset()
                print("done")
                print("chosen type:", choosentype)

                with open(filepath, "r") as f:
                    try:
                        pikmin_routes = RouteTxt()
                        pikmin_routes.from_file(f)
                        self.setup_routes(pikmin_routes, filepath)

                    except Exception as error:
                        print("error", error)
                        traceback.print_exc()

        except Exception as er:
            print("errrorrr", er)
            traceback.print_exc()
        print("loaded")

    def setup_routes(self, pikmin_routes, filepath):
        self.pikmin_routes = pikmin_routes
        self.pikminroutes_screen.pikmin_routes = self.pikmin_routes
        self.pikminroutes_screen.update()

        print("ok")
        # self.bw_map_screen.update()
        path_parts = path.split(filepath)
        self.setWindowTitle("Routes Editor - {0}".format(filepath))
        self.pathsconfig["routes"] = filepath
        self.current_route_path = filepath
        save_cfg(self.configuration)

    def button_save_level(self):
        try:
            print("ok", self.pathsconfig["routes"])

            if self.current_route_path is not None:
                filepath = self.current_route_path
                with open(filepath, "w") as f:
                    self.pikmin_routes.write(f)
                self.pathsconfig["routes"] = filepath
                save_cfg(self.configuration)
            else:
                self.button_save_as_level()
        except Exception as err:
            traceback.print_exc()

    def button_save_as_level(self):
        try:
            filepath, choosentype = QFileDialog.getSaveFileName(
                self, "Save File", self.pathsconfig["routes"],
                PIKMIN2PATHS + ";;All files (*)")

            if filepath:
                with open(filepath, "w") as f:
                    self.pikmin_routes.write(f)
                self.pathsconfig["routes"] = filepath
                self.current_route_path = filepath
                save_cfg(self.configuration)

        except Exception as err:
            traceback.print_exc()

    def button_load_collision(self):
        try:
            filepath, choosentype = QFileDialog.getOpenFileName(
                self, "Open File", self.pathsconfig["collision"],
                "Collision (*.obj);;All files (*)")
            with open(filepath, "r") as f:
                verts, faces, normals = read_obj(f)

            self.setup_collision(verts, faces, filepath)
        except:
            traceback.print_exc()

    def button_load_collision_grid(self):
        try:
            filepath, choosentype = QFileDialog.getOpenFileName(
                self, "Open File", self.pathsconfig["collision"],
                "Archived grid.bin (*.arc, *.szs);;Grid.bin (*.bin);;All files (*)"
            )
            print(choosentype)

            if choosentype == "Archived grid.bin (texts.arc, texts.szs)" or filepath.endswith(
                    ".szs") or filepath.endswith(".arc"):
                load_from_arc = True
            else:
                load_from_arc = False

            with open(filepath, "rb") as f:
                if load_from_arc:
                    archive = Archive.from_file(f)
                    f = archive["text/grid.bin"]
                collision = PikminCollision(f)

            verts = collision.vertices
            faces = [face[0] for face in collision.faces]
            self.setup_collision(verts, faces, filepath)

        except:
            traceback.print_exc()

    def setup_collision(self, verts, faces, filepath):
        width = int(self.configuration["model render"]["Width"])
        height = int(self.configuration["model render"]["Height"])
        print(width, height)

        tmprenderwindow = TempRenderWindow(verts,
                                           faces,
                                           render_res=(width, height))
        tmprenderwindow.show()

        framebuffer = tmprenderwindow.widget.grabFramebuffer()
        framebuffer.save("tmp_image.png", "PNG")
        self.pikminroutes_screen.level_image = framebuffer

        tmprenderwindow.destroy()

        self.pikminroutes_screen.set_collision(verts, faces)
        self.pathsconfig["routes"] = filepath
        save_cfg(self.configuration)

    @catch_exception
    def event_update_lineedit(self, event):
        selected_count = len(self.pikminroutes_screen.selected_waypoints)
        if selected_count == 1:
            for waypoint in self.pikminroutes_screen.selected_waypoints:
                x, y, z, radius = self.pikmin_routes.waypoints[waypoint]

                self.set_wp_lineedit_coordinates(x, y, z, radius)
                self.enable_lineedits()
                #self.lineedit_xcoordinate
        elif selected_count == 0 or selected_count > 1:
            self.lineedit_xcoordinate.setText("")
            self.lineedit_ycoordinate.setText("")
            self.lineedit_zcoordinate.setText("")
            self.lineedit_radius.setText("")
            self.disable_lineedits()

    def disable_lineedits(self):
        self.lineedit_xcoordinate.setDisabled(True)
        self.lineedit_ycoordinate.setDisabled(True)
        self.lineedit_zcoordinate.setDisabled(True)
        self.lineedit_radius.setDisabled(True)

    def enable_lineedits(self):
        self.lineedit_xcoordinate.setDisabled(False)
        self.lineedit_ycoordinate.setDisabled(False)
        self.lineedit_zcoordinate.setDisabled(False)
        self.lineedit_radius.setDisabled(False)

    def event_update_position(self, event, position):
        x, y, z = position
        self.current_coordinates = position
        if y is None:
            y = "-"
        coordtext = "X: {}, Y: {}, Z: {}".format(x, y, z)
        self.statusbar.showMessage(coordtext)
        #print(coordtext)

    @catch_exception
    def action_button_delete_wp(self):
        if self.pikmin_routes is not None and self.button_delete_waypoints.isEnabled(
        ):
            print("removing", self.pikminroutes_screen.selected_waypoints)
            for wp in self.pikminroutes_screen.selected_waypoints:
                self.pikmin_routes.remove_waypoint(wp)
            self.pikminroutes_screen.selected_waypoints = {}

            self.pikminroutes_screen.update()

    def action_button_ground_wp(self):
        if self.pikmin_routes is not None and self.pikminroutes_screen.collision is not None:
            for wp in self.pikminroutes_screen.selected_waypoints:
                x, y, z, radius = self.pikmin_routes.waypoints[wp]

                height = self.pikminroutes_screen.collision.collide_ray_downwards(
                    x, z)

                if height is not None:
                    self.pikmin_routes.waypoints[wp][1] = height
                self.set_wp_lineedit_coordinates(x, height, z, radius)
            self.pikminroutes_screen.update()

    def action_button_move_wp(self):
        if self.button_move_waypoints.ispushed:

            self.button_move_waypoints.setPushed(False)
            self.pikminroutes_screen.set_mouse_mode(
                custom_widgets.MOUSE_MODE_NONE)
            self.button_delete_waypoints.setDisabled(False)
        else:
            self.button_add_waypoint.setPushed(False)
            self.button_move_waypoints.setPushed(True)
            self.button_connect_waypoints.setPushed(False)
            self.pikminroutes_screen.set_mouse_mode(
                custom_widgets.MOUSE_MODE_MOVEWP)
            self.button_delete_waypoints.setDisabled(False)

    def action_button_add_wp(self):
        if self.button_add_waypoint.ispushed:

            self.button_add_waypoint.setPushed(False)
            self.pikminroutes_screen.set_mouse_mode(
                custom_widgets.MOUSE_MODE_NONE)
            self.button_delete_waypoints.setDisabled(False)
        else:
            self.button_add_waypoint.setPushed(True)
            self.button_move_waypoints.setPushed(False)
            self.button_connect_waypoints.setPushed(False)
            self.pikminroutes_screen.set_mouse_mode(
                custom_widgets.MOUSE_MODE_ADDWP)
            self.button_delete_waypoints.setDisabled(True)

    def action_button_connect_wp(self):
        if self.button_connect_waypoints.ispushed:

            self.button_connect_waypoints.setPushed(False)
            self.pikminroutes_screen.set_mouse_mode(
                custom_widgets.MOUSE_MODE_NONE)
            self.button_delete_waypoints.setDisabled(False)
        else:
            self.button_add_waypoint.setPushed(False)
            self.button_move_waypoints.setPushed(False)
            self.button_connect_waypoints.setPushed(True)
            self.pikminroutes_screen.set_mouse_mode(
                custom_widgets.MOUSE_MODE_CONNECTWP)
            self.button_delete_waypoints.setDisabled(True)

    def action_lineedit_change_x(self):
        try:
            value = float(self.lineedit_xcoordinate.text())
        except Exception as e:
            print(e)
        else:
            if len(self.pikminroutes_screen.selected_waypoints) == 1:
                for wp in self.pikminroutes_screen.selected_waypoints:
                    self.pikmin_routes.waypoints[wp][0] = value
                self.pikminroutes_screen.update()

    def action_lineedit_change_y(self):
        try:
            value = float(self.lineedit_ycoordinate.text())
        except Exception as e:
            print(e)
        else:
            if len(self.pikminroutes_screen.selected_waypoints) == 1:
                for wp in self.pikminroutes_screen.selected_waypoints:
                    self.pikmin_routes.waypoints[wp][1] = value
                self.pikminroutes_screen.update()

    def action_lineedit_change_z(self):
        try:
            value = float(self.lineedit_zcoordinate.text())
        except Exception as e:
            print(e)
        else:
            if len(self.pikminroutes_screen.selected_waypoints) == 1:
                for wp in self.pikminroutes_screen.selected_waypoints:
                    self.pikmin_routes.waypoints[wp][2] = value
                self.pikminroutes_screen.update()

    def action_lineedit_change_radius(self):
        try:
            value = float(self.lineedit_radius.text())
        except Exception as e:
            print(e)
        else:
            if len(self.pikminroutes_screen.selected_waypoints) == 1:
                for wp in self.pikminroutes_screen.selected_waypoints:
                    self.pikmin_routes.waypoints[wp][3] = value
                self.pikminroutes_screen.update()

    @catch_exception
    def action_connect_waypoints(self, firstwp, secondwp):
        if self.pikmin_routes is not None:
            if firstwp in self.pikmin_routes.links:
                if secondwp in self.pikmin_routes.links[firstwp]:
                    self.pikmin_routes.remove_link(firstwp, secondwp)
                else:
                    self.pikmin_routes.add_link(firstwp, secondwp)
            else:
                self.pikmin_routes.add_link(firstwp, secondwp)
            self.pikminroutes_screen.update()

    @catch_exception
    def action_move_waypoints(self, deltax, deltaz):
        if self.pikmin_routes is not None:
            for wp in self.pikminroutes_screen.selected_waypoints:
                self.pikmin_routes.waypoints[wp][0] += deltax
                self.pikmin_routes.waypoints[wp][2] += deltaz

            if len(self.pikminroutes_screen.selected_waypoints) == 1:
                do_ground = self.editorconfig.getboolean(
                    "GroundWaypointsWhenMoving")
                for wp in self.pikminroutes_screen.selected_waypoints:
                    x, y, z, radius = self.pikmin_routes.waypoints[wp]
                    if do_ground is True and self.pikminroutes_screen.collision is not None:
                        height = self.pikminroutes_screen.collision.collide_ray_downwards(
                            x, z)
                        if height is not None:
                            y = height
                            self.pikmin_routes.waypoints[wp][1] = y
                    self.set_wp_lineedit_coordinates(x, y, z, radius)

            self.pikminroutes_screen.update()

    def set_wp_lineedit_coordinates(self, x, y, z, radius):
        self.lineedit_xcoordinate.setText(str(round(x, 6)))
        self.lineedit_ycoordinate.setText(str(round(y, 6)))
        self.lineedit_zcoordinate.setText(str(round(z, 6)))
        self.lineedit_radius.setText(str(round(radius, 6)))

    @catch_exception
    def action_create_waypoint(self, x, z):
        if self.pikminroutes_screen.collision is None:
            y = 100
        else:
            height = self.pikminroutes_screen.collision.collide_ray_downwards(
                x, z)
            print("hmm, shot a ray downwards at", x, z)
            print("we got", height)
            if height is None:
                y = 100
            else:
                y = height
        radius = float(self.editorconfig["defaultradius"])
        self.pikmin_routes.add_waypoint(x, y, z, radius)
        self.pikminroutes_screen.update()
        print("created")

    @catch_exception
    def mapview_showcontextmenu(self, position):
        context_menu = QMenu(self)
        action = QAction("Copy Coordinates", self)
        action.triggered.connect(self.action_copy_coords_to_clipboard)
        context_menu.addAction(action)
        context_menu.exec(self.mapToGlobal(position))
        context_menu.destroy()

    def action_copy_coords_to_clipboard(self):
        if self.current_coordinates is not None:
            QApplication.clipboard().setText(", ".join(
                str(x) for x in self.current_coordinates))

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1200, 850)
        MainWindow.setMinimumSize(QSize(930, 850))
        MainWindow.setWindowTitle("Pikmin 2 Routes Editor")

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)

        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.pikminroutes_screen = MapViewer(self.centralwidget)
        self.pikminroutes_screen.position_update.connect(
            self.event_update_position)
        self.pikminroutes_screen.select_update.connect(
            self.event_update_lineedit)
        self.horizontalLayout.addWidget(self.pikminroutes_screen)

        spacerItem = QSpacerItem(10, 20, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.horizontalLayout.addItem(spacerItem)

        self.vertLayoutWidget = QWidget(self.centralwidget)
        self.vertLayoutWidget.setMaximumSize(QSize(250, 1200))
        self.verticalLayout = QVBoxLayout(self.vertLayoutWidget)
        self.verticalLayout.setObjectName("verticalLayout")

        self.button_add_waypoint = CheckableButton(self.centralwidget)
        self.button_delete_waypoints = QPushButton(self.centralwidget)
        self.button_ground_waypoints = QPushButton(self.centralwidget)
        self.button_move_waypoints = CheckableButton(self.centralwidget)
        self.button_connect_waypoints = CheckableButton(self.centralwidget)

        self.lineedit_xcoordinate = QLineEdit(self.centralwidget)
        self.lineedit_ycoordinate = QLineEdit(self.centralwidget)
        self.lineedit_zcoordinate = QLineEdit(self.centralwidget)
        self.lineedit_radius = QLineEdit(self.centralwidget)

        self.verticalLayout.addWidget(self.button_add_waypoint)
        self.verticalLayout.addWidget(self.button_delete_waypoints)
        self.verticalLayout.addWidget(self.button_ground_waypoints)
        self.verticalLayout.addWidget(self.button_move_waypoints)
        self.verticalLayout.addWidget(self.button_connect_waypoints)

        self.verticalLayout.addWidget(self.lineedit_xcoordinate)
        self.verticalLayout.addWidget(self.lineedit_ycoordinate)
        self.verticalLayout.addWidget(self.lineedit_zcoordinate)
        self.verticalLayout.addWidget(self.lineedit_radius)

        spacerItem1 = QSpacerItem(10, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem1)

        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.label_waypoint_info = QLabel(self.centralwidget)
        self.label_waypoint_info.setTextInteractionFlags(
            QtCore.Qt.TextSelectableByMouse)

        self.verticalLayout_2.addWidget(self.label_waypoint_info)

        self.verticalLayout.addLayout(self.verticalLayout_2)

        self.horizontalLayout.addWidget(self.vertLayoutWidget)

        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 820, 29))
        self.menubar.setObjectName("menubar")
        self.file_menu = QMenu(self.menubar)
        self.file_menu.setObjectName("menuLoad")

        # ------
        # File menu buttons
        self.file_load_action = QAction("Load", self)
        self.file_load_action.setShortcut("Ctrl+O")
        self.file_load_action.triggered.connect(self.button_load_level)
        self.file_menu.addAction(self.file_load_action)
        self.file_save_action = QAction("Save", self)
        self.file_save_action.setShortcut("Ctrl+S")
        self.file_save_action.triggered.connect(self.button_save_level)
        self.file_menu.addAction(self.file_save_action)
        self.file_save_as_action = QAction("Save As", self)
        self.file_save_as_action.setShortcut("Ctrl+Alt+S")
        self.file_save_as_action.triggered.connect(self.button_save_as_level)
        self.file_menu.addAction(self.file_save_as_action)

        # ------ Collision Menu
        self.collision_menu = QMenu(self.menubar)
        self.collision_menu.setObjectName("menuCollision")
        self.collision_load_action = QAction("Load .OBJ", self)
        self.collision_load_action.triggered.connect(
            self.button_load_collision)
        self.collision_menu.addAction(self.collision_load_action)
        self.collision_load_grid_action = QAction("Load GRID.BIN", self)
        self.collision_load_grid_action.triggered.connect(
            self.button_load_collision_grid)
        self.collision_menu.addAction(self.collision_load_grid_action)

        # ----- Set up menu bar and add the file menus
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.file_menu.menuAction())
        self.menubar.addAction(self.collision_menu.menuAction())
        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        self.file_menu.setTitle(_translate("MainWindow", "File"))
        self.button_add_waypoint.setText("Add Waypoint")
        self.button_connect_waypoints.setText("Connect Waypoint")
        self.button_delete_waypoints.setText("Delete Waypoint(s)")
        self.button_move_waypoints.setText("Move Waypoint(s)")
        self.button_ground_waypoints.setText("Ground Waypoint(s)")
        self.collision_menu.setTitle("Collision")
예제 #16
0
파일: ui_ucics.py 프로젝트: 892768447/ucics
    def setupUi(self, Ucics):
        size_280_650 = QSize(280, 650)
        size_20_20 = QSize(20, 20)
        size_25_25 = QSize(25, 25)
        Ucics.setObjectName("Ucics")
        Ucics.resize(size_280_650)    # 窗口大小
        Ucics.setMinimumSize(size_280_650)    # 设置最小大小
        Ucics.setMaximumSize(size_280_650)    # 设置最大大小
        Ucics.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)    # 无边框
        Ucics.setMouseTracking(True)    # 可拖动
        Ucics.setContextMenuPolicy(Qt.NoContextMenu)    # 禁止上下文菜单

        # 由于父QWidget无法通过样式设置背景
        # 所以这里把所有控件放到子QWidget中
        self.bgWidget = QWidget(Ucics)
        self.bgWidget.setObjectName("bgWidget")

        # 顶部标题图标 最小化 关闭
        self.topWidget = QWidget(self.bgWidget)
        self.topWidget.setMaximumHeight(25)
        self.topWidget.setObjectName("topWidget")
        # --布局
        topLayout = QHBoxLayout(self.topWidget)
        topLayout.setSpacing(1)
        topLayout.setContentsMargins(0, 0, 0, 0)
        topLayout.setObjectName("topLayout")
        # ----icon
        self.iconLabel = QLabel(self.bgWidget)
        self.iconLabel.setMinimumSize(size_25_25)
        self.iconLabel.setMaximumSize(size_25_25)
        self.iconLabel.setObjectName("iconLabel")
        # ----最小化按钮
        self.minButton = QPushButton(self.bgWidget)
        self.minButton.setMinimumSize(size_25_25)
        self.minButton.setMaximumSize(size_25_25)
        self.minButton.setObjectName("minButton")
        # ----关闭按钮
        self.closeButton = QPushButton(self.bgWidget)
        self.closeButton.setMinimumSize(size_25_25)
        self.closeButton.setMaximumSize(size_25_25)
        self.closeButton.setObjectName("closeButton")
        # ----添加到布局中
        topLayout.addWidget(self.iconLabel, 0, Qt.AlignLeft)
        topLayout.addWidget(self.minButton, 1, Qt.AlignRight)
        topLayout.addWidget(self.closeButton, 0, Qt.AlignRight)

        # 头像 昵称 心情 天气等
        self.headWidget = QWidget(self.bgWidget)
        self.headWidget.setMinimumHeight(90)
        self.headWidget.setMaximumHeight(90)
        self.headWidget.setObjectName("headWidget")
        # --布局
        headLayout = QHBoxLayout(self.headWidget)
        headLayout.setSpacing(6)
        headLayout.setContentsMargins(9, 20, 9, 6)
        headLayout.setObjectName("headLayout")
        # ----头像
        self.headLabel = QLabel(self.headWidget)
        self.headLabel.setMinimumWidth(60)
        self.headLabel.setMaximumWidth(60)
        self.headLabel.setToolTip("")
        self.headLabel.setCursor(QCursor(Qt.PointingHandCursor))
        self.headLabel.setObjectName("headLabel")
        # ----中间部分(昵称和签名等)
        self.headInfoWidget = QWidget(self.headWidget)
        self.headInfoWidget.setObjectName("headInfoWidget")
        # ------中间部分布局
        headInfoLayout = QVBoxLayout(self.headInfoWidget)
        headInfoLayout.setSpacing(1)
        headInfoLayout.setContentsMargins(0, 0, 0, 0)
        headInfoLayout.setObjectName("headInfoLayout")
        # --------昵称
        self.nameLabel = QLabel(self.headInfoWidget)
        self.nameLabel.setMinimumHeight(20)
        self.nameLabel.setMaximumHeight(20)
        self.nameLabel.setObjectName("nameLabel")
        # --------签名
        self.moodEdit = LineEdit(self.headInfoWidget)
        self.moodEdit.setMinimumHeight(20)
        self.moodEdit.setMaximumHeight(20)
        self.moodEdit.setFrame(False)    # 去掉边框
        # self.moodEdit.setClearButtonEnabled(True)    # 添加清除按钮
        self.moodEdit.setObjectName("moodEdit")
        # --------工具
        self.toolWidget = QWidget(self.headInfoWidget)
        self.toolWidget.setMinimumHeight(20)
        self.toolWidget.setMaximumHeight(20)
        self.toolWidget.setObjectName("toolWidget")
        # ----------工具布局
        toolLayout = QHBoxLayout(self.toolWidget)
        toolLayout.setSpacing(1)
        toolLayout.setContentsMargins(0, 0, 0, 0)
        toolLayout.setObjectName("toolLayout")
        # ------------空间
        self.qzoneButton = QPushButton(self.toolWidget)
        self.qzoneButton.setMinimumSize(size_20_20)
        self.qzoneButton.setMaximumSize(size_20_20)
        self.qzoneButton.setObjectName("qzoneButton")
        # ------------皮肤
        self.skinButton = QPushButton(self.toolWidget)
        self.skinButton.setMinimumSize(size_20_20)
        self.skinButton.setMaximumSize(size_20_20)
        self.skinButton.setObjectName("skinButton")
        # ------------添加到布局
        toolLayout.addWidget(self.qzoneButton, 0, Qt.AlignLeft)
        toolLayout.addWidget(self.skinButton, 1, Qt.AlignLeft)
        # --------添加到布局
        headInfoLayout.addWidget(self.nameLabel)
        headInfoLayout.addWidget(self.moodEdit)
        headInfoLayout.addWidget(self.toolWidget)
        # ----天气
        self.weatherLabel = QLabel(self.headWidget)
        self.weatherLabel.setMinimumWidth(60)
        self.weatherLabel.setMaximumWidth(60)
        self.weatherLabel.setCursor(QCursor(Qt.PointingHandCursor))
        self.weatherLabel.setObjectName("weatherLabel")
        # ----添加到布局中
        headLayout.addWidget(self.headLabel, 0, Qt.AlignLeft)
        headLayout.addWidget(self.headInfoWidget, 0, Qt.AlignCenter)
        headLayout.addWidget(self.weatherLabel, 0, Qt.AlignRight)

        # 搜索输入框
        self.searchEdit = LineEdit(self.bgWidget)
        self.searchEdit.setFrame(False)
        # self.searchEdit.setClearButtonEnabled(True)
        self.searchEdit.setObjectName("searchEdit")

        # tab
        self.tabWidget = QTabWidget(self.bgWidget)
        self.tabWidget.setUsesScrollButtons(False)    # 取消两个切换按钮
        self.tabWidget.setDocumentMode(True)    # 取消边框
        self.tabWidget.setObjectName("tabWidget")
        # --分组
        self.tabGroup = QWidget(self.tabWidget)
        self.tabGroup.setObjectName("tabGroup")
        # ----分组布局
        groupVerticalLayout = QVBoxLayout(self.tabGroup)
        groupVerticalLayout.setSpacing(0)
        groupVerticalLayout.setContentsMargins(0, 0, 0, 0)
        groupVerticalLayout.setObjectName("groupVerticalLayout")
        # ------分组list控件
        self.groupTreeWidget = QTreeWidget(self.tabGroup)
        self.groupTreeWidget.setFrameShape(QFrame.NoFrame)
        self.groupTreeWidget.setFrameStyle(QFrame.NoFrame)
        self.groupTreeWidget.setLineWidth(0)
        self.groupTreeWidget.setIndentation(0)
        self.groupTreeWidget.setRootIsDecorated(False)
        self.groupTreeWidget.setExpandsOnDoubleClick(False)
        self.groupTreeWidget.header().setVisible(False)
        self.groupTreeWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.groupTreeWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.groupTreeWidget.setObjectName("groupTreeWidget")
        # ----添加到布局
        groupVerticalLayout.addWidget(self.groupTreeWidget)
        # --历史
        self.tabHistory = QWidget(self.tabWidget)
        self.tabHistory.setObjectName("tabHistory")
        # ----历史布局
        historyVerticalLayout = QVBoxLayout(self.tabHistory)
        historyVerticalLayout.setSpacing(0)
        historyVerticalLayout.setContentsMargins(0, 0, 0, 0)
        historyVerticalLayout.setObjectName("historyVerticalLayout")
        # ------历史list控件
        self.historyTreeWidget = QTreeWidget(self.tabHistory)
        self.historyTreeWidget.setFrameShape(QFrame.NoFrame)
        self.historyTreeWidget.setFrameStyle(QFrame.NoFrame)
        self.historyTreeWidget.setLineWidth(0)
        self.historyTreeWidget.setIndentation(0)
        self.historyTreeWidget.setRootIsDecorated(False)
        self.historyTreeWidget.setExpandsOnDoubleClick(False)
        self.historyTreeWidget.header().setVisible(False)
        self.historyTreeWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.historyTreeWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.historyTreeWidget.setObjectName("historyTreeWidget")
        # ----添加到布局
        historyVerticalLayout.addWidget(self.historyTreeWidget)
        # 添加到tab中
        self.tabWidget.addTab(self.tabGroup, "")
        self.tabWidget.addTab(self.tabHistory, "")

        # 整体布局
        verticalLayout = QVBoxLayout(self.bgWidget)
        verticalLayout.setSpacing(0)
        verticalLayout.setContentsMargins(0, 0, 0, 0)
        verticalLayout.setObjectName("verticalLayout")
        verticalLayout.addWidget(self.topWidget)
        verticalLayout.addWidget(self.headWidget)
        verticalLayout.addWidget(self.searchEdit)
        verticalLayout.addWidget(self.tabWidget)

        # bg
        layout = QVBoxLayout(Ucics)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.bgWidget)

        # 初始化一些设置
        _translate = QCoreApplication.translate
        Ucics.setWindowTitle(_translate("Ucics", "UCICS"))
        self.tabWidget.setCurrentIndex(0)
        self.tabWidget.setTabToolTip(self.tabWidget.indexOf(self.tabGroup), _translate("tabGroup", "分组"))
        self.tabWidget.setTabToolTip(self.tabWidget.indexOf(self.tabHistory), _translate("tabHistory", "历史"))
        QMetaObject.connectSlotsByName(Ucics)
예제 #17
0
class ControlWidget(QWidget):
    
    
    def __init__(self,winParent):      
        super(ControlWidget, self).__init__()
        self.winParent=winParent

        self.rgbdwn = RGBMIN
        self.rgbup = RGBMAX
        self.hsvdwn = HSVMIN
        self.hsvup = HSVMAX
        self.yuvdwn = YUVMIN
        self.yuvup = YUVMAX
        self.initUI()
        
    def initUI(self):

        #self.setMinimumSize(WIDTH,HEIGTH)
        #self.setMaximumSize(WIDTH,HEIGTH)

        '''Radio buttons for Original/RGB/HSV/YUV images'''
        self.origButton = QRadioButton("Original")
        self.rgbButton = QRadioButton("RGB")
        self.hsvButton = QRadioButton("HSV")
        self.yuvButton = QRadioButton("YUV")

        '''Signals for toggled radio buttons'''
        self.origButton.toggled.connect(lambda:self.origButtonState())       
        self.rgbButton.toggled.connect(lambda:self.rgbButtonState())
        self.hsvButton.toggled.connect(lambda:self.hsvButtonState())
        self.yuvButton.toggled.connect(lambda:self.yuvButtonState())

        self.origButton.setChecked(True)

        '''Main layout of the widget will contain several vertical layouts'''
        self.gLayout = QGridLayout(self)
        self.gLayout.setObjectName("gLayout")

        ''' Vertical Layout for radio buttons '''
        self.radioLayout = QVBoxLayout()
        self.radioLayout.setObjectName("radioLayout")
        self.radioLayout.addWidget(self.origButton)
        self.radioLayout.addWidget(self.rgbButton)
        self.radioLayout.addWidget(self.hsvButton)
        self.radioLayout.addWidget(self.yuvButton)
        self.vSpacer = QSpacerItem(30, 20, QSizePolicy.Ignored, QSizePolicy.Ignored);
        self.radioLayout.addItem(self.vSpacer)
        
        hmin,smin,vmin = HSVMIN
        hmax,smax,vmax = HSVMAX
        ''' Vertical Layout for HMIN Slider''' 
        self.hminLayout = QVBoxLayout()
        self.hminLayout.setObjectName("hminLayout")
        self.hminLabel = QLabel("HMin")
        self.hminValue = QLineEdit(str(hmin),self)
        self.hminValue.setValidator(QIntValidator(hmin, hmax, self));
        self.hminValue.setFixedWidth(40)
        self.hminValue.setFixedHeight(27)
        self.hminValue.setAlignment(Qt.AlignCenter);
        self.hminSlider = QSlider(Qt.Vertical)
        self.hminSlider.setMinimum(hmin)
        self.hminSlider.setMaximum(hmax)
        self.hminSlider.setValue(hmin)
        self.hminLayout.addWidget(self.hminLabel, Qt.AlignCenter)
        self.hminLayout.addWidget(self.hminValue,Qt.AlignCenter)
        self.hminLayout.addWidget(self.hminSlider)
        

        ''' Vertical Layout for HMAX Slider''' 
        self.hmaxLayout = QVBoxLayout()
        self.hmaxLayout.setObjectName("hmaxLayout")
        self.hmaxLabel = QLabel("HMax")
        self.hmaxValue = QLineEdit(str(hmax),self)
        self.hmaxValue.setValidator(QIntValidator(hmin, hmax, self));
        self.hmaxValue.setFixedWidth(40)
        self.hmaxValue.setFixedHeight(27)
        self.hmaxValue.setAlignment(Qt.AlignCenter);
        self.hmaxSlider = QSlider(Qt.Vertical)
        self.hmaxSlider.setMinimum(hmin)
        self.hmaxSlider.setMaximum(hmax)
        self.hmaxSlider.setValue(hmax)
        self.hmaxLayout.addWidget(self.hmaxLabel)
        self.hmaxLayout.addWidget(self.hmaxValue)
        self.hmaxLayout.addWidget(self.hmaxSlider)

        ''' Vertical Layout for SMIN Slider'''
        self.sminLayout = QVBoxLayout()
        self.sminLayout.setObjectName("sminLayout")
        self.sminLabel = QLabel("SMin")
        self.sminValue = QLineEdit(str(smin),self)
        self.sminValue.setValidator(QIntValidator(smin, smax, self));
        self.sminValue.setFixedWidth(40)
        self.sminValue.setFixedHeight(27)
        self.sminValue.setAlignment(Qt.AlignCenter);
        self.sminSlider = QSlider(Qt.Vertical)
        self.sminSlider.setMinimum(smin)
        self.sminSlider.setMaximum(smax)
        self.sminSlider.setValue(smin)
        self.sminLayout.addWidget(self.sminLabel)
        self.sminLayout.addWidget(self.sminValue)
        self.sminLayout.addWidget(self.sminSlider)

        ''' Vertical Layout for SMAX Slider'''
        self.smaxLayout = QVBoxLayout()
        self.smaxLayout.setObjectName("smaxLayout")
        self.smaxLabel = QLabel("SMax")
        self.smaxValue = QLineEdit(str(smax),self)
        self.smaxValue.setValidator(QIntValidator(smin, smax, self));
        self.smaxValue.setFixedWidth(40)
        self.smaxValue.setFixedHeight(27)
        self.smaxValue.setAlignment(Qt.AlignCenter);
        self.smaxSlider = QSlider(Qt.Vertical)
        self.smaxSlider.setMinimum(smin)
        self.smaxSlider.setMaximum(smax)
        self.smaxSlider.setValue(smax)
        self.smaxLayout.addWidget(self.smaxLabel)
        self.smaxLayout.addWidget(self.smaxValue)
        self.smaxLayout.addWidget(self.smaxSlider)

        ''' Vertical Layout for VMIN Slider'''
        self.vminLayout = QVBoxLayout()
        self.vminLayout.setObjectName("vminLayout")
        self.vminLabel = QLabel("VMin")
        self.vminValue = QLineEdit(str(vmin),self)
        self.vminValue.setValidator(QIntValidator(vmin, vmax, self));
        self.vminValue.setFixedWidth(40)
        self.vminValue.setFixedHeight(27)
        self.vminValue.setAlignment(Qt.AlignCenter);
        self.vminSlider = QSlider(Qt.Vertical)
        self.vminSlider.setMinimum(vmin)
        self.vminSlider.setMaximum(vmax)
        self.vminSlider.setValue(vmin)
        self.vminLayout.addWidget(self.vminLabel)
        self.vminLayout.addWidget(self.vminValue)
        self.vminLayout.addWidget(self.vminSlider)

        ''' Vertical Layout for VMAX Slider'''
        self.vmaxLayout = QVBoxLayout()
        self.vmaxLayout.setObjectName("vmaxLayout")
        self.vmaxLabel = QLabel("VMax")
        self.vmaxValue = QLineEdit(str(vmax),self)
        self.vmaxValue.setValidator(QIntValidator(vmin, vmax, self));
        self.vmaxValue.setFixedWidth(40)
        self.vmaxValue.setFixedHeight(27)
        self.vmaxValue.setAlignment(Qt.AlignCenter);
        self.vmaxSlider = QSlider(Qt.Vertical)
        self.vmaxSlider.setMinimum(vmin)
        self.vmaxSlider.setMaximum(vmax)
        self.vmaxSlider.setValue(vmax)
        self.vmaxLayout.addWidget(self.vmaxLabel)
        self.vmaxLayout.addWidget(self.vmaxValue)
        self.vmaxLayout.addWidget(self.vmaxSlider)
    
        '''Adding all the vertical layouts to the main horizontal layout'''
        self.gLayout.addLayout(self.radioLayout,1,0,1,6,Qt.AlignCenter)
        self.gLayout.addLayout(self.hminLayout,2,0,Qt.AlignCenter)
        self.gLayout.addLayout(self.hmaxLayout,2,1,Qt.AlignCenter)
        self.gLayout.addLayout(self.sminLayout,2,2,Qt.AlignCenter)
        self.gLayout.addLayout(self.smaxLayout,2,3,Qt.AlignCenter)
        self.gLayout.addLayout(self.vminLayout,2,4,Qt.AlignCenter)
        self.gLayout.addLayout(self.vmaxLayout,2,5,Qt.AlignCenter)
        self.setLayout(self.gLayout)


        '''Signals for sliders value changes'''
        self.hminSlider.valueChanged.connect(self.changeHmin)     
        self.hmaxSlider.valueChanged.connect(self.changeHmax)
        self.sminSlider.valueChanged.connect(self.changeSmin)     
        self.smaxSlider.valueChanged.connect(self.changeSmax)
        self.vminSlider.valueChanged.connect(self.changeVmin)     
        self.vmaxSlider.valueChanged.connect(self.changeVmax)

        self.hminValue.textChanged.connect(self.changeHmin2)
        self.hmaxValue.textChanged.connect(self.changeHmax2)
        self.sminValue.textChanged.connect(self.changeSmin2)
        self.smaxValue.textChanged.connect(self.changeSmax2)
        self.vminValue.textChanged.connect(self.changeVmin2)
        self.vmaxValue.textChanged.connect(self.changeVmax2)

        

    #Show filtered image. Don't manually disable radio button, API does it for you!
    '''Methods for showing images depending on the current checked radio button'''
    def origButtonState(self):
        if self.origButton.isChecked():
            self.winParent.setFilterName('Orig')
            

    def rgbButtonState(self):
        if self.rgbButton.isChecked():
            self.winParent.setFilterName('RGB')

            rmin,gmin,bmin = RGBMIN
            rmax,gmax,bmax = RGBMAX
            print(RGBMAX)
            rd, gd, bd = self.rgbdwn
            ru, gu, bu = self.rgbup
            self.hminLabel.setText('Rmin')
            self.hminValue.setText(str(rd))
            self.hminValue.setValidator(QIntValidator(rmin, rmax, self));
            self.hminSlider.setMinimum(rmin)
            self.hminSlider.setMaximum(rmax)
            self.hminSlider.setValue(rd)

            self.hmaxLabel.setText("RMax")
            self.hmaxValue.setText(str(ru))
            self.hmaxValue.setValidator(QIntValidator(rmin, rmax, self));
            self.hmaxSlider.setMinimum(rmin)
            self.hmaxSlider.setMaximum(rmax)
            self.hmaxSlider.setValue(ru)

            self.sminLabel.setText("GMin")
            self.sminValue.setText(str(gd))
            self.sminValue.setValidator(QIntValidator(gmin, gmax, self));
            self.sminSlider.setMinimum(gmin)
            self.sminSlider.setMaximum(gmax)
            self.sminSlider.setValue(gd)

            self.smaxLabel.setText("GMax")
            self.smaxValue.setText(str(gu))
            self.smaxValue.setValidator(QIntValidator(gmin, gmax, self));
            self.smaxSlider.setMinimum(gmin)
            self.smaxSlider.setMaximum(gmax)
            self.smaxSlider.setValue(gu)

            self.vminLabel.setText("BMin")
            self.vminValue.setText(str(bd))
            self.vminValue.setValidator(QIntValidator(bmin, bmax, self));
            self.vminSlider.setMinimum(bmin)
            self.vminSlider.setMaximum(bmax)
            self.vminSlider.setValue(bd)

            self.vmaxLabel.setText("BMax")
            self.vmaxValue.setText(str(bu))
            self.vmaxValue.setValidator(QIntValidator(bmin, bmax, self));
            self.vmaxSlider.setMinimum(bmin)
            self.vmaxSlider.setMaximum(bmax)
            self.vmaxSlider.setValue(bu)

            

    def hsvButtonState(self):
        if self.hsvButton.isChecked():
            self.winParent.setFilterName('HSV')

            hmin,smin,vmin = HSVMIN
            hmax,smax,vmax = HSVMAX

            hd, sd, vd = self.hsvdwn
            hu, su, vu = self.hsvup
            
            self.hminLabel.setText("HMin")
            self.hminValue.setText(str(hd))
            self.hminValue.setValidator(QIntValidator(hmin, hmax, self));
            self.hminSlider.setMinimum(hmin)
            self.hminSlider.setMaximum(hmax)
            self.hminSlider.setValue(hd)

            self.hmaxLabel.setText("HMax")
            self.hmaxValue.setText(str(hu))
            self.hmaxValue.setValidator(QIntValidator(hmin, hmax, self));
            self.hmaxSlider.setMinimum(hmin)
            self.hmaxSlider.setMaximum(hmax)
            self.hmaxSlider.setValue(hu)

            self.sminLabel.setText("SMin")
            self.sminValue.setText(str(sd))
            self.sminValue.setValidator(QIntValidator(smin, smax, self));
            self.sminSlider.setMinimum(smin)
            self.sminSlider.setMaximum(smax)
            self.sminSlider.setValue(sd)

            self.smaxLabel.setText("SMax")
            self.smaxValue.setText(str(su))
            self.smaxValue.setValidator(QIntValidator(smin, smax, self)); 
            self.smaxSlider.setMinimum(smin)
            self.smaxSlider.setMaximum(smax)
            self.smaxSlider.setValue(su)

            self.vminLabel.setText("VMin")
            self.vminValue.setText(str(vd))
            self.vminValue.setValidator(QIntValidator(vmin, vmax, self));
            self.vminSlider.setMinimum(vmin)
            self.vminSlider.setMaximum(vmax)
            self.vminSlider.setValue(vd)

            self.vmaxLabel.setText("VMax")
            self.vmaxValue.setText(str(vu))
            self.vmaxValue.setValidator(QIntValidator(vmin, vmax, self));
            self.vmaxSlider.setMinimum(vmin)
            self.vmaxSlider.setMaximum(vmax)
            self.vmaxSlider.setValue(vu)
            

    def yuvButtonState(self):
        if self.yuvButton.isChecked():  
            self.winParent.setFilterName('YUV')

            ymin,umin,vmin = YUVMIN
            ymax,umax,vmax = YUVMAX

            yd, ud, vd = self.yuvdwn
            yu, uu, vu = self.yuvup
            
            self.hminLabel.setText("YMin")
            self.hminValue.setText(str(yd))
            self.hminValue.setValidator(QIntValidator(ymin, ymax, self));
            self.hminSlider.setMinimum(ymin)
            self.hminSlider.setMaximum(ymax)
            self.hminSlider.setValue(yd)

            self.hmaxLabel.setText("YMax")
            self.hmaxValue.setText(str(yu))
            self.hmaxValue.setValidator(QIntValidator(ymin, ymax, self));
            self.hmaxSlider.setMinimum(ymin)
            self.hmaxSlider.setMaximum(ymax)
            self.hmaxSlider.setValue(yu)

            self.sminLabel.setText("UMin")
            self.sminValue.setText(str(ud))
            self.sminValue.setValidator(QIntValidator(umin, umax, self));
            self.sminSlider.setMinimum(umin)
            self.sminSlider.setMaximum(umax)
            self.sminSlider.setValue(ud)

            self.smaxLabel.setText("UMax")
            self.smaxValue.setText(str(uu))
            self.smaxValue.setValidator(QIntValidator(umin, umax, self));
            self.smaxSlider.setMinimum(umin)
            self.smaxSlider.setMaximum(umax)
            self.smaxSlider.setValue(uu)

            self.vminLabel.setText("VMin")
            self.vminValue.setText(str(vd))
            self.vminValue.setValidator(QIntValidator(vmin, vmax, self));
            self.vminSlider.setMinimum(vmin)
            self.vminSlider.setMaximum(vmax)
            self.vminSlider.setValue(vd)

            self.vmaxLabel.setText("VMax")
            self.vmaxValue.setText(str(vu))
            self.vmaxValue.setValidator(QIntValidator(vmin, vmax, self));
            self.vmaxSlider.setMinimum(vmin)
            self.vmaxSlider.setMaximum(vmax)
            self.vmaxSlider.setValue(vu)

    '''Methods to get the slider value and update value labels'''
    def changeHmin(self):
        value = self.hminSlider.value()
        if self.hsvButton.isChecked():
            self.hsvdwn[0] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[0] = value
        elif self.yuvButton.isChecked():
            value = self.hminSlider.value()
            self.yuvdwn[0] = value
        self.hminValue.setText(str(value))
        self.setMIN()

    def changeHmin2(self):
        v = self.hminValue.text()
        if v == None or v == "":
            value = 0
        else:
            value = int(v)
        if self.hsvButton.isChecked():
            self.hsvdwn[0] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[0] = value
        elif self.yuvButton.isChecked():
            value = self.hminSlider.value()
            self.yuvdwn[0] = value
        self.hminSlider.setValue(value)
        self.setMIN()    

    def changeHmax(self):
        value = self.hmaxSlider.value()
        if self.hsvButton.isChecked():
            self.hsvup[0] = value
        elif self.rgbButton.isChecked():
            self.rgbup[0] = value
        elif self.yuvButton.isChecked():
            self.yuvup[0] = value

        self.hmaxValue.setText(str(value))
        self.setMAX()

    def changeHmax2(self):
        v = self.hmaxValue.text()
        if v == None or v == "":
            value = 0
        else:
            value = int(v)
        if self.hsvButton.isChecked():
            self.hsvup[0] = value
        elif self.rgbButton.isChecked():
            self.rgbup[0] = value
        elif self.yuvButton.isChecked():
            value = self.hmaxSlider.value()
            self.yuvup[0] = value
        self.hmaxSlider.setValue(value)
        self.setMAX()

    def changeSmin(self):
        value = self.sminSlider.value()
        if self.hsvButton.isChecked():
            self.hsvdwn[1] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[1] = value
        elif self.yuvButton.isChecked():
            self.yuvdwn[1] = value

        self.sminValue.setText(str(value))
        self.setMIN()

    def changeSmin2(self):
        v = self.sminValue.text()
        if v == None or v == "":
            value = 0
        else:
            value = int(v)
        if self.hsvButton.isChecked():
            self.hsvdwn[1] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[1] = value
        elif self.yuvButton.isChecked():
            value = self.hminSlider.value()
            self.yuvdwn[1] = value
        self.sminSlider.setValue(value)
        self.setMIN()

    def changeSmax(self):
        value = self.smaxSlider.value()
        if self.hsvButton.isChecked():
            self.hsvup[1] = value
        elif self.rgbButton.isChecked():
            self.rgbup[1] = value
        elif self.yuvButton.isChecked():
            self.yuvup[1] = value

        self.smaxValue.setText(str(value))
        self.setMAX()

    def changeSmax2(self):
        v = self.smaxValue.text()
        if v == None or v == "":
            value = 0
        else:
            value = int(v)
        if self.hsvButton.isChecked():
            self.hsvup[1] = value
        elif self.rgbButton.isChecked():
            self.rgbup[1] = value
        elif self.yuvButton.isChecked():
            value = self.hmaxSlider.value()
            self.yuvup[1] = value
        self.smaxSlider.setValue(value)
        self.setMAX()

    def changeVmin(self):
        value = self.vminSlider.value()
        if self.hsvButton.isChecked():
            self.hsvdwn[2] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[2] = value
        elif self.yuvButton.isChecked():
            self.yuvdwn[2] = value

        self.vminValue.setText(str(value))
        self.setMIN()

    def changeVmin2(self):
        v = self.vminValue.text()
        if v == None or v == "":
            value = 0
        else:
            value = int(v)
        if self.hsvButton.isChecked():
            self.hsvdwn[2] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[2] = value
        elif self.yuvButton.isChecked():
            value = self.hminSlider.value()
            self.yuvdwn[2] = value
        self.vminSlider.setValue(value)
        self.setMIN()

    def changeVmax(self):
        value = self.vmaxSlider.value()
        if self.hsvButton.isChecked():
            self.hsvup[2] = value
        elif self.rgbButton.isChecked():
            self.rgbup[2] = value
        elif self.yuvButton.isChecked():
            self.yuvup[2] = value

        self.vmaxValue.setText(str(value))
        self.setMAX()

    def changeVmax2(self):
        v = self.vmaxValue.text()
        if v == None or v == "":
            value = 0
        else:
            value = int(v)
        if self.hsvButton.isChecked():
            self.hsvup[2] = value
        elif self.rgbButton.isChecked():
            self.rgbup[2] = value
        elif self.yuvButton.isChecked():
            value = self.hmaxSlider.value()
            self.yuvup[2] = value
        self.vmaxSlider.setValue(value)
        self.setMAX()

    def setMAX (self):

        filt = self.winParent.getFilterName()
        if self.hsvButton.isChecked():
            h, s, v = self.hsvup
            self.winParent.getCamera().getFilter(filt).setUpLimit(h,s,v)
        elif self.rgbButton.isChecked():
            h, s, v = self.rgbup
            print "max", h,s,v
            self.winParent.getCamera().getFilter(filt).setUpLimit(h,s,v)
        elif self.yuvButton.isChecked():
            h, s, v = self.yuvup
            self.winParent.getCamera().getFilter(filt).setUpLimit(h,s,v)


    def setMIN (self):
        filt = self.winParent.getFilterName()
        if self.hsvButton.isChecked():
            h, s, v = self.hsvdwn
            self.winParent.getCamera().getFilter(filt).setDownLimit(h,s,v)
        elif self.rgbButton.isChecked():
            h, s, v = self.rgbdwn
            print "min", h,s,v
            self.winParent.getCamera().getFilter(filt).setDownLimit(h,s,v)
        elif self.yuvButton.isChecked():
            h, s, v = self.yuvdwn
            self.winParent.getCamera().getFilter(filt).setDownLimit(h,s,v)

  

    '''Close event, for finalize the program'''
    def closeEvent(self, event):
        self.winParent.closeimagesWidget()
예제 #18
0
class UIPreviewer(E5MainWindow):
    """
    Class implementing the UI Previewer main window.
    """
    def __init__(self, filename=None, parent=None, name=None):
        """
        Constructor
        
        @param filename name of a UI file to load
        @param parent parent widget of this window (QWidget)
        @param name name of this window (string)
        """
        self.mainWidget = None
        self.currentFile = QDir.currentPath()

        super(UIPreviewer, self).__init__(parent)
        if not name:
            self.setObjectName("UIPreviewer")
        else:
            self.setObjectName(name)

        self.setStyle(Preferences.getUI("Style"),
                      Preferences.getUI("StyleSheet"))

        self.resize(QSize(600, 480).expandedTo(self.minimumSizeHint()))
        self.statusBar()

        self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
        self.setWindowTitle(self.tr("UI Previewer"))

        self.cw = QWidget(self)
        self.cw.setObjectName("centralWidget")

        self.UIPreviewerLayout = QVBoxLayout(self.cw)
        self.UIPreviewerLayout.setContentsMargins(6, 6, 6, 6)
        self.UIPreviewerLayout.setSpacing(6)
        self.UIPreviewerLayout.setObjectName("UIPreviewerLayout")

        self.styleLayout = QHBoxLayout()
        self.styleLayout.setContentsMargins(0, 0, 0, 0)
        self.styleLayout.setSpacing(6)
        self.styleLayout.setObjectName("styleLayout")

        self.styleLabel = QLabel(self.tr("Select GUI Theme"), self.cw)
        self.styleLabel.setObjectName("styleLabel")
        self.styleLayout.addWidget(self.styleLabel)

        self.styleCombo = QComboBox(self.cw)
        self.styleCombo.setObjectName("styleCombo")
        self.styleCombo.setEditable(False)
        self.styleCombo.setToolTip(self.tr("Select the GUI Theme"))
        self.styleLayout.addWidget(self.styleCombo)
        self.styleCombo.addItems(sorted(QStyleFactory().keys()))
        currentStyle = Preferences.Prefs.settings.value('UIPreviewer/style')
        if currentStyle is not None:
            self.styleCombo.setCurrentIndex(int(currentStyle))

        styleSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.styleLayout.addItem(styleSpacer)
        self.UIPreviewerLayout.addLayout(self.styleLayout)

        self.previewSV = QScrollArea(self.cw)
        self.previewSV.setObjectName("preview")
        self.previewSV.setFrameShape(QFrame.NoFrame)
        self.previewSV.setFrameShadow(QFrame.Plain)
        self.previewSV.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
        self.UIPreviewerLayout.addWidget(self.previewSV)

        self.setCentralWidget(self.cw)

        self.styleCombo.activated[str].connect(self.__guiStyleSelected)

        self.__initActions()
        self.__initMenus()
        self.__initToolbars()

        self.__updateActions()

        # defere loading of a UI file until we are shown
        self.fileToLoad = filename

    def show(self):
        """
        Public slot to show this dialog.
        
        This overloaded slot loads a UI file to be previewed after
        the main window has been shown. This way, previewing a dialog
        doesn't interfere with showing the main window.
        """
        super(UIPreviewer, self).show()
        if self.fileToLoad is not None:
            fn, self.fileToLoad = (self.fileToLoad, None)
            self.__loadFile(fn)

    def __initActions(self):
        """
        Private method to define the user interface actions.
        """
        self.openAct = QAction(UI.PixmapCache.getIcon("openUI.png"),
                               self.tr('&Open File'), self)
        self.openAct.setShortcut(QKeySequence(self.tr("Ctrl+O", "File|Open")))
        self.openAct.setStatusTip(self.tr('Open a UI file for display'))
        self.openAct.setWhatsThis(
            self.tr("""<b>Open File</b>"""
                    """<p>This opens a new UI file for display.</p>"""))
        self.openAct.triggered.connect(self.__openFile)

        self.printAct = QAction(UI.PixmapCache.getIcon("print.png"),
                                self.tr('&Print'), self)
        self.printAct.setShortcut(QKeySequence(self.tr("Ctrl+P",
                                                       "File|Print")))
        self.printAct.setStatusTip(self.tr('Print a screen capture'))
        self.printAct.setWhatsThis(
            self.tr("""<b>Print</b>"""
                    """<p>Print a screen capture.</p>"""))
        self.printAct.triggered.connect(self.__printImage)

        self.printPreviewAct = QAction(
            UI.PixmapCache.getIcon("printPreview.png"),
            self.tr('Print Preview'), self)
        self.printPreviewAct.setStatusTip(
            self.tr('Print preview a screen capture'))
        self.printPreviewAct.setWhatsThis(
            self.tr("""<b>Print Preview</b>"""
                    """<p>Print preview a screen capture.</p>"""))
        self.printPreviewAct.triggered.connect(self.__printPreviewImage)

        self.imageAct = QAction(UI.PixmapCache.getIcon("screenCapture.png"),
                                self.tr('&Screen Capture'), self)
        self.imageAct.setShortcut(
            QKeySequence(self.tr("Ctrl+S", "File|Screen Capture")))
        self.imageAct.setStatusTip(
            self.tr('Save a screen capture to an image file'))
        self.imageAct.setWhatsThis(
            self.tr("""<b>Screen Capture</b>"""
                    """<p>Save a screen capture to an image file.</p>"""))
        self.imageAct.triggered.connect(self.__saveImage)

        self.exitAct = QAction(UI.PixmapCache.getIcon("exit.png"),
                               self.tr('&Quit'), self)
        self.exitAct.setShortcut(QKeySequence(self.tr("Ctrl+Q", "File|Quit")))
        self.exitAct.setStatusTip(self.tr('Quit the application'))
        self.exitAct.setWhatsThis(
            self.tr("""<b>Quit</b>"""
                    """<p>Quit the application.</p>"""))
        self.exitAct.triggered.connect(qApp.closeAllWindows)

        self.copyAct = QAction(UI.PixmapCache.getIcon("editCopy.png"),
                               self.tr('&Copy'), self)
        self.copyAct.setShortcut(QKeySequence(self.tr("Ctrl+C", "Edit|Copy")))
        self.copyAct.setStatusTip(self.tr('Copy screen capture to clipboard'))
        self.copyAct.setWhatsThis(
            self.tr("""<b>Copy</b>"""
                    """<p>Copy screen capture to clipboard.</p>"""))
        self.copyAct.triggered.connect(self.__copyImageToClipboard)

        self.whatsThisAct = QAction(UI.PixmapCache.getIcon("whatsThis.png"),
                                    self.tr('&What\'s This?'), self)
        self.whatsThisAct.setShortcut(QKeySequence(self.tr("Shift+F1")))
        self.whatsThisAct.setStatusTip(self.tr('Context sensitive help'))
        self.whatsThisAct.setWhatsThis(
            self.
            tr("""<b>Display context sensitive help</b>"""
               """<p>In What's This? mode, the mouse cursor shows an arrow"""
               """ with a question mark, and you can click on the interface"""
               """ elements to get a short description of what they do and"""
               """ how to use them. In dialogs, this feature can be accessed"""
               """ using the context help button in the titlebar.</p>"""))
        self.whatsThisAct.triggered.connect(self.__whatsThis)

        self.aboutAct = QAction(self.tr('&About'), self)
        self.aboutAct.setStatusTip(
            self.tr('Display information about this software'))
        self.aboutAct.setWhatsThis(
            self.tr(
                """<b>About</b>"""
                """<p>Display some information about this software.</p>"""))
        self.aboutAct.triggered.connect(self.__about)

        self.aboutQtAct = QAction(self.tr('About &Qt'), self)
        self.aboutQtAct.setStatusTip(
            self.tr('Display information about the Qt toolkit'))
        self.aboutQtAct.setWhatsThis(
            self.tr(
                """<b>About Qt</b>"""
                """<p>Display some information about the Qt toolkit.</p>"""))
        self.aboutQtAct.triggered.connect(self.__aboutQt)

    def __initMenus(self):
        """
        Private method to create the menus.
        """
        mb = self.menuBar()

        menu = mb.addMenu(self.tr('&File'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.openAct)
        menu.addAction(self.imageAct)
        menu.addSeparator()
        menu.addAction(self.printPreviewAct)
        menu.addAction(self.printAct)
        menu.addSeparator()
        menu.addAction(self.exitAct)

        menu = mb.addMenu(self.tr("&Edit"))
        menu.setTearOffEnabled(True)
        menu.addAction(self.copyAct)

        mb.addSeparator()

        menu = mb.addMenu(self.tr('&Help'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.aboutAct)
        menu.addAction(self.aboutQtAct)
        menu.addSeparator()
        menu.addAction(self.whatsThisAct)

    def __initToolbars(self):
        """
        Private method to create the toolbars.
        """
        filetb = self.addToolBar(self.tr("File"))
        filetb.setIconSize(UI.Config.ToolBarIconSize)
        filetb.addAction(self.openAct)
        filetb.addAction(self.imageAct)
        filetb.addSeparator()
        filetb.addAction(self.printPreviewAct)
        filetb.addAction(self.printAct)
        filetb.addSeparator()
        filetb.addAction(self.exitAct)

        edittb = self.addToolBar(self.tr("Edit"))
        edittb.setIconSize(UI.Config.ToolBarIconSize)
        edittb.addAction(self.copyAct)

        helptb = self.addToolBar(self.tr("Help"))
        helptb.setIconSize(UI.Config.ToolBarIconSize)
        helptb.addAction(self.whatsThisAct)

    def __whatsThis(self):
        """
        Private slot called in to enter Whats This mode.
        """
        QWhatsThis.enterWhatsThisMode()

    def __guiStyleSelected(self, selectedStyle):
        """
        Private slot to handle the selection of a GUI style.
        
        @param selectedStyle name of the selected style (string)
        """
        if self.mainWidget:
            self.__updateChildren(selectedStyle)

    def __about(self):
        """
        Private slot to show the about information.
        """
        E5MessageBox.about(
            self, self.tr("UI Previewer"),
            self.tr(
                """<h3> About UI Previewer </h3>"""
                """<p>The UI Previewer loads and displays Qt User-Interface"""
                """ files with various styles, which are selectable via a"""
                """ selection list.</p>"""))

    def __aboutQt(self):
        """
        Private slot to show info about Qt.
        """
        E5MessageBox.aboutQt(self, self.tr("UI Previewer"))

    def __openFile(self):
        """
        Private slot to load a new file.
        """
        fn = E5FileDialog.getOpenFileName(
            self, self.tr("Select UI file"), self.currentFile,
            self.tr("Qt User-Interface Files (*.ui)"))
        if fn:
            self.__loadFile(fn)

    def __loadFile(self, fn):
        """
        Private slot to load a ui file.
        
        @param fn name of the ui file to be laoded (string)
        """
        if self.mainWidget:
            self.mainWidget.close()
            self.previewSV.takeWidget()
            del self.mainWidget
            self.mainWidget = None

        # load the file
        try:
            self.mainWidget = uic.loadUi(fn)
        except Exception:
            pass

        if self.mainWidget:
            self.currentFile = fn
            self.__updateChildren(self.styleCombo.currentText())
            if (isinstance(self.mainWidget, QDialog)
                    or isinstance(self.mainWidget, QMainWindow)):
                self.mainWidget.show()
                self.mainWidget.installEventFilter(self)
            else:
                self.previewSV.setWidget(self.mainWidget)
                self.mainWidget.show()
        else:
            E5MessageBox.warning(
                self, self.tr("Load UI File"),
                self.tr("""<p>The file <b>{0}</b> could not be loaded.</p>""").
                format(fn))
        self.__updateActions()

    def __updateChildren(self, sstyle):
        """
        Private slot to change the style of the show UI.
        
        @param sstyle name of the selected style (string)
        """
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        qstyle = QStyleFactory.create(sstyle)
        self.mainWidget.setStyle(qstyle)

        lst = self.mainWidget.findChildren(QWidget)
        for obj in lst:
            try:
                obj.setStyle(qstyle)
            except AttributeError:
                pass
        del lst

        self.mainWidget.hide()
        self.mainWidget.show()

        self.lastQStyle = qstyle
        self.lastStyle = sstyle
        Preferences.Prefs.settings.setValue('UIPreviewer/style',
                                            self.styleCombo.currentIndex())
        QApplication.restoreOverrideCursor()

    def __updateActions(self):
        """
        Private slot to update the actions state.
        """
        if self.mainWidget:
            self.imageAct.setEnabled(True)
            self.printAct.setEnabled(True)
            if self.printPreviewAct:
                self.printPreviewAct.setEnabled(True)
            self.copyAct.setEnabled(True)
            self.styleCombo.setEnabled(True)
        else:
            self.imageAct.setEnabled(False)
            self.printAct.setEnabled(False)
            if self.printPreviewAct:
                self.printPreviewAct.setEnabled(False)
            self.copyAct.setEnabled(False)
            self.styleCombo.setEnabled(False)

    def __handleCloseEvent(self):
        """
        Private slot to handle the close event of a viewed QMainWidget.
        """
        if self.mainWidget:
            self.mainWidget.removeEventFilter(self)
            del self.mainWidget
            self.mainWidget = None
        self.__updateActions()

    def eventFilter(self, obj, ev):
        """
        Public method called to filter an event.
        
        @param obj object, that generated the event (QObject)
        @param ev the event, that was generated by object (QEvent)
        @return flag indicating if event was filtered out
        """
        if obj == self.mainWidget:
            if ev.type() == QEvent.Close:
                self.__handleCloseEvent()
            return True
        else:
            if isinstance(self.mainWidget, QDialog):
                return QDialog.eventFilter(self, obj, ev)
            elif isinstance(self.mainWidget, QMainWindow):
                return QMainWindow.eventFilter(self, obj, ev)
            else:
                return False

    def __saveImage(self):
        """
        Private slot to handle the Save Image menu action.
        """
        if self.mainWidget is None:
            E5MessageBox.critical(self, self.tr("Save Image"),
                                  self.tr("""There is no UI file loaded."""))
            return

        defaultExt = "PNG"
        filters = ""
        formats = QImageWriter.supportedImageFormats()
        for imageFormat in formats:
            filters = "{0}*.{1} ".format(filters,
                                         bytes(imageFormat).decode().lower())
        fileFilter = self.tr("Images ({0})").format(filters[:-1])

        fname = E5FileDialog.getSaveFileName(self, self.tr("Save Image"), "",
                                             fileFilter)
        if not fname:
            return

        ext = QFileInfo(fname).suffix().upper()
        if not ext:
            ext = defaultExt
            fname.append(".{0}".format(defaultExt.lower()))

        pix = self.mainWidget.grab()
        self.__updateChildren(self.lastStyle)
        if not pix.save(fname, str(ext)):
            E5MessageBox.critical(
                self, self.tr("Save Image"),
                self.tr("""<p>The file <b>{0}</b> could not be saved.</p>""").
                format(fname))

    def __copyImageToClipboard(self):
        """
        Private slot to handle the Copy Image menu action.
        """
        if self.mainWidget is None:
            E5MessageBox.critical(self, self.tr("Save Image"),
                                  self.tr("""There is no UI file loaded."""))
            return

        cb = QApplication.clipboard()
        cb.setPixmap(self.mainWidget.grab())
        self.__updateChildren(self.lastStyle)

    def __printImage(self):
        """
        Private slot to handle the Print Image menu action.
        """
        if self.mainWidget is None:
            E5MessageBox.critical(self, self.tr("Print Image"),
                                  self.tr("""There is no UI file loaded."""))
            return

        settings = Preferences.Prefs.settings
        printer = QPrinter(QPrinter.HighResolution)
        printer.setFullPage(True)

        printerName = Preferences.getPrinter("UIPreviewer/printername")
        if printerName:
            printer.setPrinterName(printerName)
        printer.setPageSize(
            QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize"))))
        printer.setPageOrder(
            QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder"))))
        printer.setOrientation(
            QPrinter.Orientation(int(
                settings.value("UIPreviewer/orientation"))))
        printer.setColorMode(
            QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode"))))

        printDialog = QPrintDialog(printer, self)
        if printDialog.exec_() == QDialog.Accepted:
            self.statusBar().showMessage(self.tr("Printing the image..."))
            self.__print(printer)

            settings.setValue("UIPreviewer/printername", printer.printerName())
            settings.setValue("UIPreviewer/pagesize", printer.pageSize())
            settings.setValue("UIPreviewer/pageorder", printer.pageOrder())
            settings.setValue("UIPreviewer/orientation", printer.orientation())
            settings.setValue("UIPreviewer/colormode", printer.colorMode())

        self.statusBar().showMessage(self.tr("Image sent to printer..."), 2000)

    def __printPreviewImage(self):
        """
        Private slot to handle the Print Preview menu action.
        """
        from PyQt5.QtPrintSupport import QPrintPreviewDialog

        if self.mainWidget is None:
            E5MessageBox.critical(self, self.tr("Print Preview"),
                                  self.tr("""There is no UI file loaded."""))
            return

        settings = Preferences.Prefs.settings
        printer = QPrinter(QPrinter.HighResolution)
        printer.setFullPage(True)

        printerName = Preferences.getPrinter("UIPreviewer/printername")
        if printerName:
            printer.setPrinterName(printerName)
        printer.setPageSize(
            QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize"))))
        printer.setPageOrder(
            QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder"))))
        printer.setOrientation(
            QPrinter.Orientation(int(
                settings.value("UIPreviewer/orientation"))))
        printer.setColorMode(
            QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode"))))

        preview = QPrintPreviewDialog(printer, self)
        preview.paintRequested.connect(self.__print)
        preview.exec_()

    def __print(self, printer):
        """
        Private slot to the actual printing.
        
        @param printer reference to the printer object (QPrinter)
        """
        p = QPainter(printer)
        marginX = (printer.pageRect().x() - printer.paperRect().x()) // 2
        marginY = (printer.pageRect().y() - printer.paperRect().y()) // 2

        # double the margin on bottom of page
        if printer.orientation() == QPrinter.Portrait:
            width = printer.width() - marginX * 2
            height = printer.height() - marginY * 3
        else:
            marginX *= 2
            width = printer.width() - marginX * 2
            height = printer.height() - marginY * 2
        img = self.mainWidget.grab().toImage()
        self.__updateChildren(self.lastStyle)
        p.drawImage(
            marginX, marginY,
            img.scaled(width, height, Qt.KeepAspectRatio,
                       Qt.SmoothTransformation))
        p.end()
예제 #19
0
파일: myWidgets.py 프로젝트: MazeFX/pat
class MyRecurrenceBox(QFrame):
    # TODO - Build a occurrence selector for Contract model based on spinbox
    # Used information type is DateTime.TimeDelta

    valueSet = pyqtSignal(bool)
    _recurrenceValue = None

    def __init__(self, *args):
        super(MyRecurrenceBox, self).__init__(*args)
        Lumberjack.info('spawning a << MyRecurrenceBox >>')
        _translate = QCoreApplication.translate

        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Raised)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")

        self.spinBox = QSpinBox(self)
        self.spinBox.setObjectName("spinBox")
        self.spinBox.setValue(1)
        self.verticalLayout.addWidget(self.spinBox)
        self.spinBox.valueChanged.connect(self.on_value_spin)

        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.dailyRadioButton = QRadioButton(self)
        self.dailyRadioButton.setObjectName("dailyRadioButton")
        self.horizontalLayout_2.addWidget(self.dailyRadioButton)
        self.dailyRadioButton.setText(_translate("Form", "Days"))
        self.dailyRadioButton.setChecked(True)
        self.selected_radio_button = self.dailyRadioButton
        self.dailyRadioButton.toggled.connect(self.on_radio_toggle)

        self.weeklyRadioButton = QRadioButton(self)
        self.weeklyRadioButton.setObjectName("weeklyRadioButton")
        self.horizontalLayout_2.addWidget(self.weeklyRadioButton)
        self.weeklyRadioButton.setText(_translate("Form", "Weeks"))
        self.weeklyRadioButton.toggled.connect(self.on_radio_toggle)

        self.monthlyRadioButton = QRadioButton(self)
        self.monthlyRadioButton.setObjectName("monthlyRadioButton")
        self.horizontalLayout_2.addWidget(self.monthlyRadioButton)
        self.monthlyRadioButton.setText(_translate("Form", "Months"))
        self.monthlyRadioButton.toggled.connect(self.on_radio_toggle)

        self.yearlyRadioButton = QRadioButton(self)
        self.yearlyRadioButton.setObjectName("yearlyRadioButton")
        self.horizontalLayout_2.addWidget(self.yearlyRadioButton)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.yearlyRadioButton.setText(_translate("Form", "Years"))
        self.yearlyRadioButton.toggled.connect(self.on_radio_toggle)

        self.radio_buttons = [self.dailyRadioButton,
                              self.weeklyRadioButton,
                              self.monthlyRadioButton,
                              self.yearlyRadioButton]

    def getRecurrenceValue(self):
        Lumberjack.info('< MyRecurrenceBox > - -> (getRecurrenceValue)')
        return self._recurrenceValue

    def setRecurrenceValue(self, rel_delta):
        Lumberjack.info('< MyRecurrenceBox > - -> (setRecurrenceValue)')
        self._recurrenceValue = rel_delta
        Lumberjack.debug('(setRecurrenceValue) - rel_delta = {}'.format(rel_delta))
        if rel_delta is None:
            self._recurrenceValue = None
        else:
            for kw in rel_delta:
                for radio_button in self.radio_buttons:
                    if kw == radio_button.text().lower():
                        Lumberjack.debug('(setRecurrenceValue) - checking radiobutton = {}'.format(radio_button.text()))
                        radio_button.setChecked(True)
                        self.spinBox.setValue(rel_delta[kw])

        if self._recurrenceValue is None:
            self.valueSet.emit(False)
        else:
            self.valueSet.emit(True)

    recurrenceValue = pyqtProperty(dict, fget=getRecurrenceValue, fset=setRecurrenceValue)

    def on_radio_toggle(self, *args):
        Lumberjack.info('< MyRecurrenceBox > - -> (on_radio_toggle)')
        activate = args[0]
        Lumberjack.debug('(on_toggle) - args = {}'.format(activate))
        if not activate:
            return

        for radio_button in self.radio_buttons:
            if radio_button.isChecked():
                self.selected_radio_button = radio_button
                Lumberjack.debug('(on_toggle) - selected radiobutton.text = {}'.format(radio_button.text()))
        rel_delta = self._calculate_value()
        self._recurrenceValue = rel_delta

    def on_value_spin(self, x):
        Lumberjack.info('< MyRecurrenceBox > - -> (on_value_spin)')
        rel_delta = self._calculate_value()
        self._recurrenceValue = rel_delta

    def _calculate_value(self):
        Lumberjack.info('< MyRecurrenceBox > - -> (_calculate_value)')
        x = self.spinBox.value()
        kw = self.selected_radio_button.text().lower()
        timespan = {kw: x}
        Lumberjack.debug('(_calculate_value) - calculated value = {} {}'.format(timespan, type(timespan)))
        return timespan
예제 #20
0
class Setting_Ui(QWidget):
    def __init__(self, persepolis_setting):
        super().__init__()
        icon = QtGui.QIcon()
        self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/icon.svg')))
        self.setWindowTitle('Preferences')

        global icons
        icons = ':/' + str(persepolis_setting.value('settings/icons')) + '/'

        self.verticalLayout_2 = QVBoxLayout(self)
        self.setting_tabWidget = QTabWidget(self)
        #download_options_tab
        self.download_options_tab = QWidget()
        self.layoutWidget = QWidget(self.download_options_tab)
        self.download_options_verticalLayout = QVBoxLayout(self.layoutWidget)
        self.download_options_verticalLayout.setContentsMargins(21, 21, 0, 0)
        self.download_options_verticalLayout.setObjectName(
            "download_options_verticalLayout")
        self.horizontalLayout_5 = QHBoxLayout()
        #tries_label
        self.tries_label = QLabel(self.layoutWidget)
        self.horizontalLayout_5.addWidget(self.tries_label)
        #tries_spinBox
        self.tries_spinBox = QSpinBox(self.layoutWidget)
        self.tries_spinBox.setMinimum(1)

        self.horizontalLayout_5.addWidget(self.tries_spinBox)
        self.download_options_verticalLayout.addLayout(self.horizontalLayout_5)
        self.horizontalLayout_4 = QHBoxLayout()
        #wait_label
        self.wait_label = QLabel(self.layoutWidget)
        self.horizontalLayout_4.addWidget(self.wait_label)
        #wait_spinBox
        self.wait_spinBox = QSpinBox(self.layoutWidget)
        self.horizontalLayout_4.addWidget(self.wait_spinBox)

        self.download_options_verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_3 = QHBoxLayout()
        #time_out_label
        self.time_out_label = QLabel(self.layoutWidget)
        self.horizontalLayout_3.addWidget(self.time_out_label)
        #time_out_spinBox
        self.time_out_spinBox = QSpinBox(self.layoutWidget)
        self.horizontalLayout_3.addWidget(self.time_out_spinBox)

        self.download_options_verticalLayout.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_2 = QHBoxLayout()
        #connections_label
        self.connections_label = QLabel(self.layoutWidget)
        self.horizontalLayout_2.addWidget(self.connections_label)
        #connections_spinBox
        self.connections_spinBox = QSpinBox(self.layoutWidget)
        self.connections_spinBox.setMinimum(1)
        self.connections_spinBox.setMaximum(16)
        self.horizontalLayout_2.addWidget(self.connections_spinBox)

        self.download_options_verticalLayout.addLayout(self.horizontalLayout_2)
        #rpc_port_label
        self.rpc_port_label = QLabel(self.layoutWidget)
        self.rpc_horizontalLayout = QHBoxLayout()
        self.rpc_horizontalLayout.addWidget(self.rpc_port_label)
        #rpc_port_spinbox
        self.rpc_port_spinbox = QSpinBox(self.layoutWidget)
        self.rpc_port_spinbox.setMinimum(1024)
        self.rpc_port_spinbox.setMaximum(65535)
        self.rpc_horizontalLayout.addWidget(self.rpc_port_spinbox)
        self.download_options_verticalLayout.addLayout(
            self.rpc_horizontalLayout)

        self.setting_tabWidget.addTab(self.download_options_tab, "")
        #save_as_tab
        self.save_as_tab = QWidget()

        self.layoutWidget1 = QWidget(self.save_as_tab)

        self.save_as_verticalLayout = QVBoxLayout(self.layoutWidget1)
        self.save_as_verticalLayout.setContentsMargins(20, 30, 0, 0)

        self.download_folder_horizontalLayout = QHBoxLayout()
        #download_folder_label
        self.download_folder_label = QLabel(self.layoutWidget1)
        self.download_folder_horizontalLayout.addWidget(
            self.download_folder_label)
        #download_folder_lineEdit
        self.download_folder_lineEdit = QLineEdit(self.layoutWidget1)
        self.download_folder_horizontalLayout.addWidget(
            self.download_folder_lineEdit)
        #download_folder_pushButton
        self.download_folder_pushButton = QPushButton(self.layoutWidget1)
        self.download_folder_horizontalLayout.addWidget(
            self.download_folder_pushButton)

        self.save_as_verticalLayout.addLayout(
            self.download_folder_horizontalLayout)
        self.temp_horizontalLayout = QHBoxLayout()
        #temp_download_label
        self.temp_download_label = QLabel(self.layoutWidget1)
        self.temp_horizontalLayout.addWidget(self.temp_download_label)
        #temp_download_lineEdit
        self.temp_download_lineEdit = QLineEdit(self.layoutWidget1)
        self.temp_horizontalLayout.addWidget(self.temp_download_lineEdit)
        #temp_download_pushButton
        self.temp_download_pushButton = QPushButton(self.layoutWidget1)
        self.temp_horizontalLayout.addWidget(self.temp_download_pushButton)

        self.save_as_verticalLayout.addLayout(self.temp_horizontalLayout)
        self.setting_tabWidget.addTab(self.save_as_tab, "")
        #notifications_tab
        self.notifications_tab = QWidget()
        self.layoutWidget2 = QWidget(self.notifications_tab)
        self.verticalLayout_4 = QVBoxLayout(self.layoutWidget2)
        self.verticalLayout_4.setContentsMargins(21, 21, 0, 0)
        #enable_notifications_checkBox
        self.enable_notifications_checkBox = QCheckBox(self.layoutWidget2)
        self.verticalLayout_4.addWidget(self.enable_notifications_checkBox)
        #sound_frame
        self.sound_frame = QFrame(self.layoutWidget2)
        self.sound_frame.setFrameShape(QFrame.StyledPanel)
        self.sound_frame.setFrameShadow(QFrame.Raised)

        self.verticalLayout = QVBoxLayout(self.sound_frame)
        #volume_label
        self.volume_label = QLabel(self.sound_frame)
        self.verticalLayout.addWidget(self.volume_label)
        #volume_dial
        self.volume_dial = QDial(self.sound_frame)
        self.volume_dial.setProperty("value", 100)
        self.verticalLayout.addWidget(self.volume_dial)

        self.verticalLayout_4.addWidget(self.sound_frame)
        self.setting_tabWidget.addTab(self.notifications_tab, "")
        #style_tab
        self.style_tab = QWidget()
        self.layoutWidget3 = QWidget(self.style_tab)
        self.verticalLayout_3 = QVBoxLayout(self.layoutWidget3)
        self.verticalLayout_3.setContentsMargins(21, 21, 0, 0)
        self.horizontalLayout_8 = QHBoxLayout()
        #style_label
        self.style_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_8.addWidget(self.style_label)
        #style_comboBox
        self.style_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_8.addWidget(self.style_comboBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_8)
        self.horizontalLayout_7 = QHBoxLayout()
        #color_label
        self.color_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_7.addWidget(self.color_label)
        #color_comboBox
        self.color_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_7.addWidget(self.color_comboBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_7)
        #icon_label
        self.horizontalLayout_12 = QHBoxLayout()
        self.icon_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_12.addWidget(self.icon_label)
        #icon_comboBox
        self.icon_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_12.addWidget(self.icon_comboBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_12)
        self.horizontalLayout_6 = QHBoxLayout()
        #notification_label
        self.horizontalLayout_13 = QHBoxLayout()
        self.notification_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_13.addWidget(self.notification_label)
        #notification_comboBox
        self.notification_comboBox = QComboBox(self.layoutWidget3)
        self.horizontalLayout_13.addWidget(self.notification_comboBox)
        self.verticalLayout_3.addLayout(self.horizontalLayout_13)
        #font_label
        self.font_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_6.addWidget(self.font_label)
        #fontComboBox
        self.fontComboBox = QFontComboBox(self.layoutWidget3)
        self.horizontalLayout_6.addWidget(self.fontComboBox)
        #font_size_label
        self.font_size_label = QLabel(self.layoutWidget3)
        self.horizontalLayout_6.addWidget(self.font_size_label)
        #font_size_spinBox
        self.font_size_spinBox = QSpinBox(self.layoutWidget3)
        self.font_size_spinBox.setMinimum(1)
        self.horizontalLayout_6.addWidget(self.font_size_spinBox)

        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
        self.setting_tabWidget.addTab(self.style_tab, "")
        self.verticalLayout_2.addWidget(self.setting_tabWidget)
        self.horizontalLayout = QHBoxLayout()
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        #Enable system tray icon
        self.enable_system_tray_checkBox = QCheckBox(self.layoutWidget3)
        self.verticalLayout_3.addWidget(self.enable_system_tray_checkBox)
        #after_download dialog
        self.after_download_checkBox = QCheckBox()
        self.verticalLayout_3.addWidget(self.after_download_checkBox)

        #show_menubar_checkbox
        self.show_menubar_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.show_menubar_checkbox)

        #show_sidepanel_checkbox
        self.show_sidepanel_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.show_sidepanel_checkbox)

        #hide progress window
        self.show_progress_window_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.show_progress_window_checkbox)

        #add persepolis to startup
        self.startup_checkbox = QCheckBox()
        self.verticalLayout_3.addWidget(self.startup_checkbox)

        #defaults_pushButton
        self.defaults_pushButton = QPushButton(self)
        self.horizontalLayout.addWidget(self.defaults_pushButton)
        #cancel_pushButton
        self.cancel_pushButton = QPushButton(self)
        self.cancel_pushButton.setIcon(QIcon(icons + 'remove'))
        self.horizontalLayout.addWidget(self.cancel_pushButton)
        #ok_pushButton
        self.ok_pushButton = QPushButton(self)
        self.ok_pushButton.setIcon(QIcon(icons + 'ok'))
        self.horizontalLayout.addWidget(self.ok_pushButton)

        self.verticalLayout_2.addLayout(self.horizontalLayout)
        self.setting_tabWidget.setCurrentIndex(3)

        self.setWindowTitle("Preferences")
        self.tries_label.setToolTip(
            "<html><head/><body><p>Set number of tries if download failed.</p></body></html>"
        )
        self.tries_label.setText("Number of tries : ")
        self.tries_spinBox.setToolTip(
            "<html><head/><body><p>Set number of tries if download failed.</p></body></html>"
        )
        self.wait_label.setToolTip(
            "<html><head/><body><p>Set the seconds to wait between retries. Download manager will  retry  downloads  when  the  HTTP  server  returns  a  503 response.</p></body></html>"
        )
        self.wait_label.setText("Wait between retries (seconds) : ")
        self.wait_spinBox.setToolTip(
            "<html><head/><body><p>Set the seconds to wait between retries. Download manager will  retry  downloads  when  the  HTTP  server  returns  a  503 response.</p></body></html>"
        )
        self.time_out_label.setToolTip(
            "<html><head/><body><p>Set timeout in seconds. </p></body></html>")
        self.time_out_label.setText("Time out (seconds) : ")
        self.time_out_spinBox.setToolTip(
            "<html><head/><body><p>Set timeout in seconds. </p></body></html>")
        self.connections_label.setToolTip(
            "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>"
        )
        self.connections_label.setText("Number of connections : ")
        self.connections_spinBox.setToolTip(
            "<html><head/><body><p>Using multiple connections can help speed up your download.</p></body></html>"
        )
        self.rpc_port_label.setText("RPC port number : ")
        self.rpc_port_spinbox.setToolTip(
            "<html><head/><body><p> Specify a port number for JSON-RPC/XML-RPC server to listen to. Possible Values: 1024 - 65535 Default: 6801 </p></body></html>"
        )
        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.download_options_tab),
            "Download Options")

        self.download_folder_label.setText("Download Folder : ")
        self.download_folder_pushButton.setText("Change")
        self.temp_download_label.setText("Temporary Download Folder : ")
        self.temp_download_pushButton.setText("Change")
        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.save_as_tab), "Save as")
        self.enable_notifications_checkBox.setText(
            "Enable notification sounds")
        self.volume_label.setText("Volume : ")
        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.notifications_tab),
            "Notifications")
        self.style_label.setText("Style : ")
        self.color_label.setText("Color scheme : ")
        self.icon_label.setText("Icons : ")
        self.notification_label.setText("Notification type : ")
        self.font_label.setText("Font : ")
        self.font_size_label.setText("Size : ")
        self.enable_system_tray_checkBox.setText("Enable system tray icon.")
        self.after_download_checkBox.setText(
            "Show download complete dialog,when download has finished.")
        self.show_menubar_checkbox.setText("Show menubar.")
        self.show_sidepanel_checkbox.setText("Show side panel.")
        self.show_progress_window_checkbox.setText(
            "Show download's progress window")
        self.startup_checkbox.setText("Run Persepolis at startup")

        self.setting_tabWidget.setTabText(
            self.setting_tabWidget.indexOf(self.style_tab), "Preferences")
        self.defaults_pushButton.setText("Defaults")
        self.cancel_pushButton.setText("Cancel")
        self.ok_pushButton.setText("OK")
class QRegularExpressionWizardCharactersDialog(
        QDialog, Ui_QRegularExpressionWizardCharactersDialog):
    """
    Class implementing a dialog for entering character classes.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        super(QRegularExpressionWizardCharactersDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.__initCharacterSelectors()
        
        self.comboItems = []
        self.singleComboItems = []      # these are in addition to the above
        self.comboItems.append((self.tr("Normal character"), "-c"))
        self.comboItems.append((self.tr(
            "Unicode character in hexadecimal notation"), "-h"))
        self.comboItems.append((self.tr(
            "ASCII/Latin1 character in octal notation"), "-o"))
        self.singleComboItems.extend([
            ("---", "-i"),
            (self.tr("Bell character (\\a)"), "\\a"),
            (self.tr("Escape character (\\e)"), "\\e"),
            (self.tr("Page break (\\f)"), "\\f"),
            (self.tr("Line feed (\\n)"), "\\n"),
            (self.tr("Carriage return (\\r)"), "\\r"),
            (self.tr("Horizontal tabulator (\\t)"), "\\t"),
            ("---", "-i"),
            (self.tr("Character Category"), "-ccp"),
            (self.tr("Special Character Category"), "-csp"),
            (self.tr("Character Block"), "-cbp"),
            (self.tr("POSIX Named Set"), "-psp"),
            (self.tr("Not Character Category"), "-ccn"),
            (self.tr("Not Character Block"), "-cbn"),
            (self.tr("Not Special Character Category"), "-csn"),
            (self.tr("Not POSIX Named Set"), "-psn"),
        ])
        
        self.charValidator = QRegExpValidator(QRegExp(".{0,1}"), self)
        self.hexValidator = QRegExpValidator(QRegExp("[0-9a-fA-F]{0,4}"), self)
        self.octValidator = QRegExpValidator(QRegExp("[0-3]?[0-7]{0,2}"), self)
        
        # generate dialog part for single characters
        self.singlesBoxLayout = QVBoxLayout(self.singlesBox)
        self.singlesBoxLayout.setObjectName("singlesBoxLayout")
        self.singlesBoxLayout.setSpacing(6)
        self.singlesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesBox.setLayout(self.singlesBoxLayout)
        self.singlesView = QScrollArea(self.singlesBox)
        self.singlesView.setObjectName("singlesView")
        self.singlesBoxLayout.addWidget(self.singlesView)
        
        self.singlesItemsBox = QWidget(self)
        self.singlesView.setWidget(self.singlesItemsBox)
        self.singlesItemsBox.setObjectName("singlesItemsBox")
        self.singlesItemsBox.setMinimumWidth(1000)
        self.singlesItemsBoxLayout = QVBoxLayout(self.singlesItemsBox)
        self.singlesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesItemsBoxLayout.setSpacing(6)
        self.singlesItemsBox.setLayout(self.singlesItemsBoxLayout)
        self.singlesEntries = []
        self.__addSinglesLine()
        
        hlayout0 = QHBoxLayout()
        hlayout0.setContentsMargins(0, 0, 0, 0)
        hlayout0.setSpacing(6)
        hlayout0.setObjectName("hlayout0")
        self.moreSinglesButton = QPushButton(
            self.tr("Additional Entries"), self.singlesBox)
        self.moreSinglesButton.setObjectName("moreSinglesButton")
        hlayout0.addWidget(self.moreSinglesButton)
        hspacer0 = QSpacerItem(
            30, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        hlayout0.addItem(hspacer0)
        self.singlesBoxLayout.addLayout(hlayout0)
        self.moreSinglesButton.clicked.connect(self.__addSinglesLine)
        
        # generate dialog part for character ranges
        self.rangesBoxLayout = QVBoxLayout(self.rangesBox)
        self.rangesBoxLayout.setObjectName("rangesBoxLayout")
        self.rangesBoxLayout.setSpacing(6)
        self.rangesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesBox.setLayout(self.rangesBoxLayout)
        self.rangesView = QScrollArea(self.rangesBox)
        self.rangesView.setObjectName("rangesView")
        self.rangesBoxLayout.addWidget(self.rangesView)
        
        self.rangesItemsBox = QWidget(self)
        self.rangesView.setWidget(self.rangesItemsBox)
        self.rangesItemsBox.setObjectName("rangesItemsBox")
        self.rangesItemsBox.setMinimumWidth(1000)
        self.rangesItemsBoxLayout = QVBoxLayout(self.rangesItemsBox)
        self.rangesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesItemsBoxLayout.setSpacing(6)
        self.rangesItemsBox.setLayout(self.rangesItemsBoxLayout)
        self.rangesEntries = []
        self.__addRangesLine()
        
        hlayout1 = QHBoxLayout()
        hlayout1.setContentsMargins(0, 0, 0, 0)
        hlayout1.setSpacing(6)
        hlayout1.setObjectName("hlayout1")
        self.moreRangesButton = QPushButton(
            self.tr("Additional Entries"), self.rangesBox)
        self.moreSinglesButton.setObjectName("moreRangesButton")
        hlayout1.addWidget(self.moreRangesButton)
        hspacer1 = QSpacerItem(
            30, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        hlayout1.addItem(hspacer1)
        self.rangesBoxLayout.addLayout(hlayout1)
        self.moreRangesButton.clicked.connect(self.__addRangesLine)
    
    def __initCharacterSelectors(self):
        """
        Private method to initialize the W3C character selector entries.
        """
        self.__characterCategories = (
            # display name                                  code
            (self.tr("Letter, Any"), "L"),
            (self.tr("Letter, Lower case"), "Ll"),
            (self.tr("Letter, Modifier"), "Lm"),
            (self.tr("Letter, Other"), "Lo"),
            (self.tr("Letter, Title case"), "Lt"),
            (self.tr("Letter, Upper case"), "Lu"),
            (self.tr("Letter, Lower, Upper or Title"), "L&"),
            (self.tr("Mark, Any"), "M"),
            (self.tr("Mark, Spacing"), "Mc"),
            (self.tr("Mark, Enclosing"), "Me"),
            (self.tr("Mark, Non-spacing"), "Mn"),
            (self.tr("Number, Any"), "N"),
            (self.tr("Number, Decimal"), "Nd"),
            (self.tr("Number, Letter"), "Nl"),
            (self.tr("Number, Other"), "No"),
            (self.tr("Punctuation, Any"), "P"),
            (self.tr("Punctuation, Connector"), "Pc"),
            (self.tr("Punctuation, Dash"), "Pd"),
            (self.tr("Punctuation, Close"), "Pe"),
            (self.tr("Punctuation, Final"), "Pf"),
            (self.tr("Punctuation, Initial"), "Pi"),
            (self.tr("Punctuation, Other"), "Po"),
            (self.tr("Punctuation, Open"), "Ps"),
            (self.tr("Symbol, Any"), "S"),
            (self.tr("Symbol, Currency"), "Sc"),
            (self.tr("Symbol, Modifier"), "Sk"),
            (self.tr("Symbol, Mathematical"), "Sm"),
            (self.tr("Symbol, Other"), "So"),
            (self.tr("Separator, Any"), "Z"),
            (self.tr("Separator, Line"), "Zl"),
            (self.tr("Separator, Paragraph"), "Zp"),
            (self.tr("Separator, Space"), "Zs"),
            (self.tr("Other, Any"), "C"),
            (self.tr("Other, Control"), "Cc"),
            (self.tr("Other, Format"), "Cf"),
            (self.tr("Other, Unassigned"), "Cn"),
            (self.tr("Other, Private Use"), "Co"),
            (self.tr("Other, Surrogat"), "Cn"),
        )
        
        self.__specialCharacterCategories = (
            # display name                           code
            (self.tr("Alphanumeric"), "Xan"),
            (self.tr("POSIX Space"), "Xps"),
            (self.tr("Perl Space"), "Xsp"),
            (self.tr("Universal Character"), "Xuc"),
            (self.tr("Perl Word"), "Xan"),
        )
        
        self.__characterBlocks = (
            # display name                           code
            (self.tr("Arabic"), "Arabic"),
            (self.tr("Armenian"), "Armenian"),
            (self.tr("Avestan"), "Avestan"),
            (self.tr("Balinese"), "Balinese"),
            (self.tr("Bamum"), "Bamum"),
            (self.tr("Batak"), "Batak"),
            (self.tr("Bengali"), "Bengali"),
            (self.tr("Bopomofo"), "Bopomofo"),
            (self.tr("Brahmi"), "Brahmi"),
            (self.tr("Braille"), "Braille"),
            (self.tr("Buginese"), "Buginese"),
            (self.tr("Buhid"), "Buhid"),
            (self.tr("Canadian Aboriginal"), "Canadian_Aboriginal"),
            (self.tr("Carian"), "Carian"),
            (self.tr("Chakma"), "Chakma"),
            (self.tr("Cham"), "Cham"),
            (self.tr("Cherokee"), "Cherokee"),
            (self.tr("Common"), "Common"),
            (self.tr("Coptic"), "Coptic"),
            (self.tr("Cuneiform"), "Cuneiform"),
            (self.tr("Cypriot"), "Cypriot"),
            (self.tr("Cyrillic"), "Cyrillic"),
            (self.tr("Deseret"), "Deseret,"),
            (self.tr("Devanagari"), "Devanagari"),
            (self.tr("Egyptian Hieroglyphs"), "Egyptian_Hieroglyphs"),
            (self.tr("Ethiopic"), "Ethiopic"),
            (self.tr("Georgian"), "Georgian"),
            (self.tr("Glagolitic"), "Glagolitic"),
            (self.tr("Gothic"), "Gothic"),
            (self.tr("Greek"), "Greek"),
            (self.tr("Gujarati"), "Gujarati"),
            (self.tr("Gurmukhi"), "Gurmukhi"),
            (self.tr("Han"), "Han"),
            (self.tr("Hangul"), "Hangul"),
            (self.tr("Hanunoo"), "Hanunoo"),
            (self.tr("Hebrew"), "Hebrew"),
            (self.tr("Hiragana"), "Hiragana"),
            (self.tr("Imperial Aramaic"), "Imperial_Aramaic"),
            (self.tr("Inherited"), "Inherited"),
            (self.tr("Inscriptional Pahlavi"), "Inscriptional_Pahlavi"),
            (self.tr("Inscriptional Parthian"), "Inscriptional_Parthian"),
            (self.tr("Javanese"), "Javanese"),
            (self.tr("Kaithi"), "Kaithi"),
            (self.tr("Kannada"), "Kannada"),
            (self.tr("Katakana"), "Katakana"),
            (self.tr("Kayah Li"), "Kayah_Li"),
            (self.tr("Kharoshthi"), "Kharoshthi"),
            (self.tr("Khmer"), "Khmer"),
            (self.tr("Lao"), "Lao"),
            (self.tr("Latin"), "Latin"),
            (self.tr("Lepcha"), "Lepcha"),
            (self.tr("Limbu"), "Limbu"),
            (self.tr("Linear B"), "Linear_B"),
            (self.tr("Lisu"), "Lisu"),
            (self.tr("Lycian"), "Lycian"),
            (self.tr("Lydian"), "Lydian"),
            (self.tr("Malayalam"), "Malayalam"),
            (self.tr("Mandaic"), "Mandaic"),
            (self.tr("Meetei Mayek"), "Meetei_Mayek"),
            (self.tr("Meroitic Cursive"), "Meroitic_Cursive"),
            (self.tr("Meroitic Hieroglyphs"), "Meroitic_Hieroglyphs"),
            (self.tr("Miao"), "Miao"),
            (self.tr("Mongolian"), "Mongolian"),
            (self.tr("Myanmar"), "Myanmar"),
            (self.tr("New Tai Lue"), "New_Tai_Lue"),
            (self.tr("N'Ko"), "Nko"),
            (self.tr("Ogham"), "Ogham"),
            (self.tr("Old Italic"), "Old_Italic"),
            (self.tr("Old Persian"), "Old_Persian"),
            (self.tr("Old South Arabian"), "Old_South_Arabian"),
            (self.tr("Old Turkic"), "Old_Turkic,"),
            (self.tr("Ol Chiki"), "Ol_Chiki"),
            (self.tr("Oriya"), "Oriya"),
            (self.tr("Osmanya"), "Osmanya"),
            (self.tr("Phags-pa"), "Phags_Pa"),
            (self.tr("Phoenician"), "Phoenician"),
            (self.tr("Rejang"), "Rejang"),
            (self.tr("Runic"), "Runic"),
            (self.tr("Samaritan"), "Samaritan"),
            (self.tr("Saurashtra"), "Saurashtra"),
            (self.tr("Sharada"), "Sharada"),
            (self.tr("Shavian"), "Shavian"),
            (self.tr("Sinhala"), "Sinhala"),
            (self.tr("Sora Sompeng"), "Sora_Sompeng"),
            (self.tr("Sundanese"), "Sundanese"),
            (self.tr("Syloti Nagri"), "Syloti_Nagri"),
            (self.tr("Syriac"), "Syriac"),
            (self.tr("Tagalog"), "Tagalog"),
            (self.tr("Tagbanwa"), "Tagbanwa"),
            (self.tr("Tai Le"), "Tai_Le"),
            (self.tr("Tai Tham"), "Tai_Tham"),
            (self.tr("Tai Viet"), "Tai_Viet"),
            (self.tr("Takri"), "Takri"),
            (self.tr("Tamil"), "Tamil"),
            (self.tr("Telugu"), "Telugu"),
            (self.tr("Thaana"), "Thaana"),
            (self.tr("Thai"), "Thai"),
            (self.tr("Tibetan"), "Tibetan"),
            (self.tr("Tifinagh"), "Tifinagh"),
            (self.tr("Ugaritic"), "Ugaritic"),
            (self.tr("Vai"), "Vai"),
            (self.tr("Yi"), "Yi"),
        )
        
        self.__posixNamedSets = (
            # display name                                  code
            (self.tr("Alphanumeric"), "alnum"),
            (self.tr("Alphabetic"), "alpha"),
            (self.tr("ASCII"), "ascii"),
            (self.tr("Word Letter"), "word"),
            (self.tr("Lower Case Letter"), "lower"),
            (self.tr("Upper Case Letter"), "upper"),
            (self.tr("Decimal Digit"), "digit"),
            (self.tr("Hexadecimal Digit"), "xdigit"),
            (self.tr("Space or Tab"), "blank"),
            (self.tr("White Space"), "space"),
            (self.tr("Printing (excl. space)"), "graph"),
            (self.tr("Printing (incl. space)"), "print"),
            (self.tr("Printing (excl. alphanumeric)"), "punct"),
            (self.tr("Control Character"), "cntrl"),
        )
    
    def __populateCharTypeCombo(self, combo, isSingle):
        """
        Private method to populate a given character type selection combo box.
        
        @param combo reference to the combo box to be populated (QComboBox)
        @param isSingle flag indicating a singles combo (boolean)
        """
        for txt, value in self.comboItems:
            combo.addItem(txt, value)
        if isSingle:
            for txt, value in self.singleComboItems:
                combo.addItem(txt, value)

    def __addSinglesLine(self):
        """
        Private slot to add a line of entry widgets for single characters.
        """
        hbox = QWidget(self.singlesItemsBox)
        hboxLayout = QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(6)
        hbox.setLayout(hboxLayout)
        cb1 = QComboBox(hbox)
        cb1.setEditable(False)
        self.__populateCharTypeCombo(cb1, True)
        hboxLayout.addWidget(cb1)
        le1 = QLineEdit(hbox)
        le1.setValidator(self.charValidator)
        hboxLayout.addWidget(le1)
        cb1a = QComboBox(hbox)
        cb1a.setEditable(False)
        cb1a.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        hboxLayout.addWidget(cb1a)
        cb1a.hide()
        cb2 = QComboBox(hbox)
        cb2.setEditable(False)
        self.__populateCharTypeCombo(cb2, True)
        hboxLayout.addWidget(cb2)
        le2 = QLineEdit(hbox)
        le2.setValidator(self.charValidator)
        hboxLayout.addWidget(le2)
        cb2a = QComboBox(hbox)
        cb2a.setEditable(False)
        cb2a.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        hboxLayout.addWidget(cb2a)
        cb2a.hide()
        self.singlesItemsBoxLayout.addWidget(hbox)
        
        cb1.activated[int].connect(self.__singlesCharTypeSelected)
        cb2.activated[int].connect(self.__singlesCharTypeSelected)
        hbox.show()
        
        self.singlesItemsBox.adjustSize()
        
        self.singlesEntries.append([cb1, le1, cb1a])
        self.singlesEntries.append([cb2, le2, cb2a])
    
    def __addRangesLine(self):
        """
        Private slot to add a line of entry widgets for character ranges.
        """
        hbox = QWidget(self.rangesItemsBox)
        hboxLayout = QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(6)
        hbox.setLayout(hboxLayout)
        cb1 = QComboBox(hbox)
        cb1.setEditable(False)
        self.__populateCharTypeCombo(cb1, False)
        hboxLayout.addWidget(cb1)
        l1 = QLabel(self.tr("Between:"), hbox)
        hboxLayout.addWidget(l1)
        le1 = QLineEdit(hbox)
        le1.setValidator(self.charValidator)
        hboxLayout.addWidget(le1)
        l2 = QLabel(self.tr("And:"), hbox)
        hboxLayout.addWidget(l2)
        le2 = QLineEdit(hbox)
        le2.setValidator(self.charValidator)
        hboxLayout.addWidget(le2)
        self.rangesItemsBoxLayout.addWidget(hbox)
        
        cb1.activated[int].connect(self.__rangesCharTypeSelected)
        hbox.show()
        
        self.rangesItemsBox.adjustSize()
        
        self.rangesEntries.append([cb1, le1, le2])
    
    def __populateCharacterCombo(self, combo, format):
        """
        Private method to populate a character selection combo.
        
        @param combo combo box to be populated (QComboBox)
        @param format format identifier (one of "-ccp", "-ccn",
            "-cbp", "-cbn", "-csp", "-csn", "-psp", "-psn")
        """
        combo.clear()
        
        if format in ["-ccp", "-ccn"]:
            items = self.__characterCategories
        elif format in ["-csp", "-csn"]:
            items = self.__specialCharacterCategories
        elif format in ["-cbp", "-cbn"]:
            items = self.__characterBlocks
        elif format in ["-psp", "-psn"]:
            items = self.__posixNamedSets
        
        comboLen = 0
        for txt, code in items:
            combo.addItem(txt, code)
            comboLen = max(comboLen, len(txt))
        combo.setMinimumContentsLength(comboLen)
    
    def __performSelectedAction(self, format, lineedit, combo):
        """
        Private method performing some actions depending on the input.
        
        @param format format of the selected entry (string)
        @param lineedit line edit widget to act on (QLineEdit)
        @param combo combo box widget to act on (QComboBox)
        """
        if format == "-i":
            return
        
        if format in ["-c", "-h", "-o"]:
            lineedit.show()
            lineedit.setEnabled(True)
            if combo is not None:
                combo.hide()
            if format == "-c":
                lineedit.setValidator(self.charValidator)
            elif format == "-h":
                lineedit.setValidator(self.hexValidator)
            elif format == "-o":
                lineedit.setValidator(self.octValidator)
        elif format in ["-ccp", "-ccn", "-cbp", "-cbn", "-csp", "-csn",
                        "-psp", "-psn"]:
            lineedit.setEnabled(False)
            lineedit.hide()
            if combo is not None:
                combo.show()
            self.__populateCharacterCombo(combo, format)
        else:
            lineedit.setEnabled(False)
            lineedit.hide()
            if combo is not None:
                combo.hide()
        lineedit.clear()
    
    def __singlesCharTypeSelected(self, index):
        """
        Private slot to handle the activated(int) signal of the single chars
        combo boxes.
        
        @param index selected list index (integer)
        """
        combo = self.sender()
        for entriesList in self.singlesEntries:
            if combo == entriesList[0]:
                format = combo.itemData(index)
                self.__performSelectedAction(
                    format, entriesList[1], entriesList[2])
                break
    
    def __rangesCharTypeSelected(self, index):
        """
        Private slot to handle the activated(int) signal of the char ranges
        combo boxes.
        
        @param index selected list index (integer)
        """
        combo = self.sender()
        for entriesList in self.rangesEntries:
            if combo == entriesList[0]:
                format = combo.itemData(index)
                self.__performSelectedAction(format, entriesList[1], None)
                self.__performSelectedAction(format, entriesList[2], None)
                break
    
    def __formatCharacter(self, char, format):
        """
        Private method to format the characters entered into the dialog.
        
        @param char character string entered into the dialog (string)
        @param format string giving a special format (-c, -h, -i or -o) or
            the already formatted character (string)
        @return formatted character string (string)
        """
        if format == "-c":
            return char
        elif format == "-i":
            return ""
        
        if format == "-h":
            while len(char) < 2:
                char = "0" + char
            if len(char) > 2:
                return "\\x{{{0}}}".format(char.lower())
            else:
                return "\\x{0}".format(char.lower())
        elif format == "-o":
            while len(char) < 3:
                char = "0" + char
            if len(char) > 3:
                char = char[:3]
            return "\\{0}".format(char)
        elif format in ["-ccp", "-cbp", "-csp"]:
            return "\\p{{{0}}}".format(char)
        elif format in ["-ccn", "-cbn", "-csn"]:
            return "\\P{{{0}}}".format(char)
        elif format == "-psp":
            return "[:{0}:]".format(char)
        elif format == "-psn":
            return "[:^{0}:]".format(char)
        else:
            return format
    
    def getCharacters(self):
        """
        Public method to return the character string assembled via the dialog.
        
        @return formatted string for character classes (string)
        """
        regexp = ""
        
        # negative character range
        if self.negativeCheckBox.isChecked():
            regexp += "^"
            
        # predefined character ranges
        if self.wordCharCheckBox.isChecked():
            regexp += "\\w"
        if self.nonWordCharCheckBox.isChecked():
            regexp += "\\W"
        if self.digitsCheckBox.isChecked():
            regexp += "\\d"
        if self.nonDigitsCheckBox.isChecked():
            regexp += "\\D"
        if self.newlineCheckBox.isChecked():
            regexp += "\\R"
        if self.nonNewlineCheckBox.isChecked():
            regexp += "\\N"
        if self.whitespaceCheckBox.isChecked():
            regexp += "\\s"
        if self.nonWhitespaceCheckBox.isChecked():
            regexp += "\\S"
        if self.horizontalWhitespaceCheckBox.isChecked():
            regexp += "\\h"
        if self.nonHorizontalWhitespaceCheckBox.isChecked():
            regexp += "\\H"
        if self.verticalWhitespaceCheckBox.isChecked():
            regexp += "\\v"
        if self.nonVerticalWhitespaceCheckBox.isChecked():
            regexp += "\\V"
        
        # single characters
        for entrieslist in self.singlesEntries:
            format = entrieslist[0].itemData(entrieslist[0].currentIndex())
            if format in ["-ccp", "-ccn", "-cbp", "-cbn", "-csp", "-csn",
                          "-psp", "-psn"]:
                char = entrieslist[2].itemData(entrieslist[2].currentIndex())
            else:
                char = entrieslist[1].text()
            regexp += self.__formatCharacter(char, format)
        
        # character ranges
        for entrieslist in self.rangesEntries:
            if not entrieslist[1].text() or \
               not entrieslist[2].text():
                continue
            format = entrieslist[0].itemData(entrieslist[0].currentIndex())
            char1 = entrieslist[1].text()
            char2 = entrieslist[2].text()
            regexp += "{0}-{1}".format(
                self.__formatCharacter(char1, format),
                self.__formatCharacter(char2, format))
        
        if regexp:
            if (regexp.startswith("\\") and
                regexp.count("\\") == 1 and
                "-" not in regexp) or \
               len(regexp) == 1:
                return regexp
            else:
                return "[{0}]".format(regexp)
        else:
            return ""
class QRegExpWizardCharactersDialog(QDialog, Ui_QRegExpWizardCharactersDialog):
    """
    Class implementing a dialog for entering character classes.
    """
    RegExpMode = 0
    WildcardMode = 1
    W3CMode = 2
    
    def __init__(self, mode=RegExpMode, parent=None):
        """
        Constructor
        
        @param mode mode of the dialog (one of RegExpMode, WildcardMode,
            W3CMode)
        @param parent parent widget (QWidget)
        """
        super(QRegExpWizardCharactersDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.__mode = mode
        
        if mode == QRegExpWizardCharactersDialog.WildcardMode:
            self.predefinedBox.setEnabled(False)
            self.predefinedBox.hide()
        elif mode == QRegExpWizardCharactersDialog.RegExpMode:
            self.w3cInitialIdentifierCheckBox.hide()
            self.w3cNonInitialIdentifierCheckBox.hide()
            self.w3cNmtokenCheckBox.hide()
            self.w3cNonNmtokenCheckBox.hide()
        elif mode == QRegExpWizardCharactersDialog.W3CMode:
            self.__initCharacterSelectors()
        
        self.comboItems = []
        self.singleComboItems = []      # these are in addition to the above
        self.comboItems.append((self.tr("Normal character"), "-c"))
        if mode == QRegExpWizardCharactersDialog.RegExpMode:
            self.comboItems.append((self.tr(
                "Unicode character in hexadecimal notation"), "-h"))
            self.comboItems.append((self.tr(
                "ASCII/Latin1 character in octal notation"), "-o"))
            self.singleComboItems.append(("---", "-i"))
            self.singleComboItems.append(
                (self.tr("Bell character (\\a)"), "\\a"))
            self.singleComboItems.append(
                (self.tr("Page break (\\f)"), "\\f"))
            self.singleComboItems.append(
                (self.tr("Line feed (\\n)"), "\\n"))
            self.singleComboItems.append(
                (self.tr("Carriage return (\\r)"), "\\r"))
            self.singleComboItems.append(
                (self.tr("Horizontal tabulator (\\t)"), "\\t"))
            self.singleComboItems.append(
                (self.tr("Vertical tabulator (\\v)"), "\\v"))
        elif mode == QRegExpWizardCharactersDialog.W3CMode:
            self.comboItems.append((self.tr(
                "Unicode character in hexadecimal notation"), "-h"))
            self.comboItems.append((self.tr(
                "ASCII/Latin1 character in octal notation"), "-o"))
            self.singleComboItems.append(("---", "-i"))
            self.singleComboItems.append(
                (self.tr("Line feed (\\n)"), "\\n"))
            self.singleComboItems.append(
                (self.tr("Carriage return (\\r)"), "\\r"))
            self.singleComboItems.append(
                (self.tr("Horizontal tabulator (\\t)"), "\\t"))
            self.singleComboItems.append(("---", "-i"))
            self.singleComboItems.append(
                (self.tr("Character Category"), "-ccp"))
            self.singleComboItems.append(
                (self.tr("Character Block"), "-cbp"))
            self.singleComboItems.append(
                (self.tr("Not Character Category"), "-ccn"))
            self.singleComboItems.append(
                (self.tr("Not Character Block"), "-cbn"))
        
        self.charValidator = QRegExpValidator(QRegExp(".{0,1}"), self)
        self.hexValidator = QRegExpValidator(QRegExp("[0-9a-fA-F]{0,4}"), self)
        self.octValidator = QRegExpValidator(QRegExp("[0-3]?[0-7]{0,2}"), self)
        
        # generate dialog part for single characters
        self.singlesBoxLayout = QVBoxLayout(self.singlesBox)
        self.singlesBoxLayout.setObjectName("singlesBoxLayout")
        self.singlesBoxLayout.setSpacing(6)
        self.singlesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesBox.setLayout(self.singlesBoxLayout)
        self.singlesView = QScrollArea(self.singlesBox)
        self.singlesView.setObjectName("singlesView")
        self.singlesBoxLayout.addWidget(self.singlesView)
        
        self.singlesItemsBox = QWidget(self)
        self.singlesView.setWidget(self.singlesItemsBox)
        self.singlesItemsBox.setObjectName("singlesItemsBox")
        self.singlesItemsBox.setMinimumWidth(1000)
        self.singlesItemsBoxLayout = QVBoxLayout(self.singlesItemsBox)
        self.singlesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesItemsBoxLayout.setSpacing(6)
        self.singlesItemsBox.setLayout(self.singlesItemsBoxLayout)
        self.singlesEntries = []
        self.__addSinglesLine()
        
        hlayout0 = QHBoxLayout()
        hlayout0.setContentsMargins(0, 0, 0, 0)
        hlayout0.setSpacing(6)
        hlayout0.setObjectName("hlayout0")
        self.moreSinglesButton = QPushButton(
            self.tr("Additional Entries"), self.singlesBox)
        self.moreSinglesButton.setObjectName("moreSinglesButton")
        hlayout0.addWidget(self.moreSinglesButton)
        hspacer0 = QSpacerItem(
            30, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        hlayout0.addItem(hspacer0)
        self.singlesBoxLayout.addLayout(hlayout0)
        self.moreSinglesButton.clicked.connect(self.__addSinglesLine)
        
        # generate dialog part for character ranges
        self.rangesBoxLayout = QVBoxLayout(self.rangesBox)
        self.rangesBoxLayout.setObjectName("rangesBoxLayout")
        self.rangesBoxLayout.setSpacing(6)
        self.rangesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesBox.setLayout(self.rangesBoxLayout)
        self.rangesView = QScrollArea(self.rangesBox)
        self.rangesView.setObjectName("rangesView")
        self.rangesBoxLayout.addWidget(self.rangesView)
        
        self.rangesItemsBox = QWidget(self)
        self.rangesView.setWidget(self.rangesItemsBox)
        self.rangesItemsBox.setObjectName("rangesItemsBox")
        self.rangesItemsBox.setMinimumWidth(1000)
        self.rangesItemsBoxLayout = QVBoxLayout(self.rangesItemsBox)
        self.rangesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesItemsBoxLayout.setSpacing(6)
        self.rangesItemsBox.setLayout(self.rangesItemsBoxLayout)
        self.rangesEntries = []
        self.__addRangesLine()
        
        hlayout1 = QHBoxLayout()
        hlayout1.setContentsMargins(0, 0, 0, 0)
        hlayout1.setSpacing(6)
        hlayout1.setObjectName("hlayout1")
        self.moreRangesButton = QPushButton(
            self.tr("Additional Entries"), self.rangesBox)
        self.moreSinglesButton.setObjectName("moreRangesButton")
        hlayout1.addWidget(self.moreRangesButton)
        hspacer1 = QSpacerItem(
            30, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        hlayout1.addItem(hspacer1)
        self.rangesBoxLayout.addLayout(hlayout1)
        self.moreRangesButton.clicked.connect(self.__addRangesLine)
        
    def __initCharacterSelectors(self):
        """
        Private method to initialize the W3C character selector entries.
        """
        self.__characterCategories = (
            # display name                              code
            (self.tr("Letter, Any"), "L"),
            (self.tr("Letter, Uppercase"), "Lu"),
            (self.tr("Letter, Lowercase"), "Ll"),
            (self.tr("Letter, Titlecase"), "Lt"),
            (self.tr("Letter, Modifier"), "Lm"),
            (self.tr("Letter, Other"), "Lo"),
            (self.tr("Mark, Any"), "M"),
            (self.tr("Mark, Nonspacing"), "Mn"),
            (self.tr("Mark, Spacing Combining"), "Mc"),
            (self.tr("Mark, Enclosing"), "Me"),
            (self.tr("Number, Any"), "N"),
            (self.tr("Number, Decimal Digit"), "Nd"),
            (self.tr("Number, Letter"), "Nl"),
            (self.tr("Number, Other"), "No"),
            (self.tr("Punctuation, Any"), "P"),
            (self.tr("Punctuation, Connector"), "Pc"),
            (self.tr("Punctuation, Dash"), "Pd"),
            (self.tr("Punctuation, Open"), "Ps"),
            (self.tr("Punctuation, Close"), "Pe"),
            (self.tr("Punctuation, Initial Quote"), "Pi"),
            (self.tr("Punctuation, Final Quote"), "Pf"),
            (self.tr("Punctuation, Other"), "Po"),
            (self.tr("Symbol, Any"), "S"),
            (self.tr("Symbol, Math"), "Sm"),
            (self.tr("Symbol, Currency"), "Sc"),
            (self.tr("Symbol, Modifier"), "Sk"),
            (self.tr("Symbol, Other"), "So"),
            (self.tr("Separator, Any"), "Z"),
            (self.tr("Separator, Space"), "Zs"),
            (self.tr("Separator, Line"), "Zl"),
            (self.tr("Separator, Paragraph"), "Zp"),
            (self.tr("Other, Any"), "C"),
            (self.tr("Other, Control"), "Cc"),
            (self.tr("Other, Format"), "Cf"),
            (self.tr("Other, Private Use"), "Co"),
            (self.tr("Other, Not Assigned"), "Cn"),
        )
        
        self.__characterBlocks = (
            (self.tr("Basic Latin"),
             "IsBasicLatin"),
            (self.tr("Latin-1 Supplement"),
             "IsLatin-1Supplement"),
            (self.tr("Latin Extended-A"),
             "IsLatinExtended-A"),
            (self.tr("Latin Extended-B"),
             "IsLatinExtended-B"),
            (self.tr("IPA Extensions"),
             "IsIPAExtensions"),
            (self.tr("Spacing Modifier Letters"),
             "IsSpacingModifierLetters"),
            (self.tr("Combining Diacritical Marks"),
             "IsCombiningDiacriticalMarks"),
            (self.tr("Greek"),
             "IsGreek"),
            (self.tr("Cyrillic"),
             "IsCyrillic"),
            (self.tr("Armenian"),
             "IsArmenian"),
            (self.tr("Hebrew"),
             "IsHebrew"),
            (self.tr("Arabic"),
             "IsArabic"),
            (self.tr("Syriac"),
             "IsSyriac"),
            (self.tr("Thaana"),
             "IsThaana"),
            (self.tr("Devanagari"),
             "IsDevanagari"),
            (self.tr("Bengali"),
             "IsBengali"),
            (self.tr("Gurmukhi"),
             "IsBengali"),
            (self.tr("Gujarati"),
             "IsGujarati"),
            (self.tr("Oriya"),
             "IsOriya"),
            (self.tr("Tamil"),
             "IsTamil"),
            (self.tr("Telugu"),
             "IsTelugu"),
            (self.tr("Kannada"),
             "IsKannada"),
            (self.tr("Malayalam"),
             "IsMalayalam"),
            (self.tr("Sinhala"),
             "IsSinhala"),
            (self.tr("Thai"),
             "IsThai"),
            (self.tr("Lao"),
             "IsLao"),
            (self.tr("Tibetan"),
             "IsTibetan"),
            (self.tr("Myanmar"),
             "IsMyanmar"),
            (self.tr("Georgian"),
             "IsGeorgian"),
            (self.tr("Hangul Jamo"),
             "IsHangulJamo"),
            (self.tr("Ethiopic"),
             "IsEthiopic"),
            (self.tr("Cherokee"),
             "IsCherokee"),
            (self.tr("Unified Canadian Aboriginal Syllabics"),
             "IsUnifiedCanadianAboriginalSyllabics"),
            (self.tr("Ogham"),
             "IsOgham"),
            (self.tr("Runic"),
             "IsRunic"),
            (self.tr("Khmer"),
             "IsKhmer"),
            (self.tr("Mongolian"),
             "IsMongolian"),
            (self.tr("Latin Extended Additional"),
             "IsLatinExtendedAdditional"),
            (self.tr("Greek Extended"),
             "IsGreekExtended"),
            (self.tr("General Punctuation"),
             "IsGeneralPunctuation"),
            (self.tr("Superscripts and Subscripts"),
             "IsSuperscriptsandSubscripts"),
            (self.tr("Currency Symbols"),
             "IsCurrencySymbols"),
            (self.tr("Combining Marks for Symbols"),
             "IsCombiningMarksforSymbols"),
            (self.tr("Letterlike Symbols"),
             "IsLetterlikeSymbols"),
            (self.tr("Number Forms"),
             "IsNumberForms"),
            (self.tr("Arrows"),
             "IsArrows"),
            (self.tr("Mathematical Operators"),
             "IsMathematicalOperators"),
            (self.tr("Miscellaneous Technical"),
             "IsMiscellaneousTechnical"),
            (self.tr("Control Pictures"),
             "IsControlPictures"),
            (self.tr("Optical Character Recognition"),
             "IsOpticalCharacterRecognition"),
            (self.tr("Enclosed Alphanumerics"),
             "IsEnclosedAlphanumerics"),
            (self.tr("Box Drawing"),
             "IsBoxDrawing"),
            (self.tr("Block Elements"),
             "IsBlockElements"),
            (self.tr("Geometric Shapes"),
             "IsGeometricShapes"),
            (self.tr("Miscellaneous Symbols"),
             "IsMiscellaneousSymbols"),
            (self.tr("Dingbats"),
             "IsDingbats"),
            (self.tr("Braille Patterns"),
             "IsBraillePatterns"),
            (self.tr("CJK Radicals Supplement"),
             "IsCJKRadicalsSupplement"),
            (self.tr("KangXi Radicals"),
             "IsKangXiRadicals"),
            (self.tr("Ideographic Description Chars"),
             "IsIdeographicDescriptionChars"),
            (self.tr("CJK Symbols and Punctuation"),
             "IsCJKSymbolsandPunctuation"),
            (self.tr("Hiragana"),
             "IsHiragana"),
            (self.tr("Katakana"),
             "IsKatakana"),
            (self.tr("Bopomofo"),
             "IsBopomofo"),
            (self.tr("Hangul Compatibility Jamo"),
             "IsHangulCompatibilityJamo"),
            (self.tr("Kanbun"),
             "IsKanbun"),
            (self.tr("Bopomofo Extended"),
             "IsBopomofoExtended"),
            (self.tr("Enclosed CJK Letters and Months"),
             "IsEnclosedCJKLettersandMonths"),
            (self.tr("CJK Compatibility"),
             "IsCJKCompatibility"),
            (self.tr("CJK Unified Ideographs Extension A"),
             "IsCJKUnifiedIdeographsExtensionA"),
            (self.tr("CJK Unified Ideographs"),
             "IsCJKUnifiedIdeographs"),
            (self.tr("Yi Syllables"),
             "IsYiSyllables"),
            (self.tr("Yi Radicals"),
             "IsYiRadicals"),
            (self.tr("Hangul Syllables"),
             "IsHangulSyllables"),
            (self.tr("Private Use"),
             "IsPrivateUse"),
            (self.tr("CJK Compatibility Ideographs"),
             "IsCJKCompatibilityIdeographs"),
            (self.tr("Alphabetic Presentation Forms"),
             "IsAlphabeticPresentationForms"),
            (self.tr("Arabic Presentation Forms-A"),
             "IsArabicPresentationForms-A"),
            (self.tr("Combining Half Marks"),
             "IsCombiningHalfMarks"),
            (self.tr("CJK Compatibility Forms"),
             "IsCJKCompatibilityForms"),
            (self.tr("Small Form Variants"),
             "IsSmallFormVariants"),
            (self.tr("Arabic Presentation Forms-B"),
             "IsArabicPresentationForms-B"),
            (self.tr("Halfwidth and Fullwidth Forms"),
             "IsHalfwidthandFullwidthForms"),
            (self.tr("Specials"),
             "IsSpecials"),
            (self.tr("Old Italic"),
             "IsOldItalic"),
            (self.tr("Gothic"),
             "IsGothic"),
            (self.tr("Deseret"),
             "IsDeseret"),
            (self.tr("Byzantine Musical Symbols"),
             "IsByzantineMusicalSymbols"),
            (self.tr("Musical Symbols"),
             "IsMusicalSymbols"),
            (self.tr("Mathematical Alphanumeric Symbols"),
             "IsMathematicalAlphanumericSymbols"),
            (self.tr("CJK Unified Ideographic Extension B"),
             "IsCJKUnifiedIdeographicExtensionB"),
            (self.tr("CJK Compatapility Ideographic Supplement"),
             "IsCJKCompatapilityIdeographicSupplement"),
            (self.tr("Tags"),
             "IsTags"),
        )
        
    def __populateCharTypeCombo(self, combo, isSingle):
        """
        Private method to populate a given character type selection combo box.
        
        @param combo reference to the combo box to be populated (QComboBox)
        @param isSingle flag indicating a singles combo (boolean)
        """
        for txt, value in self.comboItems:
            combo.addItem(txt, value)
        if isSingle:
            for txt, value in self.singleComboItems:
                combo.addItem(txt, value)
        
    def __addSinglesLine(self):
        """
        Private slot to add a line of entry widgets for single characters.
        """
        hbox = QWidget(self.singlesItemsBox)
        hboxLayout = QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(6)
        hbox.setLayout(hboxLayout)
        cb1 = QComboBox(hbox)
        cb1.setEditable(False)
        self.__populateCharTypeCombo(cb1, True)
        hboxLayout.addWidget(cb1)
        le1 = QLineEdit(hbox)
        le1.setValidator(self.charValidator)
        hboxLayout.addWidget(le1)
        cb1a = QComboBox(hbox)
        cb1a.setEditable(False)
        cb1a.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        hboxLayout.addWidget(cb1a)
        cb1a.hide()
        cb2 = QComboBox(hbox)
        cb2.setEditable(False)
        self.__populateCharTypeCombo(cb2, True)
        hboxLayout.addWidget(cb2)
        le2 = QLineEdit(hbox)
        le2.setValidator(self.charValidator)
        hboxLayout.addWidget(le2)
        cb2a = QComboBox(hbox)
        cb2a.setEditable(False)
        cb2a.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        hboxLayout.addWidget(cb2a)
        cb2a.hide()
        self.singlesItemsBoxLayout.addWidget(hbox)
        
        cb1.activated[int].connect(self.__singlesCharTypeSelected)
        cb2.activated[int].connect(self.__singlesCharTypeSelected)
        hbox.show()
        
        self.singlesItemsBox.adjustSize()
        
        self.singlesEntries.append([cb1, le1, cb1a])
        self.singlesEntries.append([cb2, le2, cb2a])
        
    def __addRangesLine(self):
        """
        Private slot to add a line of entry widgets for character ranges.
        """
        hbox = QWidget(self.rangesItemsBox)
        hboxLayout = QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(6)
        hbox.setLayout(hboxLayout)
        cb1 = QComboBox(hbox)
        cb1.setEditable(False)
        self.__populateCharTypeCombo(cb1, False)
        hboxLayout.addWidget(cb1)
        l1 = QLabel(self.tr("Between:"), hbox)
        hboxLayout.addWidget(l1)
        le1 = QLineEdit(hbox)
        le1.setValidator(self.charValidator)
        hboxLayout.addWidget(le1)
        l2 = QLabel(self.tr("And:"), hbox)
        hboxLayout.addWidget(l2)
        le2 = QLineEdit(hbox)
        le2.setValidator(self.charValidator)
        hboxLayout.addWidget(le2)
        self.rangesItemsBoxLayout.addWidget(hbox)
        
        cb1.activated[int].connect(self.__rangesCharTypeSelected)
        hbox.show()
        
        self.rangesItemsBox.adjustSize()
        
        self.rangesEntries.append([cb1, le1, le2])
        
    def __populateW3cCharacterCombo(self, combo, format):
        """
        Private method to populate a W3C character selection combo.
        
        @param combo combo box to be populated (QComboBox)
        @param format format identifier (one of "-ccp", "-ccn", "-cbp", "-cbn")
        """
        combo.clear()
        
        if format in ["-ccp", "-ccn"]:
            comboLen = 0
            for txt, code in self.__characterCategories:
                combo.addItem(txt, code)
                comboLen = max(comboLen, len(txt))
            combo.setMinimumContentsLength(comboLen)
        elif format in ["-cbp", "-cbn"]:
            comboLen = 0
            for txt, code in self.__characterBlocks:
                combo.addItem(txt, code)
                comboLen = max(comboLen, len(txt))
            combo.setMinimumContentsLength(comboLen)
        
    def __performSelectedAction(self, format, lineedit, combo):
        """
        Private method performing some actions depending on the input.
        
        @param format format of the selected entry (string)
        @param lineedit line edit widget to act on (QLineEdit)
        @param combo combo box widget to act on (QComboBox)
        """
        if format == "-i":
            return
        
        if format in ["-c", "-h", "-o"]:
            lineedit.show()
            lineedit.setEnabled(True)
            if combo is not None:
                combo.hide()
            if format == "-c":
                lineedit.setValidator(self.charValidator)
            elif format == "-h":
                lineedit.setValidator(self.hexValidator)
            elif format == "-o":
                lineedit.setValidator(self.octValidator)
        elif format in ["-ccp", "-ccn", "-cbp", "-cbn"]:
            lineedit.setEnabled(False)
            lineedit.hide()
            if combo is not None:
                combo.show()
            self.__populateW3cCharacterCombo(combo, format)
        else:
            lineedit.setEnabled(False)
            lineedit.hide()
            if combo is not None:
                combo.hide()
        lineedit.clear()
        
    def __singlesCharTypeSelected(self, index):
        """
        Private slot to handle the activated(int) signal of the single chars
        combo boxes.
        
        @param index selected list index (integer)
        """
        combo = self.sender()
        for entriesList in self.singlesEntries:
            if combo == entriesList[0]:
                format = combo.itemData(index)
                self.__performSelectedAction(
                    format, entriesList[1], entriesList[2])
                break
        
    def __rangesCharTypeSelected(self, index):
        """
        Private slot to handle the activated(int) signal of the char ranges
        combo boxes.
        
        @param index selected list index (integer)
        """
        combo = self.sender()
        for entriesList in self.rangesEntries:
            if combo == entriesList[0]:
                format = combo.itemData(index)
                self.__performSelectedAction(format, entriesList[1], None)
                self.__performSelectedAction(format, entriesList[2], None)
                break
        
    def __formatCharacter(self, char, format):
        """
        Private method to format the characters entered into the dialog.
        
        @param char character string entered into the dialog (string)
        @param format string giving a special format (-c, -h, -i or -o) or
            the already formatted character (string)
        @return formatted character string (string)
        """
        if format == "-c":
            return char
        elif format == "-i":
            return ""
        
        if self.__mode in [QRegExpWizardCharactersDialog.RegExpMode,
                           QRegExpWizardCharactersDialog.W3CMode]:
            if format == "-h":
                return "\\x{0}".format(char.lower())
            elif format == "-o":
                return "\\0{0}".format(char)
            elif format in ["-ccp", "-cbp"]:
                return "\\p{{{0}}}".format(char)
            elif format in ["-ccn", "-cbn"]:
                return "\\P{{{0}}}".format(char)
            else:
                return format
        
    def getCharacters(self):
        """
        Public method to return the character string assembled via the dialog.
        
        @return formatted string for character classes (string)
        """
        regexp = ""
        
        # negative character range
        if self.negativeCheckBox.isChecked():
            regexp += "^"
            
        # predefined character ranges
        if self.wordCharCheckBox.isChecked():
            regexp += "\\w"
        if self.nonWordCharCheckBox.isChecked():
            regexp += "\\W"
        if self.digitsCheckBox.isChecked():
            regexp += "\\d"
        if self.nonDigitsCheckBox.isChecked():
            regexp += "\\D"
        if self.whitespaceCheckBox.isChecked():
            regexp += "\\s"
        if self.nonWhitespaceCheckBox.isChecked():
            regexp += "\\S"
        if self.w3cInitialIdentifierCheckBox.isChecked():
            regexp += "\\i"
        if self.w3cNonInitialIdentifierCheckBox.isChecked():
            regexp += "\\I"
        if self.w3cNmtokenCheckBox.isChecked():
            regexp += "\\c"
        if self.w3cNonNmtokenCheckBox.isChecked():
            regexp += "\\C"
            
        # single characters
        for entrieslist in self.singlesEntries:
            format = entrieslist[0].itemData(entrieslist[0].currentIndex())
            if format in ["-ccp", "-ccn", "-cbp", "-cbn"]:
                char = entrieslist[2].itemData(entrieslist[2].currentIndex())
            else:
                char = entrieslist[1].text()
            regexp += self.__formatCharacter(char, format)
        
        # character ranges
        for entrieslist in self.rangesEntries:
            if not entrieslist[1].text() or \
               not entrieslist[2].text():
                continue
            format = entrieslist[0].itemData(entrieslist[0].currentIndex())
            char1 = entrieslist[1].text()
            char2 = entrieslist[2].text()
            regexp += "{0}-{1}".format(
                self.__formatCharacter(char1, format),
                self.__formatCharacter(char2, format))
        
        if regexp:
            if (regexp.startswith("\\") and
                regexp.count("\\") == 1 and
                "-" not in regexp) or \
               len(regexp) == 1:
                return regexp
            else:
                return "[{0}]".format(regexp)
        else:
            return ""
예제 #23
0
class TRPreviewer(E5MainWindow):
    """
    Class implementing the UI Previewer main window.
    """
    def __init__(self, filenames=[], parent=None, name=None):
        """
        Constructor
        
        @param filenames filenames of form and/or translation files to load
        @param parent parent widget of this window (QWidget)
        @param name name of this window (string)
        """
        self.mainWidget = None
        self.currentFile = QDir.currentPath()
        
        super(TRPreviewer, self).__init__(parent)
        if not name:
            self.setObjectName("TRPreviewer")
        else:
            self.setObjectName(name)
        
        self.setStyle(Preferences.getUI("Style"),
                      Preferences.getUI("StyleSheet"))
        
        self.resize(QSize(800, 600).expandedTo(self.minimumSizeHint()))
        self.statusBar()
        
        self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
        self.setWindowTitle(self.tr("Translations Previewer"))

        self.cw = QWidget(self)
        self.cw.setObjectName("qt_central_widget")
        
        self.TRPreviewerLayout = QVBoxLayout(self.cw)
        self.TRPreviewerLayout.setContentsMargins(6, 6, 6, 6)
        self.TRPreviewerLayout.setSpacing(6)
        self.TRPreviewerLayout.setObjectName("TRPreviewerLayout")

        self.languageLayout = QHBoxLayout()
        self.languageLayout.setContentsMargins(0, 0, 0, 0)
        self.languageLayout.setSpacing(6)
        self.languageLayout.setObjectName("languageLayout")

        self.languageLabel = QLabel(
            self.tr("Select language file"), self.cw)
        self.languageLabel.setObjectName("languageLabel")
        self.languageLayout.addWidget(self.languageLabel)

        self.languageCombo = QComboBox(self.cw)
        self.languageCombo.setObjectName("languageCombo")
        self.languageCombo.setEditable(False)
        self.languageCombo.setToolTip(self.tr("Select language file"))
        self.languageCombo.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.languageLayout.addWidget(self.languageCombo)
        
        languageSpacer = QSpacerItem(
            40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.languageLayout.addItem(languageSpacer)
        self.TRPreviewerLayout.addLayout(self.languageLayout)

        self.preview = WidgetArea(self.cw)
        self.preview.setObjectName("preview")
        self.TRPreviewerLayout.addWidget(self.preview)
        self.preview.lastWidgetClosed.connect(self.__updateActions)

        self.setCentralWidget(self.cw)
        
        self.languageCombo.activated[str].connect(self.setTranslation)
        
        self.translations = TranslationsDict(self.languageCombo, self)
        self.translations.translationChanged.connect(
            self.preview.rebuildWidgets)
        
        self.__initActions()
        self.__initMenus()
        self.__initToolbars()
        
        self.__updateActions()
        
        # fire up the single application server
        from .TRSingleApplication import TRSingleApplicationServer
        self.SAServer = TRSingleApplicationServer(self)
        self.SAServer.loadForm.connect(self.preview.loadWidget)
        self.SAServer.loadTranslation.connect(self.translations.add)
        
        # defere loading of a UI file until we are shown
        self.filesToLoad = filenames[:]
        
    def show(self):
        """
        Public slot to show this dialog.
        
        This overloaded slot loads a UI file to be previewed after
        the main window has been shown. This way, previewing a dialog
        doesn't interfere with showing the main window.
        """
        super(TRPreviewer, self).show()
        if self.filesToLoad:
            filenames, self.filesToLoad = (self.filesToLoad[:], [])
            first = True
            for fn in filenames:
                fi = QFileInfo(fn)
                if fi.suffix().lower() == 'ui':
                    self.preview.loadWidget(fn)
                elif fi.suffix().lower() == 'qm':
                    self.translations.add(fn, first)
                    first = False
            
            self.__updateActions()
        
    def closeEvent(self, event):
        """
        Protected event handler for the close event.
        
        @param event close event (QCloseEvent)
        """
        if self.SAServer is not None:
            self.SAServer.shutdown()
            self.SAServer = None
        event.accept()
        
    def __initActions(self):
        """
        Private method to define the user interface actions.
        """
        self.openUIAct = QAction(
            UI.PixmapCache.getIcon("openUI.png"),
            self.tr('&Open UI Files...'), self)
        self.openUIAct.setStatusTip(self.tr('Open UI files for display'))
        self.openUIAct.setWhatsThis(self.tr(
            """<b>Open UI Files</b>"""
            """<p>This opens some UI files for display.</p>"""
        ))
        self.openUIAct.triggered.connect(self.__openWidget)
        
        self.openQMAct = QAction(
            UI.PixmapCache.getIcon("openQM.png"),
            self.tr('Open &Translation Files...'), self)
        self.openQMAct.setStatusTip(self.tr(
            'Open Translation files for display'))
        self.openQMAct.setWhatsThis(self.tr(
            """<b>Open Translation Files</b>"""
            """<p>This opens some translation files for display.</p>"""
        ))
        self.openQMAct.triggered.connect(self.__openTranslation)
        
        self.reloadAct = QAction(
            UI.PixmapCache.getIcon("reload.png"),
            self.tr('&Reload Translations'), self)
        self.reloadAct.setStatusTip(self.tr(
            'Reload the loaded translations'))
        self.reloadAct.setWhatsThis(self.tr(
            """<b>Reload Translations</b>"""
            """<p>This reloads the translations for the loaded"""
            """ languages.</p>"""
        ))
        self.reloadAct.triggered.connect(self.translations.reload)
        
        self.exitAct = QAction(
            UI.PixmapCache.getIcon("exit.png"), self.tr('&Quit'), self)
        self.exitAct.setShortcut(QKeySequence(
            self.tr("Ctrl+Q", "File|Quit")))
        self.exitAct.setStatusTip(self.tr('Quit the application'))
        self.exitAct.setWhatsThis(self.tr(
            """<b>Quit</b>"""
            """<p>Quit the application.</p>"""
        ))
        self.exitAct.triggered.connect(qApp.closeAllWindows)
        
        self.whatsThisAct = QAction(
            UI.PixmapCache.getIcon("whatsThis.png"),
            self.tr('&What\'s This?'), self)
        self.whatsThisAct.setShortcut(QKeySequence(self.tr("Shift+F1")))
        self.whatsThisAct.setStatusTip(self.tr('Context sensitive help'))
        self.whatsThisAct.setWhatsThis(self.tr(
            """<b>Display context sensitive help</b>"""
            """<p>In What's This? mode, the mouse cursor shows an arrow"""
            """ with a question mark, and you can click on the interface"""
            """ elements to get a short description of what they do and"""
            """ how to use them. In dialogs, this feature can be accessed"""
            """ using the context help button in the titlebar.</p>"""
        ))
        self.whatsThisAct.triggered.connect(self.__whatsThis)

        self.aboutAct = QAction(self.tr('&About'), self)
        self.aboutAct.setStatusTip(self.tr(
            'Display information about this software'))
        self.aboutAct.setWhatsThis(self.tr(
            """<b>About</b>"""
            """<p>Display some information about this software.</p>"""
        ))
        self.aboutAct.triggered.connect(self.__about)
        
        self.aboutQtAct = QAction(self.tr('About &Qt'), self)
        self.aboutQtAct.setStatusTip(
            self.tr('Display information about the Qt toolkit'))
        self.aboutQtAct.setWhatsThis(self.tr(
            """<b>About Qt</b>"""
            """<p>Display some information about the Qt toolkit.</p>"""
        ))
        self.aboutQtAct.triggered.connect(self.__aboutQt)
        
        self.tileAct = QAction(self.tr('&Tile'), self)
        self.tileAct.setStatusTip(self.tr('Tile the windows'))
        self.tileAct.setWhatsThis(self.tr(
            """<b>Tile the windows</b>"""
            """<p>Rearrange and resize the windows so that they are"""
            """ tiled.</p>"""
        ))
        self.tileAct.triggered.connect(self.preview.tileSubWindows)
        
        self.cascadeAct = QAction(self.tr('&Cascade'), self)
        self.cascadeAct.setStatusTip(self.tr('Cascade the windows'))
        self.cascadeAct.setWhatsThis(self.tr(
            """<b>Cascade the windows</b>"""
            """<p>Rearrange and resize the windows so that they are"""
            """ cascaded.</p>"""
        ))
        self.cascadeAct.triggered.connect(self.preview.cascadeSubWindows)
        
        self.closeAct = QAction(
            UI.PixmapCache.getIcon("close.png"), self.tr('&Close'), self)
        self.closeAct.setShortcut(QKeySequence(self.tr(
            "Ctrl+W", "File|Close")))
        self.closeAct.setStatusTip(self.tr('Close the current window'))
        self.closeAct.setWhatsThis(self.tr(
            """<b>Close Window</b>"""
            """<p>Close the current window.</p>"""
        ))
        self.closeAct.triggered.connect(self.preview.closeWidget)
        
        self.closeAllAct = QAction(self.tr('Clos&e All'), self)
        self.closeAllAct.setStatusTip(self.tr('Close all windows'))
        self.closeAllAct.setWhatsThis(self.tr(
            """<b>Close All Windows</b>"""
            """<p>Close all windows.</p>"""
        ))
        self.closeAllAct.triggered.connect(self.preview.closeAllWidgets)

    def __initMenus(self):
        """
        Private method to create the menus.
        """
        mb = self.menuBar()

        menu = mb.addMenu(self.tr('&File'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.openUIAct)
        menu.addAction(self.openQMAct)
        menu.addAction(self.reloadAct)
        menu.addSeparator()
        menu.addAction(self.closeAct)
        menu.addAction(self.closeAllAct)
        menu.addSeparator()
        menu.addAction(self.exitAct)
        
        self.windowMenu = mb.addMenu(self.tr('&Window'))
        self.windowMenu.setTearOffEnabled(True)
        self.windowMenu.aboutToShow.connect(self.__showWindowMenu)
        self.windowMenu.triggered.connect(self.preview.toggleSelectedWidget)
        
        mb.addSeparator()
        
        menu = mb.addMenu(self.tr('&Help'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.aboutAct)
        menu.addAction(self.aboutQtAct)
        menu.addSeparator()
        menu.addAction(self.whatsThisAct)

    def __initToolbars(self):
        """
        Private method to create the toolbars.
        """
        filetb = self.addToolBar(self.tr("File"))
        filetb.setIconSize(UI.Config.ToolBarIconSize)
        filetb.addAction(self.openUIAct)
        filetb.addAction(self.openQMAct)
        filetb.addAction(self.reloadAct)
        filetb.addSeparator()
        filetb.addAction(self.closeAct)
        filetb.addSeparator()
        filetb.addAction(self.exitAct)
        
        helptb = self.addToolBar(self.tr("Help"))
        helptb.setIconSize(UI.Config.ToolBarIconSize)
        helptb.addAction(self.whatsThisAct)
    
    def __whatsThis(self):
        """
        Private slot called in to enter Whats This mode.
        """
        QWhatsThis.enterWhatsThisMode()
        
    def __updateActions(self):
        """
        Private slot to update the actions state.
        """
        if self.preview.hasWidgets():
            self.closeAct.setEnabled(True)
            self.closeAllAct.setEnabled(True)
            self.tileAct.setEnabled(True)
            self.cascadeAct.setEnabled(True)
        else:
            self.closeAct.setEnabled(False)
            self.closeAllAct.setEnabled(False)
            self.tileAct.setEnabled(False)
            self.cascadeAct.setEnabled(False)
        
        if self.translations.hasTranslations():
            self.reloadAct.setEnabled(True)
        else:
            self.reloadAct.setEnabled(False)

    def __about(self):
        """
        Private slot to show the about information.
        """
        E5MessageBox.about(
            self,
            self.tr("TR Previewer"),
            self.tr(
                """<h3> About TR Previewer </h3>"""
                """<p>The TR Previewer loads and displays Qt User-Interface"""
                """ files and translation files and shows dialogs for a"""
                """ selected language.</p>"""
            )
        )
    
    def __aboutQt(self):
        """
        Private slot to show info about Qt.
        """
        E5MessageBox.aboutQt(self, self.tr("TR Previewer"))
    
    def __openWidget(self):
        """
        Private slot to handle the Open Dialog action.
        """
        fileNameList = E5FileDialog.getOpenFileNames(
            None,
            self.tr("Select UI files"),
            "",
            self.tr("Qt User-Interface Files (*.ui)"))
        
        for fileName in fileNameList:
            self.preview.loadWidget(fileName)
        
        self.__updateActions()
    
    def __openTranslation(self):
        """
        Private slot to handle the Open Translation action.
        """
        fileNameList = E5FileDialog.getOpenFileNames(
            None,
            self.tr("Select translation files"),
            "",
            self.tr("Qt Translation Files (*.qm)"))
        
        first = True
        for fileName in fileNameList:
            self.translations.add(fileName, first)
            first = False
        
        self.__updateActions()
    
    def setTranslation(self, name):
        """
        Public slot to activate a translation.
        
        @param name name (language) of the translation (string)
        """
        self.translations.set(name)
    
    def __showWindowMenu(self):
        """
        Private slot to handle the aboutToShow signal of the window menu.
        """
        self.windowMenu.clear()
        self.windowMenu.addAction(self.tileAct)
        self.windowMenu.addAction(self.cascadeAct)
        self.windowMenu.addSeparator()

        self.preview.showWindowMenu(self.windowMenu)
    
    def reloadTranslations(self):
        """
        Public slot to reload all translations.
        """
        self.translations.reload()
예제 #24
0
파일: ui.py 프로젝트: JulianOrteil/Helix
class Ui_Helix(object):
    """Contains the widgets used in the main window of the application.

    Call :meth:`setup_ui` to build the widgets used in the window.

    Attributes:
        central_widget (:obj:`QWidget`):
            The container widget of everything in the window.
        central_layout (:obj:`QGridLayout`):
            The primary layout organizing each component of the window.
        navbar (:obj:`navbar`):
            The widget containing each button navigating to the
            different modes of the application.
        navbar_layout (:obj:`navbar_layout`):
            The layout organizing each button of the navbar.
        home_btn (:obj:`QToolButton`):
            The button, when clicked, redirecting the user to the home
            window.
        annotation_btn (:obj:`QToolButton`):
            The button, when clicked, redirecting the user to the
            annotation window.
        train_btn (:obj:`QToolButton`):
            The button, when clicked, redirecting the user to the model
            train window.
        eval_btn (:obj:`QToolButton`):
            The button, when clicked, redirecting the user to the
            evaluation window.
        navbar_spcaer (:obj:`QSpacerItem`):
            The spacer pushing all buttons to the top of the navbar.
        topbar (:obj:`QFrame`):
            The topbar containing the application logo and the minimize,
            maximize, and close buttons.
        topbar_layout (:obj:`topbar_layout`):
            The layout organizing each widget of the topbar.
        helix_logo (:obj:`QLabel`):
            The widget containing the double helix part of the logo.
        helix_logo_text(:obj:`QLabel`):
            The widget containing the 'HELIX' part of the logo.
        topbar_spcaer (:obj:`QSpacerItem`):
            The spacer pushing the logo and buttons apart.
        minimize_btn (:obj:`QToolButton`):
            The button minimizing the application.
        maximize_btn (:obj:`QToolButton`):
            The button maximizing the application.
        close_btn (:obj:`QToolButton`):
            The button closing the application.
        main_content (:obj:`QFrame`):
            The content container for each separate window.
        main_content_layout (:obj:`QHBoxLayout`):
            The layout organizing each window.
        content_bar (:obj:`QFrame`):
            The widget between the navbar and content container hosting
            each button for each window.
        content_bar_layout (:obj:`QVBoxLayout`):
            The layout organizing each button for each window.
        content_bar_spacer (:obj:`QSpacerItem`):
            The spcaer pushing each menu button to the top of the
            content_bar.
        content (:obj:`QLabel`):
            A default content window. Meant to be replaced.
    """

    central_widget: QWidget
    central_layout: QGridLayout

    navbar: QFrame
    navbar_layout: QVBoxLayout
    home_btn: QToolButton
    annotation_btn: QToolButton
    train_btn: QToolButton
    eval_btn: QToolButton
    navbar_spacer: QSpacerItem

    topbar: QFrame
    topbar_layout: QHBoxLayout
    helix_logo: QLabel
    helix_logo_text: QLabel
    topbar_spacer: QSpacerItem
    minimize_btn: QToolButton
    maximize_btn: QToolButton
    close_btn: QToolButton

    main_content: QFrame
    main_content_layout: QHBoxLayout
    content_bar: QFrame
    content_bar_layout: QVBoxLayout
    # open_file_btn: QToolButton
    # open_dataset_btn: QToolButton
    # next_image_btn: QToolButton
    # previous_image_btn: QToolButton
    content_bar_spacer: QSpacerItem
    content: QLabel

    def setup_ui(self, Helix: QMainWindow) -> None:
        """Builds the widgets for the window.

        Args:
            Helix (:obj:`QMainWindow`):
                The child window inheriting this builder class. The
                child will hold the references to every widget built in
                this class.

        Example Usage:
            >>> class Window(Ui_Helix, QMainWindow):
            ...
            ...     def __init__(self) -> None:
            ...         super().__init__()
            ...
            ...         self.setup_ui(self)
        """

        # Create base window
        Helix.resize(1920, 1080)
        Helix.setMinimumSize(QSize(800, 600))
        Helix.setObjectName("Helix")

        size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(Helix.sizePolicy().hasHeightForWidth())

        Helix.setSizePolicy(size_policy)
        Helix.setStyleSheet("* {    \n"
                            "    background-color: rgb(60, 62, 83);\n"
                            "    color: white;\n"
                            "}\n"
                            "\n"
                            "QFrame, QToolButton {\n"
                            "    background-color: rgb(42, 43, 64);\n"
                            "    border: none;\n"
                            "}\n"
                            "\n"
                            "QToolButton:hover {\n"
                            "    background-color: rgb(26, 30, 50);\n"
                            "}\n"
                            "\n"
                            "QToolButton:pressed {\n"
                            "    background-color: rgb(60, 62, 83);\n"
                            "}\n"
                            "\n"
                            "#image {\n"
                            "    background-color: rgb(26, 30, 50);\n"
                            "}\n"
                            "\n"
                            "#main_content {\n"
                            "    background-color: rgb(26, 30, 50);\n"
                            "}")

        self._setup_central_widgets(Helix)
        self._setup_navbar()
        self._setup_topbar()
        self._setup_central_content()

        Helix.setCentralWidget(self.central_widget)
        self._retranslate_ui(Helix)

    def _setup_central_widgets(self, Helix: QMainWindow) -> None:
        # Create the central widget
        self.central_widget = QWidget(Helix)
        self.central_widget.setObjectName("central_widget")

        # Create the central layout
        self.central_layout = QGridLayout(self.central_widget)
        self.central_layout.setContentsMargins(0, 0, 0, 0)
        self.central_layout.setHorizontalSpacing(3)
        self.central_layout.setObjectName("central_layout")
        self.central_layout.setVerticalSpacing(0)

    def _setup_navbar(self) -> None:
        # Create the navbar
        self.navbar = QFrame(self.central_widget)
        self.navbar.setFrameShadow(QFrame.Raised)
        self.navbar.setFrameShape(QFrame.StyledPanel)
        self.navbar.setMinimumSize(QSize(45, 0))
        self.navbar.setObjectName("navbar")

        size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        size_policy.setHorizontalStretch(1)
        size_policy.setVerticalStretch(23)
        size_policy.setHeightForWidth(
            self.navbar.sizePolicy().hasHeightForWidth())

        self.navbar.setSizePolicy(size_policy)

        # Create the navbar layout
        self.navbar_layout = QVBoxLayout(self.navbar)
        self.navbar_layout.setContentsMargins(0, 0, 0, 0)
        self.navbar_layout.setObjectName("navbar_layout")

        # Create the home btn
        self.home_btn = QToolButton(self.navbar)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/images/images/home_icon_sml.png"),
                       QIcon.Normal, QIcon.Off)

        self.home_btn.setIcon(icon)
        self.home_btn.setIconSize(QSize(45, 45))
        self.home_btn.setMinimumSize(QSize(45, 45))
        self.home_btn.setObjectName("home_btn")

        size_policy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.home_btn.sizePolicy().hasHeightForWidth())

        self.home_btn.setSizePolicy(size_policy)
        self.home_btn.setText('')

        # Create the annotation btn
        self.annotation_btn = QToolButton(self.navbar)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/images/images/annotate_icon.png"),
                       QIcon.Normal, QIcon.Off)
        self.annotation_btn.setIcon(icon)
        self.annotation_btn.setIconSize(QSize(45, 45))
        self.annotation_btn.setMinimumSize(QSize(45, 45))
        self.annotation_btn.setObjectName("annotation_btn")

        size_policy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.annotation_btn.sizePolicy().hasHeightForWidth())

        self.annotation_btn.setSizePolicy(size_policy)
        self.annotation_btn.setText('')

        # Create the train btn
        self.train_btn = QToolButton(self.navbar)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/images/images/train_icon.png"), QIcon.Normal,
                       QIcon.Off)
        self.train_btn.setIcon(icon)
        self.train_btn.setIconSize(QSize(45, 45))
        self.train_btn.setMinimumSize(QSize(45, 45))
        self.train_btn.setObjectName("train_btn")

        size_policy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.train_btn.sizePolicy().hasHeightForWidth())

        self.train_btn.setSizePolicy(size_policy)
        self.train_btn.setText('')

        # Create the eval btn
        self.eval_btn = QToolButton(self.navbar)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/images/images/evaluate_icon.png"),
                       QIcon.Normal, QIcon.Off)
        self.eval_btn.setIcon(icon)
        self.eval_btn.setIconSize(QSize(45, 45))
        self.eval_btn.setMinimumSize(QSize(45, 45))
        self.eval_btn.setObjectName("eval_btn")

        size_policy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.eval_btn.sizePolicy().hasHeightForWidth())

        self.eval_btn.setSizePolicy(size_policy)
        self.eval_btn.setText('')

        # Create the bottom spacer
        self.navbar_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                         QSizePolicy.Expanding)

        # Add the widgets to the navbar layout
        self.navbar_layout.addWidget(self.home_btn)
        self.navbar_layout.addWidget(self.annotation_btn)
        self.navbar_layout.addWidget(self.train_btn)
        self.navbar_layout.addWidget(self.eval_btn)
        self.navbar_layout.addItem(self.navbar_spacer)

        # Add the navbar to the central laytout
        self.central_layout.addWidget(self.navbar, 1, 0, 1, 1)

    def _setup_topbar(self) -> None:
        # Create the topbar
        self.topbar = QFrame(self.central_widget)
        self.topbar.setFrameShadow(QFrame.Raised)
        self.topbar.setFrameShape(QFrame.StyledPanel)
        self.topbar.setMinimumSize(QSize(0, 45))
        self.topbar.setObjectName("topbar")

        size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(1)
        size_policy.setHeightForWidth(
            self.topbar.sizePolicy().hasHeightForWidth())

        self.topbar.setSizePolicy(size_policy)

        # Create the topbar layout
        self.topbar_layout = QHBoxLayout(self.topbar)
        self.topbar_layout.setContentsMargins(0, 0, 0, 0)
        self.topbar_layout.setObjectName("topbar_layout")

        # Create the Helix logo
        self.helix_logo = QLabel(self.topbar)
        self.helix_logo.setAlignment(Qt.AlignCenter)
        self.helix_logo.setMinimumSize(QSize(45, 45))
        self.helix_logo.setObjectName("helix_logo")
        self.helix_logo.setPixmap(
            QPixmap(":/images/images/helix_icon_sml.png"))
        self.helix_logo.setScaledContents(True)
        self.helix_logo.setText('')
        self.helix_logo.setWordWrap(False)

        # Create the Helix logo text
        self.helix_logo_text = QLabel(self.topbar)
        self.helix_logo_text.setAlignment(Qt.AlignLeading | Qt.AlignLeft
                                          | Qt.AlignVCenter)

        font = QFont()
        font.setFamily("Arial Black")
        font.setItalic(True)
        font.setPointSize(16)
        font.setWeight(50)

        self.helix_logo_text.setFont(font)
        self.helix_logo_text.setObjectName("helix_logo_text")
        self.helix_logo_text.setStyleSheet('')

        # Create the topbar spacer
        self.topbar_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                         QSizePolicy.Minimum)

        # Create the minimize btn
        self.minimize_btn = QToolButton(self.topbar)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/images/images/minimize_icon.png"),
                       QIcon.Normal, QIcon.Off)

        self.minimize_btn.setIcon(icon)
        self.minimize_btn.setIconSize(QSize(20, 20))
        self.minimize_btn.setMinimumSize(QSize(45, 45))
        self.minimize_btn.setObjectName("minimize_btn")
        self.minimize_btn.setText('')

        # Create the maximize btn
        self.maximize_btn = QToolButton(self.topbar)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/images/images/maximize_icon.png"),
                       QIcon.Normal, QIcon.Off)

        self.maximize_btn.setIcon(icon)
        self.maximize_btn.setIconSize(QSize(20, 20))
        self.maximize_btn.setMinimumSize(QSize(45, 45))
        self.maximize_btn.setObjectName("maximize_btn")
        self.maximize_btn.setText('')

        # Create the close btn
        self.close_btn = QToolButton(self.topbar)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/images/images/close_icon.png"), QIcon.Normal,
                       QIcon.Off)

        self.close_btn.setIcon(icon)
        self.close_btn.setIconSize(QSize(20, 20))
        self.close_btn.setMinimumSize(QSize(45, 45))
        self.close_btn.setObjectName("close_btn")
        self.close_btn.setText('')

        # Add the widgets to the topbar layout
        self.topbar_layout.addWidget(self.helix_logo)
        self.topbar_layout.addWidget(self.helix_logo_text)
        self.topbar_layout.addItem(self.topbar_spacer)
        self.topbar_layout.addWidget(self.minimize_btn)
        self.topbar_layout.addWidget(self.maximize_btn)
        self.topbar_layout.addWidget(self.close_btn)

        # Add the topbar to the central layout
        self.central_layout.addWidget(self.topbar, 0, 0, 1, 2)

    def _setup_central_content(self) -> None:
        # Create the main content container
        self.main_content = QFrame(self.central_widget)
        self.main_content.setFrameShadow(QFrame.Raised)
        self.main_content.setFrameShape(QFrame.StyledPanel)
        self.main_content.setObjectName("main_content")

        size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        size_policy.setHorizontalStretch(42)
        size_policy.setHeightForWidth(
            self.main_content.sizePolicy().hasHeightForWidth())
        size_policy.setVerticalStretch(0)

        self.main_content.setSizePolicy(size_policy)
        self.main_content.setStyleSheet('')

        # Create the main content layout
        self.main_content_layout = QHBoxLayout(self.main_content)
        self.main_content_layout.setContentsMargins(0, 0, 0, 0)
        self.main_content_layout.setObjectName("main_content_layout")
        self.main_content_layout.setSpacing(0)

        # Create the content_bar
        self.content_bar = QFrame(self.main_content)
        self.content_bar.setFrameShadow(QFrame.Raised)
        self.content_bar.setFrameShape(QFrame.StyledPanel)
        self.content_bar.setObjectName("content_bar")

        size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size_policy.setHorizontalStretch(1)
        size_policy.setHeightForWidth(
            self.content_bar.sizePolicy().hasHeightForWidth())
        size_policy.setVerticalStretch(0)

        self.content_bar.setSizePolicy(size_policy)

        # Create the content_bar layout
        self.content_bar_layout = QVBoxLayout(self.content_bar)
        self.content_bar_layout.setObjectName("content_bar_layout")

        # Create the open single file btn
        # self.open_file_btn = QToolButton(self.content_bar)
        # self.open_file_btn.setAutoRaise(False)
        # self.open_file_btn.setEnabled(False)

        # font = QFont()
        # font.setFamilies("Segoe UI")
        # font.setPointSize(10)

        # self.open_file_btn.setFont(font)

        # icon = QIcon()
        # icon.addPixmap(
        #     QPixmap(":/images/images/open_file_icon_sml.png"),
        #     QIcon.Normal,
        #     QIcon.Off
        # )

        # self.open_file_btn.setIcon(icon)
        # self.open_file_btn.setIconSize(QSize(60, 60))
        # # self.open_file_btn.setObjectName("open_file_btn")
        # self.open_file_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        # Create the open dataset btn
        # self.open_dataset_btn = QToolButton(self.content_bar)
        # self.open_dataset_btn.setAutoRaise(False)
        # self.open_dataset_btn.setEnabled(False)

        # font = QFont()
        # font.setFamilies("Segoe UI")
        # font.setPointSize(10)

        # self.open_dataset_btn.setFont(font)

        # icon = QIcon()
        # icon.addPixmap(
        #     QPixmap(":/images/images/open_directory_icon_sml.png"),
        #     QIcon.Normal,
        #     QIcon.Off
        # )

        # self.open_dataset_btn.setIcon(icon)
        # self.open_dataset_btn.setIconSize(QSize(60, 60))
        # # self.open_dataset_btn.setObjectName("open_dataset_btn")
        # self.open_dataset_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        # Create the next image btn
        # self.next_image_btn = QToolButton(self.content_bar)
        # self.next_image_btn.setAutoRaise(False)
        # self.next_image_btn.setEnabled(False)

        # font = QFont()
        # font.setFamilies("Segoe UI")
        # font.setPointSize(10)

        # self.next_image_btn.setFont(font)

        # icon = QIcon()
        # icon.addPixmap(
        #     QPixmap(":/images/images/arrow_right_sml.png"),
        #     QIcon.Normal,
        #     QIcon.Off
        # )

        # self.next_image_btn.setIcon(icon)
        # self.next_image_btn.setIconSize(QSize(60, 60))
        # # self.next_image_btn.setObjectName("next_image_btn")
        # self.next_image_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        # Create the previous image btn
        # self.previous_image_btn = QToolButton(self.content_bar)
        # self.previous_image_btn.setAutoRaise(False)
        # self.previous_image_btn.setEnabled(False)

        # font = QFont()
        # font.setFamilies("Segoe UI")
        # font.setPointSize(10)

        # self.previous_image_btn.setFont(font)

        # icon = QIcon()
        # icon.addPixmap(
        #     QPixmap(":/images/images/arrow_left_sml.png"),
        #     QIcon.Normal,
        #     QIcon.Off
        # )

        # self.previous_image_btn.setIcon(icon)
        # self.previous_image_btn.setIconSize(QSize(60, 60))
        # # self.previous_image_btn.setObjectName("previous_image_btn")
        # self.previous_image_btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        # Create the content_bar spacer
        self.content_bar_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        # Create the content
        self.content = QLabel(self.main_content)
        self.content.setAlignment(Qt.AlignCenter)

        font = QFont()
        font.setFamily("Arial Black")
        font.setItalic(True)
        font.setKerning(True)
        font.setPointSize(20)

        self.content.setFont(font)
        self.content.setObjectName("content")

        size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size_policy.setHorizontalStretch(6)
        size_policy.setHeightForWidth(
            self.content.sizePolicy().hasHeightForWidth())
        size_policy.setVerticalStretch(0)

        self.content.setSizePolicy(size_policy)

        # Add the widgets to the content_bar layout
        # self.content_bar_layout.addWidget(self.open_file_btn)
        # self.content_bar_layout.addWidget(self.open_dataset_btn)
        # self.content_bar_layout.addWidget(self.next_image_btn)
        # self.content_bar_layout.addWidget(self.previous_image_btn)
        self.content_bar_layout.addItem(self.content_bar_spacer)

        # Add the widgets to the main content layout
        self.main_content_layout.addWidget(self.content_bar)
        self.main_content_layout.addWidget(self.content)

        # Add the main content container to the central layout
        self.central_layout.addWidget(self.main_content, 1, 1, 1, 1)

    def _retranslate_ui(self, Helix: QMainWindow) -> None:
        _translate = QCoreApplication.translate

        Helix.setWindowTitle(_translate("Helix", "Helix"))
        self.helix_logo_text.setText(_translate("Helix", "HELIX"))
        self.close_btn.setText(_translate("Helix", "X"))
        # self.open_file_btn.setShortcut(_translate("Helix", "Ctrl+O"))
        # self.open_file_btn.setText(_translate("Helix", "Open Single File\n(Ctrl + O)"))
        # self.open_dataset_btn.setShortcut(_translate("Helix", "Ctrl+Shift+O"))
        # self.open_dataset_btn.setText(
        #     _translate("Helix", "Open Dataset Directory\n(Ctrl + Shift + O)")
        # )
        # self.next_image_btn.setShortcut(_translate("Helix", "d"))
        # self.next_image_btn.setText(_translate("Helix", "Next Image (d)"))
        # self.previous_image_btn.setShortcut(_translate("Helix", "a"))
        # self.previous_image_btn.setText(_translate("Helix", "Previous Image (a)"))
        self.content.setText(
            _translate("Helix",
                       "THIS DEFAULT CONTENT WINDOW SHOULD BE REPLACED."))
예제 #25
0
class Ui_MainWindow(QMainWindow):
    #Notice that this is the parent window.
    def __init__(self, *args, **kwargs):
        super(Ui_MainWindow, self).__init__(*args, **kwargs)

#Begin page loading

    def begin(self):
        self.label.setText(label.begin())

    def complete(self):
        self.label.setText(label.complete())

#####Download functions.

    def downloads(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(self.web,
                                                  "Save as",
                                                  "",
                                                  "All Files (*)",
                                                  options=options)
        address = self.address.text()
        if fileName:
            subprocess.Popen(['wget', address, '-O', fileName])

#Set the label text.

    def loadings(self):
        self.label.setText(label.loadings())
####################################################
#####Printer functions.

    def handlePreview(self):
        dialog = QPrintPreviewDialog()
        dialog.paintRequested.connect(self.handlePaintRequest)
        dialog.exec_()

    def handlePaintRequest(self, printer):
        self.web.render(QPainter(printer))

#Set the label text.

    def printme(self):
        self.label.setText(label.printer())
####################################################
#Open html5 playback.

    def html5(self):
        subprocess.Popen(['python', '/usr/share/html5.py'])
        self.label.setText(label.html5())
####################################################
#####Page navigation functions.

#Back function.

    def backs(self, url):
        goback = self.web.back()

#Forward function.

    def forwards(self, url):
        self.web.forward()

#Reload function.

    def reloads(self):
        self.web.reload()

#System arguments support / Go to address / Find text functionality.

    def system_arguments(self):
        if len(sys.argv) == 1:
            url = self.address.text()
            if url.startswith('http://'):
                change = str(url)
                self.address.setText(change)
                load = self.address.text()
                self.label.setText(load)
                self.web.load(QUrl(load))
                del sys.argv[1:]

            elif url.startswith('https://'):
                change = str(url)
                self.address.setText(change)
                load = self.address.text()
                self.label.setText(load)
                self.web.load(QUrl(load))
                del sys.argv[1:]

            elif url.startswith('find:'):
                load = self.address.text()
                self.result0 = load.replace('find:', '')
                print "Finding:" + self.result0
                self.web.findText(self.result0)
                self.label.setText(label.finding())
                del sys.argv[1:]

            else:
                add = "https://" + url
                change = str(add)
                self.address.setText(change)
                load = self.address.text()
                self.label.setText(load)
                self.web.load(QUrl(load))
                del sys.argv[1:]

        else:
            self.location = sys.argv[1:]
            self.temp = str(self.location)
            self.result0 = self.temp.replace('[', '')
            self.result1 = self.result0.replace(']', '')
            self.result_final = self.result1.replace("'", '')

            url = self.result_final
            if url.startswith('http://'):
                change = str(url)
                self.address.setText(change)
                load = self.address.text()
                self.label.setText(load)
                self.loading1 = self.web.load(QUrl(load))
                del sys.argv[1:]

            elif url.startswith('https://'):
                change = str(url)
                self.address.setText(change)
                load = self.address.text()
                self.label.setText(load)
                self.loading1 = self.web.load(QUrl(load))
                del sys.argv[1:]

            else:
                change = str("https://" + url)
                self.address.setText(change)
                load = self.address.text()
                self.label.setText(load)
                self.web.load(QUrl(load))
                del sys.argv[1:]

#Home page function.

    def homes(self):
        self.home = "http://www.techtimejourney.net/postx_pages/postx.html"
        self.address.setText(self.home)
        self.web.load(QUrl(self.home))
####################################################
#####Page Zoom functions.

    def zoomins(self):
        self.web.setZoomFactor(self.web.zoomFactor() + .2)

    def zoomouts(self):
        self.web.setZoomFactor(self.web.zoomFactor() - .2)

##################################
#####Search engines & default (Now. Startpage).

    def extra(self):
        search = self.Search.text()
        text = self.switch_2.text()
        if text == ('wolf'):

            #Wolfram Alpha search.
            adds1 = "https://www.wolframalpha.com/input/?i=" + search
            self.web.load(QUrl(adds1))
            print adds1

        elif text == ('wiki'):

            #Wikipedia search (english).
            adds1 = "https://en.wikipedia.org/w/index.php?title=Special:Search&profile=default&fulltext=Search&search=" + search
            self.web.load(QUrl(adds1))
            print adds1

        elif text == ('tube'):

            #Youtube search (english).
            adds1 = "https://www.youtube.com/results?search_query=" + search
            self.web.load(QUrl(adds1))
            print adds1

        elif text == ('gs'):

            #Startpage search (english).
            adds1 = "https://startpage.com/do/search?query=" + search
            self.web.load(QUrl(adds1))
            print adds1

        else:
            adds1 = "https://startpage.com/do/search?query=" + search
            self.web.load(QUrl(adds1))
            print adds1

############################################
#####Bookmark functions.

    def bookmarks(self, widget):
        home = os.getenv("HOME")
        print home
        site = str(self.address.text())
        os.chdir(home)
        f = open('.bookmarks.html', 'a')
        f.write("<br>" + "<a href=" + site + ">" + site + "</a>")
        f.close()

#Set label text.

    def notice_new_bookmark(self):
        self.label.setText(label.bookmarked())

#Open bookmarks file.

    def bookopen(self, widget):
        home = os.getenv("HOME")
        print home
        home = os.getenv("HOME")
        os.chdir(home)
        head = "file:///"
        books = ".bookmarks.html"
        adds = self.address.setText(head + home + '/' + books)
        adda = self.address.text()
        self.web.load(QUrl(adda))
####################################################
#####Other functions.
#Label reset.

    def reset(self):
        self.label.setText('')

#About messagebox.

    def about(self):
        buttonReply = QMessageBox.question(
            self,
            "RunIT-QT Browser Copyright (c) 2015 JJ Posti <techtimejourney.net>",
            "RunIT-QT  comes with ABSOLUTELY NO WARRANTY;  This is free software, and you are welcome to redistribute it under  GPL Version 2, June 1991 This is the 0.6.3 version(March 2018). ___________________________________________________________________________ \n \nArgument support (since 0.6).\nStart browser like this: runit 'gooogle.fi' and follow statusbar instructions. ___________________________________________________________________________\n \nFind text from html(since 0.6).\nWrite find:something to address field and press enter to find the first entry. Press enter again to find the second entry etc. ___________________________________________________________________________\n \nRight-click menu:Save image functionality(since 0.6). Right-click upon an image and choose Copy Image address. Next choose Save image and the Save as dialog should open.",
            QMessageBox.Ok)
        if buttonReply == QMessageBox.Ok:
            pass
####################################################
#####UI Parts.

    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.setStyleSheet("background-color:#a7a7a7;font-size: 12px;")

        MainWindow.setMaximumHeight(16777215)
        MainWindow.setMaximumWidth(16777215)

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        self.toolbar = QToolBar()
        self.toolbar.setObjectName(_fromUtf8("toolbar"))
        self.verticalLayout_2 = QVBoxLayout(self.centralwidget)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))

        #Timer for label resets.
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.reset)
        self.timer.start(9000)  #Update within every 9 seconds.

        #Back.
        self.back = QToolButton()
        self.back.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon = QIcon()
        icon.addPixmap(QPixmap(_fromUtf8(":/icons/back.png")), QIcon.Normal,
                       QIcon.Off)
        self.back.setIcon(icon)
        self.back.setObjectName(_fromUtf8("back"))
        self.back.setToolTip('Go Back')
        self.back.clicked.connect(self.backs)
        self.back.setFixedSize(24, 24)
        self.toolbar.addWidget(self.back)

        #Address.
        self.address = QLineEdit()
        self.address.setStyleSheet(
            "QLineEdit{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QLineEdit:hover{background-color:#5c5c5c;}")
        self.address.setObjectName(_fromUtf8("lineEdit"))
        self.address.setPlaceholderText("Type an address")
        self.address.returnPressed.connect(self.system_arguments)
        self.toolbar.addWidget(self.address)

        #Forward.
        self.forward = QToolButton()
        self.forward.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon1 = QIcon()
        icon1.addPixmap(QPixmap(_fromUtf8(":/icons/forward.png")),
                        QIcon.Normal, QIcon.Off)
        self.forward.setIcon(icon1)
        self.forward.setObjectName(_fromUtf8("forward"))
        self.forward.setToolTip('Go Forward')
        self.forward.clicked.connect(self.forwards)
        self.forward.setFixedSize(24, 24)
        self.toolbar.addWidget(self.forward)

        #Home.
        self.home = QToolButton()
        self.home.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon2 = QIcon()
        icon2.addPixmap(QPixmap(_fromUtf8(":/icons/home.png")), QIcon.Normal,
                        QIcon.Off)
        self.home.setIcon(icon2)
        self.home.setObjectName(_fromUtf8("home"))
        self.home.setToolTip('Go Home')
        self.home.clicked.connect(self.homes)
        self.home.setFixedSize(24, 24)
        self.toolbar.addWidget(self.home)

        #Reload.
        self.reloading = QToolButton()
        self.reloading.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon3 = QIcon()
        icon3.addPixmap(QPixmap(_fromUtf8(":/icons/reload.png")), QIcon.Normal,
                        QIcon.Off)
        self.reloading.setIcon(icon3)
        self.reloading.setObjectName(_fromUtf8("reload"))
        self.reloading.setToolTip('Reload Page')
        self.reloading.clicked.connect(self.reloads)
        self.reloading.setFixedSize(24, 24)
        self.toolbar.addWidget(self.reloading)

        #Html5 player.
        self.vlc = QToolButton()
        self.vlc.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon4 = QIcon()
        icon4.addPixmap(QPixmap(_fromUtf8(":/icons/vlc_play.png")),
                        QIcon.Normal, QIcon.Off)
        self.vlc.setIcon(icon4)
        self.vlc.setObjectName(_fromUtf8("vlc"))
        self.vlc.setToolTip('Open HTML5 player')
        self.vlc.clicked.connect(self.html5)
        self.vlc.setFixedSize(24, 24)
        self.toolbar.addWidget(self.vlc)

        #Bookmark.
        self.bookmark = QToolButton()
        self.bookmark.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon5 = QIcon()
        icon5.addPixmap(QPixmap(_fromUtf8(":/icons/bookmark.png")),
                        QIcon.Normal, QIcon.Off)
        self.bookmark.setIcon(icon5)
        self.bookmark.setObjectName(_fromUtf8("bookmark"))
        self.bookmark.setToolTip('Bookmark addressbar location')
        self.bookmark.clicked.connect(self.bookmarks)
        self.bookmark.clicked.connect(self.notice_new_bookmark)
        self.bookmark.setFixedSize(24, 24)
        self.toolbar.addWidget(self.bookmark)

        #Open Bookmarks.
        self.see_bookmark = QToolButton()
        self.see_bookmark.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon6 = QIcon()
        icon6.addPixmap(QPixmap(_fromUtf8(":/icons/seebook.png")),
                        QIcon.Normal, QIcon.Off)
        self.see_bookmark.setIcon(icon6)
        self.see_bookmark.setObjectName(_fromUtf8("see_bookmark"))
        self.see_bookmark.setToolTip('See Bookmarks')
        self.see_bookmark.clicked.connect(self.bookopen)
        self.see_bookmark.setFixedSize(24, 24)
        self.toolbar.addWidget(self.see_bookmark)

        #Download.
        self.download = QToolButton()
        self.download.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon7 = QIcon()
        icon7.addPixmap(QPixmap(_fromUtf8(":/icons/download.png")),
                        QIcon.Normal, QIcon.Off)
        self.download.setIcon(icon7)
        self.download.setObjectName(_fromUtf8("download"))
        self.download.setToolTip('Download file from location')
        self.download.clicked.connect(self.downloads)
        self.download.clicked.connect(self.loadings)
        self.download.setFixedSize(24, 24)
        self.toolbar.addWidget(self.download)

        #Search Switch.
        self.switch_2 = QLineEdit()
        self.switch_2.setStyleSheet(
            "QLineEdit{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QLineEdit:hover{background-color:#5c5c5c;}")
        self.switch_2.setObjectName(_fromUtf8("switch_2"))
        self.switch_2.setPlaceholderText("Switch")
        self.switch_2.setFixedSize(50, 24)
        self.switch_2.setToolTip(
            'gs=Startpage, wiki = Wikipedia,  tube = Youtube,  wolf = Wolfram Alpha. Empty = Startpage search (default)'
        )
        self.switch_2.returnPressed.connect(self.extra)
        self.toolbar.addWidget(self.switch_2)

        #Search.
        self.Search = QLineEdit()
        self.Search.setStyleSheet(
            "QLineEdit{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QLineEdit:hover{background-color:#5c5c5c;}")
        self.Search.setObjectName(_fromUtf8("Search"))
        self.Search.setPlaceholderText("Search something")
        self.Search.setToolTip('Search')
        self.Search.returnPressed.connect(self.extra)
        self.toolbar.addWidget(self.Search)

        #Printing.
        self.printing = QToolButton()
        self.printing.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon8 = QIcon()
        icon8.addPixmap(QPixmap(_fromUtf8(":/icons/print.png")), QIcon.Normal,
                        QIcon.Off)
        self.printing.setIcon(icon8)
        self.printing.setObjectName(_fromUtf8("print"))
        self.printing.setToolTip('Print')
        self.printing.clicked.connect(self.handlePreview)
        self.printing.clicked.connect(self.printme)
        self.printing.setFixedSize(24, 24)
        self.toolbar.addWidget(self.printing)

        #Zoom +.
        self.zoom_in = QToolButton()
        self.zoom_in.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon9 = QIcon()
        icon9.addPixmap(QPixmap(_fromUtf8(":/icons/zoom-in.png")),
                        QIcon.Normal, QIcon.Off)
        self.zoom_in.setIcon(icon9)
        self.zoom_in.setObjectName(_fromUtf8("zoom_in"))
        self.zoom_in.setToolTip('Zoom +')
        self.zoom_in.clicked.connect(self.zoomins)
        self.zoom_in.setFixedSize(24, 24)
        self.toolbar.addWidget(self.zoom_in)

        #Zoom -.
        self.zoom_out = QToolButton()
        self.zoom_out.setStyleSheet(
            "QToolButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QToolButton:hover{background-color:#5c5c5c;}")
        icon10 = QIcon()
        icon10.addPixmap(QPixmap(_fromUtf8(":/icons/zoom-out.png")),
                         QIcon.Normal, QIcon.Off)
        self.zoom_out.setIcon(icon10)
        self.zoom_out.setObjectName(_fromUtf8("zoom_out"))
        self.zoom_out.setToolTip('Zoom -')
        self.zoom_out.clicked.connect(self.zoomouts)
        self.zoom_out.setFixedSize(24, 24)
        self.toolbar.addWidget(self.zoom_out)

        #About.
        self.about1 = QPushButton()
        self.about1.setObjectName("Info")
        self.about1.setStyleSheet(
            "QPushButton{color:#ffffff; background-color:#353535; border: 2px solid #353535; border-radius: 3px;font-size: 12px;}"
            "QPushButton:hover{background-color:#5c5c5c;}")
        self.about1.setText("i")
        self.about1.setToolTip('Info')
        self.about1.setFixedSize(24, 24)
        self.about1.clicked.connect(self.about)
        self.toolbar.addWidget(self.about1)

        #Web browser.
        self.web = NewWindow(self.centralwidget)
        self.web.titleChanged = self.setWindowTitle
        self.web.urlChanged.connect(
            lambda x: self.address.setText(x.toString()))
        self.web.loadStarted.connect(self.begin)
        self.web.loadFinished.connect(self.complete)

        #Label as a secondary address placeholder.
        self.label = QLabel()
        self.label.setFixedSize(500, 16)
        self.label.setText(
            "Click addressbar and press enter if you supplied arguments.")
        self.web.setObjectName(_fromUtf8("kwebview"))
        self.web.setMaximumHeight(16777215)
        self.web.setMaximumWidth(16777215)

        #Adding to layout.
        MainWindow.setCentralWidget(self.centralwidget)
        self.verticalLayout_2.addWidget(self.toolbar)
        self.verticalLayout_2.addWidget(self.web)
        self.verticalLayout_2.addWidget(self.label)

        #Web inspector.
        self.inspector = QWebInspector()

        self.web.page().settings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        self.inspector.setPage(self.web.page())

        #More Browser settings.
        self.web.page().settings().setAttribute(QWebSettings.JavascriptEnabled,
                                                True)
        self.web.page().settings().setAttribute(
            QWebSettings.LocalContentCanAccessFileUrls, True)
        self.web.page().settings().setAttribute(
            QWebSettings.LocalContentCanAccessRemoteUrls, True)
        self.web.page().settings().setAttribute(
            QWebSettings.LocalStorageEnabled, True)
        self.web.page().settings().setAttribute(QWebSettings.PluginsEnabled,
                                                True)
        self.web.page().settings().setAttribute(
            QWebSettings.PrivateBrowsingEnabled, False)
        self.web.page().settings().setAttribute(
            QWebSettings.SpatialNavigationEnabled, True)
        self.web.page().settings().setAttribute(QWebSettings.AutoLoadImages,
                                                True)
        self.web.page().settings().setAttribute(
            QWebSettings.AcceleratedCompositingEnabled, True)
        ####################################################
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "RunIT-QT", None))
        self.back.setText(_translate("MainWindow", "Back", None))
        self.forward.setText(_translate("MainWindow", "Forward\n" "", None))
        self.home.setText(_translate("MainWindow", "Home", None))
        self.reloading.setText(_translate("MainWindow", "Reload\n" "", None))
        self.vlc.setText(_translate("MainWindow", "Vlc Play", None))
        self.bookmark.setText(_translate("MainWindow", "Bookmarkl", None))
        self.see_bookmark.setText(
            _translate("MainWindow", "See bookmarks", None))
        self.download.setText(_translate("MainWindow", "Download", None))
        self.printing.setText(_translate("MainWindow", "Print", None))
        self.zoom_in.setText(_translate("MainWindow", "Zoom+", None))
        self.zoom_out.setText(_translate("MainWindow", "Zoom-", None))
예제 #26
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(533, 388)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.mainGridLayout = QGridLayout()
        self.mainGridLayout.setObjectName(_fromUtf8("mainGridLayout"))
        self.z_Spin = QSpinBox(self.centralwidget)
        self.z_Spin.setMinimum(1)
        self.z_Spin.setObjectName(_fromUtf8("z_Spin"))
        self.mainGridLayout.addWidget(self.z_Spin, 2, 0, 1, 2)
        self.time_Spin = QSpinBox(self.centralwidget)
        self.time_Spin.setMinimum(1)
        self.time_Spin.setObjectName(_fromUtf8("time_Spin"))
        self.mainGridLayout.addWidget(self.time_Spin, 2, 2, 1, 1)
        self.openFile_Button = QPushButton(self.centralwidget)
        self.openFile_Button.setObjectName(_fromUtf8("openFile_Button"))
        self.mainGridLayout.addWidget(self.openFile_Button, 0, 0, 1, 1)
        self.DIC_Spin = QSpinBox(self.centralwidget)
        self.DIC_Spin.setMinimum(1)
        self.DIC_Spin.setObjectName(_fromUtf8("DIC_Spin"))
        self.mainGridLayout.addWidget(self.DIC_Spin, 2, 4, 1, 1)
        self.Z_Label = QLabel(self.centralwidget)
        self.Z_Label.setObjectName(_fromUtf8("Z_Label"))
        self.mainGridLayout.addWidget(self.Z_Label, 1, 0, 1, 2)
        self.correctAtt_Check = QCheckBox(self.centralwidget)
        self.correctAtt_Check.setObjectName(_fromUtf8("correctAtt_Check"))
        self.mainGridLayout.addWidget(self.correctAtt_Check, 3, 4, 1, 1)
        self.Ch_label = QLabel(self.centralwidget)
        self.Ch_label.setObjectName(_fromUtf8("Ch_label"))
        self.mainGridLayout.addWidget(self.Ch_label, 1, 3, 1, 1)
        self.Bkgd_horizontalLayout = QHBoxLayout()
        self.Bkgd_horizontalLayout.setObjectName(
            _fromUtf8("Bkgd_horizontalLayout"))
        self.removeBG_Check = QCheckBox(self.centralwidget)
        self.removeBG_Check.setObjectName(_fromUtf8("removeBG_Check"))
        self.Bkgd_horizontalLayout.addWidget(self.removeBG_Check)
        self.customize_Check = QCheckBox(self.centralwidget)
        self.customize_Check.setObjectName(_fromUtf8("customize_Check"))
        self.Bkgd_horizontalLayout.addWidget(self.customize_Check)
        self.mainGridLayout.addLayout(self.Bkgd_horizontalLayout, 3, 2, 1, 2)
        self.comboBox = QComboBox(self.centralwidget)
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.mainGridLayout.addWidget(self.comboBox, 4, 0, 3, 2)
        self.fileName_Line = QLineEdit(self.centralwidget)
        self.fileName_Line.setObjectName(_fromUtf8("fileName_Line"))
        self.mainGridLayout.addWidget(self.fileName_Line, 0, 1, 1, 4)
        self.correctDrift_Check = QCheckBox(self.centralwidget)
        self.correctDrift_Check.setObjectName(_fromUtf8("correctDrift_Check"))
        self.mainGridLayout.addWidget(self.correctDrift_Check, 3, 0, 1, 2)
        self.T_Label = QLabel(self.centralwidget)
        self.T_Label.setObjectName(_fromUtf8("T_Label"))
        self.mainGridLayout.addWidget(self.T_Label, 1, 2, 1, 1)
        self.DIC_label = QLabel(self.centralwidget)
        self.DIC_label.setObjectName(_fromUtf8("DIC_label"))
        self.mainGridLayout.addWidget(self.DIC_label, 1, 4, 1, 1)
        self.channel_Spin = QSpinBox(self.centralwidget)
        self.channel_Spin.setMinimum(1)
        self.channel_Spin.setMaximum(5)
        self.channel_Spin.setObjectName(_fromUtf8("channel_Spin"))
        self.mainGridLayout.addWidget(self.channel_Spin, 2, 3, 1, 1)
        self.run_Button = QPushButton(self.centralwidget)
        self.run_Button.setObjectName(_fromUtf8("run_Button"))
        self.mainGridLayout.addWidget(self.run_Button, 9, 0, 1, 1)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.resolution_Spin = QDoubleSpinBox(self.centralwidget)
        self.resolution_Spin.setSingleStep(0.01)
        self.resolution_Spin.setProperty("value", 0.21)
        self.resolution_Spin.setObjectName(_fromUtf8("resolution_Spin"))
        self.horizontalLayout.addWidget(self.resolution_Spin)
        self.resolution_Label = QLabel(self.centralwidget)
        self.resolution_Label.setObjectName(_fromUtf8("resolution_Label"))
        self.horizontalLayout.addWidget(self.resolution_Label)
        self.mainGridLayout.addLayout(self.horizontalLayout, 7, 0, 2, 2)
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.correctAtt_Spin = QDoubleSpinBox(self.centralwidget)
        self.correctAtt_Spin.setMaximum(1.0)
        self.correctAtt_Spin.setMinimum(0.01)
        self.correctAtt_Spin.setValue(0.1)
        self.correctAtt_Spin.setSingleStep(0.01)
        self.correctAtt_Spin.setObjectName(_fromUtf8("correctAtt_Spin"))
        self.verticalLayout.addWidget(self.correctAtt_Spin)
        spacerItem = QSpacerItem(88, 37, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem)
        self.mainGridLayout.addLayout(self.verticalLayout, 4, 4, 5, 1)
        self.featureSize_verticalLayout = QVBoxLayout()
        self.featureSize_verticalLayout.setObjectName(
            _fromUtf8("featureSize_verticalLayout"))
        self.horizontalLayout_1 = QHBoxLayout()
        self.horizontalLayout_1.setObjectName(_fromUtf8("horizontalLayout_1"))
        self.featureSize1_Label = QLabel(self.centralwidget)
        self.featureSize1_Label.setEnabled(True)
        self.featureSize1_Label.setObjectName(_fromUtf8("featureSize1_Label"))
        self.horizontalLayout_1.addWidget(self.featureSize1_Label)
        self.featureSize1_Spin = oddSpinBox(self.centralwidget)
        self.featureSize1_Spin.setEnabled(True)
        self.featureSize1_Spin.setMaximum(999)
        self.featureSize1_Spin.setSingleStep(2)
        self.featureSize1_Spin.setObjectName(_fromUtf8("featureSize1_Spin"))
        self.horizontalLayout_1.addWidget(self.featureSize1_Spin)
        self.featureSize_verticalLayout.addLayout(self.horizontalLayout_1)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.featureSize2_Label = QLabel(self.centralwidget)
        self.featureSize2_Label.setEnabled(True)
        self.featureSize2_Label.setObjectName(_fromUtf8("featureSize2_Label"))
        self.horizontalLayout_2.addWidget(self.featureSize2_Label)
        self.featureSize2_Spin = oddSpinBox(self.centralwidget)
        self.featureSize2_Spin.setEnabled(True)
        self.featureSize2_Spin.setMaximum(999)
        self.featureSize2_Spin.setSingleStep(2)
        self.featureSize2_Spin.setObjectName(_fromUtf8("featureSize2_Spin"))
        self.horizontalLayout_2.addWidget(self.featureSize2_Spin)
        self.featureSize_verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
        self.featureSize3_Label = QLabel(self.centralwidget)
        self.featureSize3_Label.setEnabled(True)
        self.featureSize3_Label.setObjectName(_fromUtf8("featureSize3_Label"))
        self.horizontalLayout_3.addWidget(self.featureSize3_Label)
        self.featureSize3_Spin = oddSpinBox(self.centralwidget)
        self.featureSize3_Spin.setEnabled(True)
        self.featureSize3_Spin.setMaximum(999)
        self.featureSize3_Spin.setSingleStep(2)
        self.featureSize3_Spin.setObjectName(_fromUtf8("featureSize3_Spin"))
        self.horizontalLayout_3.addWidget(self.featureSize3_Spin)
        self.featureSize_verticalLayout.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
        self.featureSize4_Label = QLabel(self.centralwidget)
        self.featureSize4_Label.setEnabled(True)
        self.featureSize4_Label.setObjectName(_fromUtf8("featureSize4_Label"))
        self.horizontalLayout_5.addWidget(self.featureSize4_Label)
        self.featureSize4_Spin = oddSpinBox(self.centralwidget)
        self.featureSize4_Spin.setEnabled(True)
        self.featureSize4_Spin.setMaximum(999)
        self.featureSize4_Spin.setSingleStep(2)
        self.featureSize4_Spin.setObjectName(_fromUtf8("featureSize4_Spin"))
        self.horizontalLayout_5.addWidget(self.featureSize4_Spin)
        self.featureSize_verticalLayout.addLayout(self.horizontalLayout_5)
        self.horizontalLayout_8 = QHBoxLayout()
        self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
        self.featureSize5_Label = QLabel(self.centralwidget)
        self.featureSize5_Label.setEnabled(True)
        self.featureSize5_Label.setObjectName(_fromUtf8("featureSize5_Label"))
        self.horizontalLayout_8.addWidget(self.featureSize5_Label)
        self.featureSize5_Spin = oddSpinBox(self.centralwidget)
        self.featureSize5_Spin.setEnabled(True)
        self.featureSize5_Spin.setMaximum(999)
        self.featureSize5_Spin.setSingleStep(2)
        self.featureSize5_Spin.setObjectName(_fromUtf8("featureSize5_Spin"))
        self.horizontalLayout_8.addWidget(self.featureSize5_Spin)
        self.featureSize_verticalLayout.addLayout(self.horizontalLayout_8)
        spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.featureSize_verticalLayout.addItem(spacerItem1)
        self.mainGridLayout.addLayout(self.featureSize_verticalLayout, 4, 2, 5,
                                      2)
        self.gridLayout.addLayout(self.mainGridLayout, 0, 0, 1, 1)
        self.resolution_Label.raise_()
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusBar = QStatusBar(MainWindow)
        self.statusBar.setObjectName(_fromUtf8("statusBar"))
        MainWindow.setStatusBar(self.statusBar)

        self.featureSpins = [
            self.featureSize1_Spin, self.featureSize2_Spin,
            self.featureSize3_Spin, self.featureSize4_Spin,
            self.featureSize5_Spin
        ]
        self.featureLabels = [
            self.featureSize1_Label, self.featureSize2_Label,
            self.featureSize3_Label, self.featureSize4_Label,
            self.featureSize5_Label
        ]
        self.defaultFeatureValue = 301
        self.initialSetup()

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

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.openFile_Button.setText(_translate("MainWindow", "Open", None))
        self.Z_Label.setText(_translate("MainWindow", "Z", None))
        self.correctAtt_Check.setText(
            _translate("MainWindow", "Correct Attenuation", None))
        self.Ch_label.setText(_translate("MainWindow", "C", None))
        self.removeBG_Check.setText(
            _translate("MainWindow", "Remove Bkgd", None))
        self.customize_Check.setText(
            _translate("MainWindow", "Customize", None))
        self.comboBox.setItemText(0, _translate("MainWindow", "czt", None))
        self.comboBox.setItemText(1, _translate("MainWindow", "zct", None))
        self.correctDrift_Check.setText(
            _translate("MainWindow", "Correct Drift", None))
        self.T_Label.setText(_translate("MainWindow", "T", None))
        self.DIC_label.setText(_translate("MainWindow", "DIC", None))
        self.run_Button.setText(_translate("MainWindow", "Run", None))
        self.resolution_Label.setText(_translate("MainWindow", "um/pix", None))
        self.featureSize1_Label.setText(
            _translate("MainWindow", "Feature Size Ch X", None))
        self.featureSize2_Label.setText(
            _translate("MainWindow", "Feature Size Ch 2", None))
        self.featureSize3_Label.setText(
            _translate("MainWindow", "Feature Size Ch 3", None))
        self.featureSize4_Label.setText(
            _translate("MainWindow", "Feature Size Ch 4", None))
        self.featureSize5_Label.setText(
            _translate("MainWindow", "Feature Size Ch 5", None))

    def initialSetup(self):
        for feature in self.featureSpins:
            feature.setValue(self.defaultFeatureValue)
        self.noBckgdChecked()
        self.correctAttClicked(False)
        self.run_Button.setEnabled(False)

        self.z_Spin.setValue(18)
        self.time_Spin.setValue(4)
        self.channel_Spin.setValue(3)
        self.DIC_Spin.setValue(3)
        self.fileName_Line.setText(
            '/home/renat/Documents/work/development/example/W9F004T0001Z01C1.tif'
        )

        # #         self.z_Spin.setValue(1)
        # #         self.time_Spin.setValue(17)
        # #         self.channel_Spin.setValue(3)
        # #         self.DIC_Spin.setValue(1)
        # #         self.fileName_Line.setText('/home/renat/Documents/work/development/test/TESTME_BGLI141_1B_t2.tif')
        #
        # #         self.z_Spin.setValue(5)
        # #         self.time_Spin.setValue(7)
        # #         self.channel_Spin.setValue(3)
        # #         self.DIC_Spin.setValue(3)
        # #         self.fileName_Line.setText('/home/renat/Documents/work/development/test/OD3465-0002.tif_Files/OD3465-0002_z0t0c0.tif')
        self.run_Button.setEnabled(True)

    #
    # #         self.z_Spin.setValue(5)
    # #         self.time_Spin.setValue(7)
    # #         self.channel_Spin.setValue(3)
    # #         self.DIC_Spin.setValue(3)
    # #         self.fileName_Line.setText('/home/renat/Documents/work/development/test/OD3465-0003_2x2.tif_Files/OD3465-0003_2x2_z0t0c0.tif')
    # #         self.resolution_Spin.setValue(0.42)
    # #         self.run_Button.setEnabled(True)0

    def connectUI(self):
        self.openFile_Button.clicked.connect(self.openFile)
        self.run_Button.clicked.connect(self.run)
        self.correctAtt_Check.toggled.connect(self.correctAttClicked)

        self.channel_Spin.valueChanged.connect(self.channelNumChanged)
        self.DIC_Spin.valueChanged.connect(self.DIC_changed)
        self.removeBG_Check.toggled.connect(self.removeBGClicked)
        self.customize_Check.toggled.connect(self.customBGClicked)

    #         for i in range(len(self.featureSpins)):
    #             self.featureSpins[i].valueChanged.connect(self.checkOdd)

    def openFile(self):
        fileFilter = "TIF (*.tif)"
        fileName = QFileDialog.getOpenFileName(
            self.centralwidget, 'Open File',
            '/home/renat/Documents/work/development/Well005/', fileFilter)
        self.fileName_Line.setText(_translate("MainWindow", fileName[0], None))
        self.run_Button.setEnabled(True)

    def correctAttClicked(self, state):
        self.correctAtt_Spin.setEnabled(state)
        self.correctAtt_Spin.setVisible(state)
        if state:
            self.removeBG_Check.setChecked(True)

    def removeBGClicked(self, state):
        if state:
            self.customize_Check.setVisible(True)
            self.customize_Check.setEnabled(True)
            if self.channel_Spin.value() > 1: self.showFeatureSize(0, True)
        else:
            self.noBckgdChecked()

    def customBGClicked(self, state):
        nCh = self.channel_Spin.value()
        if state:
            self.showFeatureSize(0, False)
            self.featureSize1_Label.setText("Feature Size Ch 1")
            for i in range(nCh):
                if i != self.DIC_Spin.value() - 1:
                    self.showFeatureSize(i, True)
        else:
            self.hideAllFeatures()
            self.featureSize1_Label.setText("Feature Size Ch X")
            if self.channel_Spin.value() > 1: self.showFeatureSize(0, True)

    def channelNumChanged(self, nCh):
        self.DIC_Spin.setMaximum(nCh)
        if self.customize_Check.isChecked():
            self.customBGClicked(False)
            self.customBGClicked(True)

    def DIC_changed(self):
        if self.customize_Check.isChecked():
            self.customBGClicked(False)
            self.customBGClicked(True)

    def hideAllFeatures(self):
        for i in range(len(self.featureLabels)):
            self.showFeatureSize(i, False)

    def noBckgdChecked(self):
        self.correctAtt_Check.setChecked(False)
        self.hideAllFeatures()
        self.customize_Check.setChecked(False)
        self.customize_Check.setEnabled(False)
        self.customize_Check.setVisible(False)

    def showFeatureSize(self, ch, bool):
        self.featureSpins[ch].setEnabled(bool)
        self.featureSpins[ch].setVisible(bool)
        self.featureLabels[ch].setVisible(bool)

    def checkOdd(self, val):
        if val % 2 == 0:
            self.centralwidget.sender().setValue(val + 1)

    def run(self):
        self.statusBar.showMessage('Running...')
        QApplication.processEvents()
        if self.customize_Check.isChecked():
            featureList = []
            for f in self.featureSpins:
                featureList.append(f.value())
        else:
            featureList = [
                self.featureSize1_Spin.value()
                for i in range(self.channel_Spin.value())
            ]
        featureList[self.DIC_Spin.value() - 1] = None
        self.statusBar.showMessage('Loading images...')
        imgs = self.openImage()
        self.statusBar.showMessage('Cropping...')
        try:
            allEmbs = cropAPI.cropEmbs(imgs, self.DIC_Spin.value() - 1, self.correctDrift_Check.isChecked(), \
                                       self.correctAtt_Check.isChecked(), self.correctAtt_Spin.value(),
                                       self.removeBG_Check.isChecked(), featureList, self.resolution_Spin.value())
            self.save(allEmbs)
        except Exception as err:
            QMessageBox.warning(self.centralwidget, 'Error',
                                traceback.format_exc())
            self.statusBar.showMessage('Error: ' + str(err))

    def openImage(self):
        path, nZ, nT, nCh, order = str(self.fileName_Line.text()), self.z_Spin.value(), self.time_Spin.value(), \
                                   self.channel_Spin.value(), str(self.comboBox.currentText())
        if os.path.isfile(path):
            ims = myFunc.loadImTif(path)
            if len(ims.shape) == 2:
                path = '/'.join(path.split('/')[:-1]) + '/'
                ims = myFunc.loadImFolder(path)
        elif os.path.isdir(path):
            ims = myFunc.loadImFolder(path)
        else:
            raise ('Error: wrong path {0}'.format(path))
        if len(ims.shape) > 3:
            ims = np.reshape(ims, (-1, ims.shape[-2], ims.shape[-1]))
        if np.array(ims).size == nZ * nT * nCh * ims[0].size:
            if order == 'czt':
                ims = np.reshape(ims, (nT, nZ, nCh, ims[0].shape[0],
                                       ims[0].shape[1])).astype(np.float)
            else:
                ims = np.reshape(ims, (nT, nCh, nZ, ims[0].shape[0],
                                       ims[0].shape[1])).astype(np.float)
                ims = np.swapaxes(ims, 1, 2)
        else:
            self.statusBar.showMessage(
                'Error: number of images (or sizes) does not correspond to z={0}, t={1}, ch={2}'
                .format(nZ, nT, nCh))
            raise Exception(
                'Error: number of images (or sizes) does not correspond to z={0}, t={1}, ch={2}'
                .format(nZ, nT, nCh))
        return ims

    def save(self, allEmbs):
        path = '/'.join(str(self.fileName_Line.text()).split('/')[:-1]) + '/'
        if not os.path.exists(path + 'crop/'): myFunc.mkdir_p(path + 'crop/')
        for i in range(len(allEmbs)):
            self.statusBar.showMessage('saving Embryo {}'.format(i + 1))
            myFunc.saveImagesMulti(allEmbs[i].astype(np.uint16),
                                   path + 'crop/Emb{0:02}.tif'.format(i))
        self.statusBar.showMessage('embryos saved')
예제 #27
0
class WMagnetOut(QGroupBox):
    """Setup of QGroupBox for output for Magnet
    """
    def __init__(self, parent=None):
        """Initialize the widget
        """

        QWidget.__init__(self, parent)
        self.u = gui_option.unit
        # Setup main widget
        self.setTitle(self.tr("Output"))
        self.setMinimumSize(QSize(200, 0))
        self.setObjectName("g_output")
        self.layout = QVBoxLayout(self)
        self.layout.setObjectName("layout")
        # The widget is composed of several QLabel in a vertical layout
        self.out_Smag = QLabel(self)
        self.out_Smag.setObjectName("out_Smag")
        self.layout.addWidget(self.out_Smag)

        self.out_gap = QLabel(self)
        self.out_gap.setObjectName("out_gap")
        self.layout.addWidget(self.out_gap)

        self.out_gap_min = QLabel(self)
        self.out_gap_min.setObjectName("out_gap_min")
        self.layout.addWidget(self.out_gap_min)

        self.out_taum = QLabel(self)
        self.out_taum.setObjectName("out_taum")
        self.layout.addWidget(self.out_taum)

    def comp_output(self):
        """Update the Output text with the computed values

        Parameters
        ----------
        self : WMagnetOut
            A WMagnetOut object
        """
        mach = self.parent().machine
        # Gap is set in SMachineDimension
        gap = format(self.u.get_m(mach.comp_width_airgap_mag()), ".4g")
        self.out_gap.setText(
            self.tr("gap: ") + gap + " " + self.u.get_m_name())

        mag_txt = self.tr("Magnet surface: ")
        gm_txt = self.tr("gap_min: ")
        taum_txt = self.tr("taum: ")

        if self.parent().check() is None:
            # We compute the output only if the slot is correctly set
            Zs = mach.rotor.slot.Zs
            # Compute all the needed output as string (scientific notation with
            # 2 digits)
            Smag = format(
                self.u.get_m2(mach.rotor.slot.magnet[0].comp_surface()), ".4g")
            gap_min = format(self.u.get_m(mach.comp_width_airgap_mec()), ".4g")

            taum = 100 * mach.rotor.slot.magnet[0].comp_ratio_opening(Zs / 2.0)
            taum = "%.4g" % (taum)

            # Update the GUI to display the Output
            self.out_Smag.setText(mag_txt + Smag + " " + self.u.get_m2_name())
            self.out_gap_min.setText(gm_txt + gap_min + " " +
                                     self.u.get_m_name())
            self.out_taum.setText(taum_txt + taum + " %")
        else:
            # We can't compute the output => We erase the previous version
            # (that way the user know that something is wrong without
            # clicking next)
            self.out_Smag.setText(mag_txt + "?")
            self.out_gap_min.setText(gm_txt + "?")
            self.out_taum.setText(taum_txt + " ?")
class MenuContainers:
    def __init__(self, page_containers_grid_layout: QGridLayout,
                 gui_concentrate_handler):
        super(MenuContainers, self).__init__()
        self.gui_concentrate_handler = gui_concentrate_handler
        self.page_containers_grid_layout: QGridLayout = page_containers_grid_layout

    def setup_ui(self, navigation_item_vlayout: QVBoxLayout,
                 containers: QFrame, page_containers: QFrame):

        self.containers_menu_li = QVBoxLayout(navigation_item_vlayout)
        self.containers_menu_li.setContentsMargins(0, 0, 0, 0)
        self.containers_menu_li.setSpacing(23)
        self.containers_menu_li.setObjectName("containers_menu_li")

        # set li_setting
        li_setting = QLabel(navigation_item_vlayout)
        li_setting.setAccessibleName(MenuContainersStyles.lis_style[0])
        li_setting.setStyleSheet(MenuContainersStyles.lis_style[1])
        li_setting.setCursor(QCursor(Qt.PointingHandCursor))
        li_setting.setPixmap(
            QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH +
                    "/main_window/setting_logo.svg"))
        li_setting.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                | Qt.AlignVCenter)
        UtilsClick.clickable(li_setting).connect(
            partial(self.li_clicked, "setting"))
        self.containers_menu_li.addWidget(li_setting)

        # set li_menu
        li_menu = QLabel(navigation_item_vlayout)
        li_menu.setCursor(QCursor(Qt.PointingHandCursor))
        li_menu.setAccessibleName(MenuContainersStyles.lis_style[0])
        li_menu.setStyleSheet(MenuContainersStyles.lis_style[1])
        li_menu.setPixmap(
            QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH +
                    "/main_window/menu_logo.svg"))
        li_menu.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                             | Qt.AlignVCenter)
        UtilsClick.clickable(li_menu).connect(partial(self.li_clicked, "menu"))
        self.containers_menu_li.addWidget(li_menu)

        # set li_report
        li_report = QLabel(navigation_item_vlayout)
        li_report.setCursor(QCursor(Qt.PointingHandCursor))
        li_report.setPixmap(
            QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH +
                    "/main_window/chart_logo.svg"))
        li_report.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                               | Qt.AlignVCenter)
        li_report.setAccessibleName(MenuContainersStyles.lis_style[0])
        li_report.setStyleSheet(MenuContainersStyles.lis_style[1])
        self.containers_menu_li.addWidget(li_report)

        # set li_store
        li_store = QLabel(navigation_item_vlayout)
        li_store.setAccessibleName(MenuContainersStyles.lis_style[0])
        li_store.setStyleSheet(MenuContainersStyles.lis_style[1])
        li_store.setCursor(QCursor(Qt.PointingHandCursor))
        li_store.setPixmap(
            QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH +
                    "/main_window/box_logo.svg"))
        li_store.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                              | Qt.AlignVCenter)
        self.containers_menu_li.addWidget(li_store)

        # set li_brain
        li_brain = QLabel(navigation_item_vlayout)
        li_brain.setAccessibleName(MenuContainersStyles.lis_style[0])
        li_brain.setStyleSheet(MenuContainersStyles.lis_style[1])
        li_brain.setCursor(QCursor(Qt.PointingHandCursor))
        li_brain.setPixmap(
            QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH +
                    "/main_window/brain_logo.svg"))
        li_brain.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                              | Qt.AlignVCenter)
        self.containers_menu_li.addWidget(li_brain)

        from .settings_dialog_frame.setting_dialog_frame import SettingDialogFrame
        self.setting_Dialog = SettingDialogFrame(containers)
        self.setting_Dialog.setup_ui()
        self.setting_Dialog.set_visibility_effect(False, False)

        from .tools_dialog_frame.tool_dialog_frame import ToolDialogFrame
        self.tools_dialog = ToolDialogFrame(containers,
                                            self.page_containers_grid_layout,
                                            self.gui_concentrate_handler)
        self.tools_dialog.setup_ui(page_containers=page_containers)
        self.tools_dialog.set_visibility_effect(False, False)

    def li_clicked(self, li_name: str):
        """ this method for event clicked  list item navigation menu
            Arguments:
                li_name {str} -- [list item name]
        """
        if li_name == "setting":
            self.hide_all_frame()
            self.setting_Dialog.set_visibility_effect(True, True)

        elif li_name == "menu":
            self.hide_all_frame()
            self.tools_dialog.set_visibility_effect(True, True)

    def hide_all_frame(self):
        """this method for hide all frames
        """
        self.setting_Dialog.set_visibility_effect(False, False)
        self.tools_dialog.set_visibility_effect(False, False)
예제 #29
0
class UploadWindowUI(object):

    title = "DERIVA File Uploader"

    def __init__(self, MainWin):

        # Main Window
        MainWin.setObjectName("UploadWindow")
        MainWin.setWindowTitle(MainWin.tr(self.title))
        MainWin.resize(1024, 768)
        self.centralWidget = QWidget(MainWin)
        self.centralWidget.setObjectName("centralWidget")
        MainWin.setCentralWidget(self.centralWidget)
        self.verticalLayout = QVBoxLayout(self.centralWidget)
        self.verticalLayout.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")

        self.horizontalLayout = QHBoxLayout()
        self.pathLabel = QLabel("Directory:")
        self.horizontalLayout.addWidget(self.pathLabel)
        self.pathTextBox = QLineEdit()
        self.pathTextBox.setReadOnly(True)
        self.horizontalLayout.addWidget(self.pathTextBox)
        self.browseButton = QPushButton("Browse", self.centralWidget)
        self.browseButton.clicked.connect(MainWin.on_actionBrowse_triggered)
        self.horizontalLayout.addWidget(self.browseButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

        # Splitter for Upload list/Log
        self.splitter = QSplitter(Qt.Vertical)

        # Table View (Upload list)
        self.uploadList = TableWidget(self.centralWidget)
        self.uploadList.setObjectName("uploadList")
        self.uploadList.setStyleSheet(
            """
            QTableWidget {
                    border: 2px solid grey;
                    border-radius: 5px;
            }
            """)
        self.uploadList.setEditTriggers(QAbstractItemView.NoEditTriggers)  # use NoEditTriggers to disable editing
        self.uploadList.setAlternatingRowColors(True)
        self.uploadList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.uploadList.setSelectionMode(QAbstractItemView.NoSelection)
        self.uploadList.verticalHeader().setDefaultSectionSize(18)  # tighten up the row size
        self.uploadList.horizontalHeader().setStretchLastSection(True)
        self.uploadList.setSortingEnabled(True)  # allow sorting
        self.splitter.addWidget(self.uploadList)

        # Log Widget
        self.logTextBrowser = QPlainTextEditLogger(self.centralWidget)
        self.logTextBrowser.widget.setObjectName("logTextBrowser")
        self.logTextBrowser.widget.setStyleSheet(
            """
            QPlainTextEdit {
                    border: 2px solid grey;
                    border-radius: 5px;
                    background-color: lightgray;
            }
            """)
        self.splitter.addWidget(self.logTextBrowser.widget)

        # add splitter
        self.splitter.setSizes([400, 200])
        self.verticalLayout.addWidget(self.splitter)

    # Actions

        # Browse
        self.actionBrowse = QAction(MainWin)
        self.actionBrowse.setObjectName("actionBrowse")
        self.actionBrowse.setText(MainWin.tr("Browse"))
        self.actionBrowse.setToolTip(MainWin.tr("Set the upload directory"))
        self.actionBrowse.setShortcut(MainWin.tr("Ctrl+B"))

        # Upload
        self.actionUpload = QAction(MainWin)
        self.actionUpload.setObjectName("actionUpload")
        self.actionUpload.setText(MainWin.tr("Upload"))
        self.actionUpload.setToolTip(MainWin.tr("Upload files"))
        self.actionUpload.setShortcut(MainWin.tr("Ctrl+L"))
        self.actionUpload.setEnabled(False)

        # Rescan
        self.actionRescan = QAction(MainWin)
        self.actionRescan.setObjectName("actionRescan")
        self.actionRescan.setText(MainWin.tr("Rescan"))
        self.actionRescan.setToolTip(MainWin.tr("Rescan the upload directory"))
        self.actionRescan.setShortcut(MainWin.tr("Ctrl+R"))
        self.actionRescan.setEnabled(False)

        # Cancel
        self.actionCancel = QAction(MainWin)
        self.actionCancel.setObjectName("actionCancel")
        self.actionCancel.setText(MainWin.tr("Cancel"))
        self.actionCancel.setToolTip(MainWin.tr("Cancel any upload(s) in-progress"))
        self.actionCancel.setShortcut(MainWin.tr("Ctrl+C"))

        # Options
        self.actionOptions = QAction(MainWin)
        self.actionOptions.setObjectName("actionOptions")
        self.actionOptions.setText(MainWin.tr("Options"))
        self.actionOptions.setToolTip(MainWin.tr("Configuration Options"))
        self.actionOptions.setShortcut(MainWin.tr("Ctrl+P"))

        # Login
        self.actionLogin = QAction(MainWin)
        self.actionLogin.setObjectName("actionLogin")
        self.actionLogin.setText(MainWin.tr("Login"))
        self.actionLogin.setToolTip(MainWin.tr("Login to the server"))
        self.actionLogin.setShortcut(MainWin.tr("Ctrl+G"))
        self.actionLogin.setEnabled(False)

        # Logout
        self.actionLogout = QAction(MainWin)
        self.actionLogout.setObjectName("actionLogout")
        self.actionLogout.setText(MainWin.tr("Logout"))
        self.actionLogout.setToolTip(MainWin.tr("Logout of the server"))
        self.actionLogout.setShortcut(MainWin.tr("Ctrl+O"))
        self.actionLogout.setEnabled(False)

        # Exit
        self.actionExit = QAction(MainWin)
        self.actionExit.setObjectName("actionExit")
        self.actionExit.setText(MainWin.tr("Exit"))
        self.actionExit.setToolTip(MainWin.tr("Exit the application"))
        self.actionExit.setShortcut(MainWin.tr("Ctrl+Z"))

        # Help
        self.actionHelp = QAction(MainWin)
        self.actionHelp.setObjectName("actionHelp")
        self.actionHelp.setText(MainWin.tr("Help"))
        self.actionHelp.setToolTip(MainWin.tr("Help"))
        self.actionHelp.setShortcut(MainWin.tr("Ctrl+H"))

    # Menu Bar

        """
        self.menuBar = QMenuBar(MainWin)
        self.menuBar.setObjectName("menuBar")
        MainWin.setMenuBar(self.menuBar)
        self.menuBar.setStyleSheet(
            "QMenuBar{font-family: Arial;font-style: normal;font-size: 10pt;font-weight: bold;};")
        """

    # Tool Bar

        self.mainToolBar = QToolBar(MainWin)
        self.mainToolBar.setObjectName("mainToolBar")
        self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.mainToolBar.setContextMenuPolicy(Qt.PreventContextMenu)
        MainWin.addToolBar(Qt.TopToolBarArea, self.mainToolBar)

        # Upload
        self.mainToolBar.addAction(self.actionUpload)
        self.actionUpload.setIcon(qApp.style().standardIcon(QStyle.SP_FileDialogToParent))

        # Rescan
        self.mainToolBar.addAction(self.actionRescan)
        self.actionRescan.setIcon(qApp.style().standardIcon(QStyle.SP_BrowserReload))

        # Cancel
        self.mainToolBar.addAction(self.actionCancel)
        self.actionCancel.setIcon(qApp.style().standardIcon(QStyle.SP_BrowserStop))
        self.actionCancel.setEnabled(False)

        # Options
        self.mainToolBar.addAction(self.actionOptions)
        self.actionOptions.setIcon(qApp.style().standardIcon(QStyle.SP_FileDialogDetailedView))

        # this spacer right justifies everything that comes after it
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.mainToolBar.addWidget(spacer)

        # Login
        self.mainToolBar.addAction(self.actionLogin)
        self.actionLogin.setIcon(qApp.style().standardIcon(QStyle.SP_DialogApplyButton))

        # Logout
        self.mainToolBar.addAction(self.actionLogout)
        self.actionLogout.setIcon(qApp.style().standardIcon(QStyle.SP_DialogOkButton))

        # Help
        #self.mainToolBar.addAction(self.actionHelp)
        self.actionHelp.setIcon(qApp.style().standardIcon(QStyle.SP_MessageBoxQuestion))

        # Exit
        self.mainToolBar.addAction(self.actionExit)
        self.actionExit.setIcon(qApp.style().standardIcon(QStyle.SP_DialogCancelButton))

    # Status Bar

        self.statusBar = QStatusBar(MainWin)
        self.statusBar.setToolTip("")
        self.statusBar.setStatusTip("")
        self.statusBar.setObjectName("statusBar")
        MainWin.setStatusBar(self.statusBar)

    # configure logging
        self.logTextBrowser.widget.log_update_signal.connect(MainWin.updateLog)
        self.logTextBrowser.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
        logging.getLogger().addHandler(self.logTextBrowser)

    # finalize UI setup
        QMetaObject.connectSlotsByName(MainWin)
예제 #30
0
class Ui_SubWindow(QMainWindow):
    def __init__(self, source_filename, confirm_path_signal):
        super().__init__()
        self.setupUi()
        self.btn_dict = {}  #以按钮为键,以(文件名字,进度条)为值的字典
        self.create_unit(source_filename, confirm_path_signal)

    def setupUi(self):
        self.resize(400, 400)
        self.cen_wid = QWidget()
        self.setCentralWidget(self.cen_wid)
        self.verticalLayout_2 = QVBoxLayout(self.cen_wid)
        self.cen_wid.setLayout(self.verticalLayout_2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        # self.statusbar = QStatusBar(self)
        # self.statusbar.setObjectName("statusbar")
        # self.setStatusBar(self.statusbar)
        self.setWindowTitle("SubWindow")

    def create_unit(self, source_filename, confirm_path_signal):

        for source, filename in source_filename:
            self.horizontalLayout = QHBoxLayout()
            self.groupbox = QGroupBox()
            self.label = QLabel(
                self.cen_wid)  # os.path.dirname(os.path.abspath(sys.argv[0]))
            self.label.setPixmap(
                QPixmap(
                    os.path.dirname(os.path.abspath(sys.argv[0])) + "\\" +
                    "file.jpg"))
            self.horizontalLayout.addWidget(self.label)
            self.verticalLayout = QVBoxLayout()

            self.label_2 = QLabel(self)
            self.label_2.setText("from " + source + ":" + filename)
            self.verticalLayout.addWidget(self.label_2)
            self.progressBar = QProgressBar(self)
            self.progressBar.setProperty("value", 0)
            self.progressBar.setObjectName("progressBar")
            self.verticalLayout.addWidget(self.progressBar)
            self.pushButton = QPushButton(self)
            self.pushButton.setFocusPolicy(QtCore.Qt.NoFocus)
            self.pushButton.setFlat(True)
            self.pushButton.setText("另存为")
            self.pushButton.clicked.connect(
                lambda: self.saveas(self.pushButton, confirm_path_signal
                                    ))  # 这里或许会出bug,是否能如我所愿,传递时,将所按的按钮传递到参数去
            self.verticalLayout.addWidget(self.pushButton)
            self.groupbox.setLayout(self.verticalLayout)
            self.horizontalLayout.addWidget(self.groupbox)
            self.btn_dict[self.pushButton] = (filename, self.progressBar)
            self.verticalLayout_2.addLayout(self.horizontalLayout)

    def saveas(self, pushbtn, confirm_path_signal):  #另存为
        if "available" in dir(self):
            pass
        else:
            self.available = {}
            for btn in self.btn_dict.keys():
                self.available[btn] = [
                    "0", False, False
                ]  # tuple中第一个元素是confirm(该按钮对应的文件是否已经确认保存路径)
                # 第二个元素是recv_or_not(该按钮对应的文件是否已经被接收)
        # 还要生成文件保存对话框
        abspath = QFileDialog.getSaveFileName(self, 'save as...')[0]
        if pushbtn not in self.available.keys():
            self.available[pushbtn] = ["0", False, False]
        #print("file is:",self.btn_dict[pushbtn][0])
        self.available[pushbtn][0] = abspath
        self.available[pushbtn][1] = True
        confirm_path_signal.emit()

    def addfile(self, source_filename, confirm_path_signal):
        self.create_unit(source_filename, confirm_path_signal)
예제 #31
0
class WVentOut(QGroupBox):
    """Setup of QGroupBox for output for Ventilation
    """
    def __init__(self, parent=None):
        """Initialize the widget
        """

        QWidget.__init__(self, parent)
        # Init the main widget
        self.u = gui_option.unit
        self.setTitle(self.tr("Output"))
        self.setMinimumSize(QSize(300, 0))
        self.setObjectName("g_output")
        self.layout = QVBoxLayout(self)
        self.layout.setObjectName("layout")

        # The widget is composed of several QLabel in a vertical layout
        self.out_Rint = QLabel(self)
        self.out_Rint.setObjectName("out_Rint")
        self.layout.addWidget(self.out_Rint)

        self.out_Rext = QLabel(self)
        self.out_Rext.setObjectName("out_Rext")
        self.layout.addWidget(self.out_Rext)

        self.out_lam_surface = QLabel(self)
        self.out_lam_surface.setObjectName("out_lam_surface")
        self.layout.addWidget(self.out_lam_surface)

        self.out_lam_vent_surface = QLabel(self)
        self.out_lam_vent_surface.setObjectName("out_lam_vent_surface")
        self.layout.addWidget(self.out_lam_vent_surface)

        self.out_vent_surf = QLabel(self)
        self.out_vent_surf.setObjectName("out_vent_surf")
        self.layout.addWidget(self.out_vent_surf)

        # self.layout.addWidget(self)

    def comp_output(self):
        """Update the Output group according to the current value

        Parameters
        ----------
        self : WVentOut
            A WVentOut object
        """

        lam = self.parent().lam

        # Lamination output
        Rint = format(self.u.get_m(lam.Rint), ".4g")
        self.out_Rint.setText(
            self.tr("Lam. internal radius: ") + Rint + " " +
            self.u.get_m_name())

        Rext = format(self.u.get_m(lam.Rext), ".4g")
        self.out_Rext.setText(
            self.tr("Lam. external radius: ") + Rext + " " +
            self.u.get_m_name())
        Slam = format(self.u.get_m2(pi * (lam.Rext**2 - lam.Rint**2)), ".4g")
        self.out_lam_surface.setText(
            self.tr("Lam. surface (no slot, no vent): ") + Slam + " " +
            self.u.get_m2_name())
        # Ventilation output
        try:
            lam = Lamination(Rext=lam.Rext, Rint=lam.Rint)

            lam.axial_vent = self.parent().lam.axial_vent
            Svent = format(self.u.get_m2(lam.comp_surface_axial_vent()), ".4g")
        except Exception:
            Svent = 0
            self.out_lam_vent_surface.setText(
                self.tr("Lam. surface (no slot, with vent): ?"))
            self.out_vent_surf.setText(self.tr("Vent surface: ?"))
        if Svent != 0:
            Slv = format(float(Slam) - float(Svent), ".4g")
            self.out_lam_vent_surface.setText(
                self.tr("Lam. surface (no slot, with vent): ") + Slv + " " +
                self.u.get_m2_name())
            self.out_vent_surf.setText(
                self.tr("Vent surface: ") + Svent + " " + self.u.get_m2_name())
예제 #32
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1400, 900)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.centralwidget.resize(1400, 900)
        ''' Structure of this GUI
        centralWidget (1400 x 900)
            verticalLayout
                horizontalLayoutTop
                    webcam_box1 (700 x 500)
                    webcam_box2 (700 x 500)
                horizontalLayoutBottom
                    controlBox  (300 x 300)
                    timer_LCD   (200 x 100) (could be (200 x 300)
                    pulseOxBox  (450 x 300)

        '''
        BigFont = QFont("Helvetica [Cronyx]", 12, QFont.Bold)
        # vertical layout allows to add widget vertically
        self.verticalLayout = QVBoxLayout()

        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))

        self.horizontalLayoutTop = QHBoxLayout()
        self.horizontalLayoutTop.setObjectName(
            _fromUtf8("horizontalLayoutTop"))

        self.webcam_box1 = QGroupBox(self.centralwidget)
        self.webcam_box1.setTitle(_fromUtf8("Camera Feed 1"))
        self.webcam_box1.setObjectName(_fromUtf8("webcam_box_1"))
        #self.webcam_box1.setGeometry(QtCore.QRect(0, 0, 700, 500))

        #self.webcam_box2.setGeometry(QtCore.QRect(700, 0, 700, 500))

        self.webcam1 = QLabel(self.webcam_box1)
        self.webcam1.setGeometry(QtCore.QRect(30, 30, 641,
                                              481))  # Default image size
        self.webcam1.setText(_fromUtf8("Camera Feed 1"))
        self.webcam1.setObjectName(_fromUtf8("webcam_1"))

        self.webcam1_hBox = QHBoxLayout()

        # Camera Control
        #self.cameraControlWidget = QWidget(self.centralwidget)
        self.cameraControlWidget = []
        self.cameraControlWidget.append(PtGreyCameraControl(0))
        self.cameraControlWidget.append(PtGreyCameraControl(1))

        #self.CameraControlGrid = QGridLayout()
        # self.CameraControlForm =QFormLayout()

        # self.FPS_value.setFixedWidth(5)

        # self.CameraControlForm.addRow(self.exposure_title, self.exposure_value)
        # self.CameraControlForm.addRow(self.gain_title,self.gain_value)
        # self.CameraControlForm.addRow(self.FPS_title,self.FPS_value)

        #self.cameraControlWidget.setLayout(self.CameraControlGrid)
        self.webcam1_hBox.addWidget(self.webcam1, 3)
        self.webcam1_hBox.addWidget(self.cameraControlWidget[0], 1)

        self.webcam_box1.setLayout(self.webcam1_hBox)

        # Webcam -2 // May be webcam or the second point grey

        self.webcam_box2 = QGroupBox(self.centralwidget)
        self.webcam_box2.setTitle(_fromUtf8("Camera Feed 2"))
        self.webcam_box2.setObjectName(_fromUtf8("webcam_box_2"))

        self.webcam2 = QLabel(self.webcam_box2)
        self.webcam2.setGeometry(QtCore.QRect(30, 30, 641,
                                              481))  # Default image size
        self.webcam2.setText(_fromUtf8("Camera Feed 2"))
        self.webcam2.setObjectName(_fromUtf8("webcam_2"))

        self.webcam2_vBox = QHBoxLayout()
        self.webcamControlWidget = QWidget(self.centralwidget)

        self.webcam2_hBoxBottom = QVBoxLayout()

        self.push_inc_webcam_gain = QPushButton()
        self.push_inc_webcam_gain.setObjectName(
            _fromUtf8("increase_webcam_gain"))
        self.push_inc_webcam_gain.setFont(BigFont)

        self.push_dec_webcam_gain = QPushButton()
        self.push_dec_webcam_gain.setObjectName(
            _fromUtf8("decrease_webcam_gain"))
        self.push_dec_webcam_gain.setFont(BigFont)

        self.push_inc_webcam_exp = QPushButton()
        self.push_inc_webcam_exp.setObjectName(
            _fromUtf8("increase_webcam_exposure"))
        self.push_inc_webcam_exp.setFont(BigFont)

        self.push_dec_webcam_exp = QPushButton()
        self.push_dec_webcam_exp.setObjectName(
            _fromUtf8("decrease_webcam_exposure"))
        self.push_dec_webcam_exp.setFont(BigFont)

        self.webcam2_hBoxBottom.addWidget(self.push_inc_webcam_exp)
        self.webcam2_hBoxBottom.addWidget(self.push_dec_webcam_exp)
        self.webcam2_hBoxBottom.addWidget(self.push_inc_webcam_gain)
        self.webcam2_hBoxBottom.addWidget(self.push_dec_webcam_gain)

        self.webcamControlWidget.setLayout(self.webcam2_hBoxBottom)

        self.webcam2_vBox.addWidget(self.webcam2, 3)
        #FIXME: Need to implement both webcam and point grey here
        self.webcam2_vBox.addWidget(self.cameraControlWidget[1], 1)

        self.webcam_box2.setLayout(self.webcam2_vBox)
        self.OTEventBlock = OTEventBlock()

        if CONFIG.PROFILE == 0:  #Operating room profile

            self.horizontalLayoutTop.addWidget(self.webcam_box1, 2)
            self.cameraControlWidget[0].Binning_value.setEnabled(False)
            self.cameraControlWidget[0].offsetX_value.setEnabled(False)
            self.cameraControlWidget[0].offsetY_value.setEnabled(False)
            self.cameraControlWidget[0].width_value.setEnabled(False)
            self.cameraControlWidget[0].height_value.setEnabled(False)

            self.horizontalLayoutTop.addWidget(self.OTEventBlock, 1)
        else:
            self.horizontalLayoutTop.addWidget(self.webcam_box1, 1)
            self.horizontalLayoutTop.addWidget(self.webcam_box2, 1)

        #self.horizontalLayoutTop.addWidget(self.perfusion_box)

        self.horizontalLayoutBottom = QHBoxLayout()
        self.horizontalLayoutBottom.setObjectName(
            _fromUtf8("horizontalLayoutBottom"))

        # Application controls

        self.control_box = QGroupBox(self.centralwidget)
        self.control_box.setTitle(_fromUtf8("Controls"))
        self.control_box.setObjectName(_fromUtf8("control_box"))
        self.control_box.setGeometry(QtCore.QRect(0, 0, 300, 300))

        self.control_vBox = QVBoxLayout()
        self.control_hBoxTop = QHBoxLayout()

        self.push_setup = QPushButton()
        # self.push_setup.setGeometry(QtCore.QRect(80, 20, 81, 23))
        self.push_setup.setObjectName(_fromUtf8("push_setup"))
        self.push_setup.setFont(BigFont)

        self.push_start = QPushButton()
        # self.push_start.setGeometry(QtCore.QRect(190, 20, 81, 23))
        self.push_start.setObjectName(_fromUtf8("push_start"))
        self.push_start.setFont(BigFont)

        self.push_stop = QPushButton()
        # self.push_stop.setGeometry(QtCore.QRect(300, 20, 81, 23))
        self.push_stop.setObjectName(_fromUtf8("push_stop"))
        self.push_stop.setFont(BigFont)

        self.push_process = QPushButton()
        # self.push_process.setGeometry(QtCore.QRect(80, 50, 81, 23))
        self.push_process.setObjectName(_fromUtf8("push_process"))
        self.push_process.setFont(BigFont)

        self.control_hBoxTop.addWidget(self.push_start)
        self.control_hBoxTop.addWidget(self.push_stop)
        self.control_hBoxTop.addWidget(self.push_setup)

        self.plain_instruction = QPlainTextEdit(self.control_box)
        self.plain_instruction.setGeometry(QtCore.QRect(0, 100, 400, 300))
        self.plain_instruction.setObjectName(_fromUtf8("plain_instruction"))
        self.plain_instruction.setCenterOnScroll(True)
        self.plain_instruction.setReadOnly(True)

        self.control_vBox.addLayout(self.control_hBoxTop)
        self.control_vBox.addWidget(self.plain_instruction)

        self.control_box.setLayout(self.control_vBox)
        '''

        self.push_setup = QPushButton(self.control_box)
        self.push_setup.setGeometry(QtCore.QRect(80, 20, 81, 23))
        self.push_setup.setObjectName(_fromUtf8("push_setup"))
        
        self.push_start = QPushButton(self.control_box)
        self.push_start.setGeometry(QtCore.QRect(190, 20, 81, 23))
        self.push_start.setObjectName(_fromUtf8("push_start"))

        self.push_stop = QPushButton(self.control_box)
        self.push_stop.setGeometry(QtCore.QRect(300, 20, 81, 23))
        self.push_stop.setObjectName(_fromUtf8("push_stop"))

        self.push_process = QPushButton(self.control_box)
        self.push_process.setGeometry(QtCore.QRect(80, 50, 81, 23))
        self.push_process.setObjectName(_fromUtf8("push_process"))

        self.plain_instruction = QPlainTextEdit(self.control_box)
        self.plain_instruction.setGeometry(QtCore.QRect(0, 100, 400, 300))
        self.plain_instruction.setObjectName(_fromUtf8("plain_instruction"))
        self.plain_instruction.setCenterOnScroll(True)
        self.plain_instruction.setReadOnly(True)
        '''

        # Pulse Oximeter output
        self.pulseOx_box = QGroupBox(self.centralwidget)
        self.pulseOx_box.setTitle(_fromUtf8("Pulse oximeter recordings"))
        self.pulseOx_box.setObjectName(_fromUtf8("pulseox_Output"))
        #self.pulseOx_box.setGeometry(0, 0, 450, 300)

        self.pulseOxLayout = QVBoxLayout()

        # PULSE oximeter
        self.pulseOx = DisplayForm()
        self.pulseOx2 = DisplayForm()
        #self.pulseOx.setGeometry(8,8,450,150)
        #self.pulseOx1.setGeometry(8,8,450,150)

        self.pulseOxLayout.addWidget(self.pulseOx)
        if CONFIG.PROFILE:
            self.pulseOxLayout.addWidget(self.pulseOx2)

        self.pulseOx_box.setLayout(self.pulseOxLayout)

        # Timer
        self.timer_lcd = QLCDNumber(self.centralwidget)
        self.timer_lcd.setObjectName(_fromUtf8("pulseox_Output"))
        self.timer_lcd.setGeometry(10, 10, 200, 100)

        self.horizontalLayoutBottom.addWidget(self.control_box, 2)
        self.horizontalLayoutBottom.addWidget(self.timer_lcd, 1)
        self.horizontalLayoutBottom.addWidget(self.pulseOx_box, 2)

        self.verticalLayout.addLayout(self.horizontalLayoutTop, 3)
        self.verticalLayout.addLayout(self.horizontalLayoutBottom, 2)

        self.centralwidget.setLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        #self.config_form = ConfigForm()
        #self.toolbar = Toolbar()

        # Group controls
        '''
        self.label_2 = QLabel(self.control_box)
        self.label_2.setGeometry(QtCore.QRect(30, 20, 71, 16))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.push_check = QPushButton(self.control_box)
        self.push_check.setGeometry(QtCore.QRect(80, 40, 81, 23))
        self.push_check.setObjectName(_fromUtf8("push_check"))
        self.push_close = QPushButton(self.control_box)
        self.push_close.setGeometry(QtCore.QRect(190, 40, 81, 23))
        self.push_close.setObjectName(_fromUtf8("push_close"))
        
        self.push_browse = QPushButton(self.control_box)
        self.push_browse.setGeometry(QtCore.QRect(80, 120,81,23))
        self.push_browse.setObjectName(_fromUtf8('push_browse'))
        self.label = QLabel(self.control_box)
        self.label.setGeometry(QtCore.QRect(30, 150, 91, 16))
        self.label.setObjectName(_fromUtf8("label"))
        self.plain_instruction = QPlainTextEdit(self.control_box)
        self.plain_instruction.setGeometry(QtCore.QRect(30, 180, 300, 300))
        self.plain_instruction.setObjectName(_fromUtf8("plain_instruction"))
        self.plain_instruction.setCenterOnScroll(True)
        self.plain_instruction.setReadOnly(True)
        #self.plain_instruction.setMaximumBlockCount(20)
        # Group_Frame
        
        
        self.horizontalLayoutBottom = QHBoxLayout()
        self.horizontalLayoutBottom.setObjectName(_fromUtf8("horizontalLayoutBottom"))
        
        # Group_Output 
        self.Group_Output = QGroupBox(self.centralwidget)
        self.Group_Output.setTitle(_fromUtf8("distancePPG Output"))
        self.Group_Output.setObjectName(_fromUtf8("Group_Output"))
        self.label_3 = QLabel(self.Group_Output)
        self.label_3.setGeometry(QtCore.QRect(20, 20, 130, 15))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.line_HR = QLCDNumber(self.Group_Output)
        self.line_HR.setGeometry(QtCore.QRect(20, 40, 100, 100))
        self.line_HR.setObjectName(_fromUtf8("line_HR"))
        self.label_4 = QLabel(self.Group_Output)
        self.label_4.setGeometry(QtCore.QRect(20, 140, 130, 15))
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.SQDisplay = QLCDNumber(self.Group_Output)
        self.SQDisplay.setGeometry(QtCore.QRect(20, 160, 100, 100))
        self.SQDisplay.setObjectName(_fromUtf8("SQDisplay"))
        self.label_6= QLabel(self.Group_Output)
        self.label_6.setGeometry(QtCore.QRect(20, 260, 130, 15))
        self.label_6.setObjectName(_fromUtf8("label_6"))
        self.motion = QLCDNumber(self.Group_Output)
        self.motion.setGeometry(QtCore.QRect(20, 280, 100, 100))
        self.motion.setObjectName(_fromUtf8("motion"))
        #self.frame_HRV = matplotlibWidget(self.Group_Output)
        #self.frame_HRV.setGeometry(QtCore.QRect(20, 90, 191, 141))
        #self.frame_HRV.setObjectName(_fromUtf8("frame_HRV"))
        #self.label_4 = QLabel(self.Group_Output)
        #self.label_4.setGeometry(QtCore.QRect(20, 70, 54, 12))
        #self.label_4.setObjectName(_fromUtf8("label_4"))
        self.label_5 = QLabel(self.Group_Output)
        self.label_5.setGeometry(QtCore.QRect(230, 10, 200, 12))
        self.label_5.setObjectName(_fromUtf8("label_5"))
        
        self.cameraPPG = CameraForm(self.Group_Output)
        self.cameraPPG.setGeometry(QtCore.QRect(230, 22, 500, 400))
        self.cameraPPG.setObjectName(_fromUtf8("camera_PPG"))
        #self.verticalLayout_2.addWidget(self.Group_Output)
        #self.verticalLayout_4.addLayout(self.verticalLayout_2)
        self.verticalLayout.addLayout(self.horizontalLayoutTop)
        self.verticalLayout.addLayout(self.horizontalLayoutBottom)
        self.centralwidget.setLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        
        #menubar 
        
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 696, 18))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuSave = QtGui.QMenu(self.menubar)
        self.menuSave.setObjectName(_fromUtf8("menuSave"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.actionCurrent_Dir = QtGui.QAction(MainWindow)
        self.actionCurrent_Dir.setObjectName(_fromUtf8("actionCurrent_Dir"))
        self.actionChange_Dir = QtGui.QAction(MainWindow)
        self.actionChange_Dir.setObjectName(_fromUtf8("actionChange_Dir"))
        self.menubar.addAction(self.menuSave.menuAction())
        
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        '''

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            _translate("MainWindow", "PerfusionCam Demo", None))
        self.push_start.setText(_translate("MainWindow", "Start", None))
        self.push_stop.setText(_translate("MainWindow", "Stop", None))
        self.push_setup.setText(_translate("MainWindow", "Setup", None))
        self.push_process.setText(_translate("MainWindow", "Process", None))
        self.push_inc_webcam_gain.setText(
            _translate("MainWindow", "Inc. Gain", None))
        self.push_dec_webcam_gain.setText(
            _translate("MainWindow", "Dec. Gain", None))
        self.push_inc_webcam_exp.setText(
            _translate("MainWindow", "Inc. Exposure", None))
        self.push_dec_webcam_exp.setText(
            _translate("MainWindow", "Dec. Exposure", None))
        self.cameraControlWidget[0].push_cameraSetup.setText(
            _translate("MainWindow", "Update Settings", None))
        self.cameraControlWidget[1].push_cameraSetup.setText(
            _translate("MainWindow", "Update Settings", None))

        #self.label.setText(_translate("MainWindow", "Status:", None))
        #self.label_2.setText(_translate("MainWindow", "Controls:", None))
        #self.push_check.setText(_translate("MainWindow", "Check ", None))
        #self.push_close.setText(_translate("MainWindow", "Close", None))
        #self.push_browse.setText(_translate("MainWindow", "Select Folder", None))
        #self.label_3.setText(_translate("MainWindow", "BR (Br PM)", None))
        #self.label_4.setText(_translate("MainWindow", "Signal Quality:", None))
        #self.label_5.setText(_translate("MainWindow", "Camera PPG Waveform:", None))
        #self.label_6.setText(_translate("MainWindow", "LF/HF (using PRV):", None))

        #self.menuSave.setTitle(_translate("MainWindow", "File", None))


#self.actionCurrent_Dir.setText(_translate("MainWindow", "Current Dir", None))
#self.actionChange_Dir.setText(_translate("MainWindow", "Change Dir", None))
예제 #33
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.lastyear = int(time.strftime('%Y', time.localtime(time.time()))) - 1
        self.in_parameters = {u'datetime': str(self.lastyear) + u'年',
                              u'target_area': u'绍兴市',
                              u'density_cell': u'10',
                              u'density_class': 10,
                              u'day_cell': u'15',
                              u'day_class': 10,
                              u'out_type': u'tiff'}
        self.setupUi()

    def setupUi(self):
        self.setObjectName("MainWindow")
        self.setFixedSize(1040, 915)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        icon = QIcon()
        icon.addPixmap(QPixmap('./resource/weather-thunder.png'),QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.centralwidget = QWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setObjectName("centralwidget")
        self.layoutWidget = QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QRect(32, 10, 979, 851))
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout_5 =QVBoxLayout(self.layoutWidget)
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.datetime_label = QLabel(self.layoutWidget)
        self.datetime_label.setObjectName("datetime_label")
        self.horizontalLayout.addWidget(self.datetime_label)
        self.datetime = QDateEdit(self.layoutWidget)
        self.datetime.setDateTime(QDateTime(QDate(self.lastyear, 1, 1), QTime(0, 0, 0)))
        self.datetime.setObjectName("datetime")
        self.horizontalLayout.addWidget(self.datetime)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.target_area_label = QLabel(self.layoutWidget)
        self.target_area_label.setObjectName("target_area_label")
        self.horizontalLayout.addWidget(self.target_area_label)
        self.target_area = QComboBox(self.layoutWidget)
        self.target_area.setObjectName("target_area")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.horizontalLayout.addWidget(self.target_area)
        spacerItem2 = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.verticalLayout_5.addLayout(self.horizontalLayout)
        self.tabWidget = QTabWidget(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
        self.tabWidget.setSizePolicy(sizePolicy)
        self.tabWidget.setObjectName("tabWidget")
        self.density_tab = QWidget()
        self.density_tab.setObjectName("density_tab")
        self.verticalLayout_3 =QVBoxLayout(self.density_tab)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.verticalLayout_2 =QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.density_cell_label = QLabel(self.density_tab)
        self.density_cell_label.setObjectName("density_cell_label")
        self.horizontalLayout_2.addWidget(self.density_cell_label)
        self.density_cell = QSpinBox(self.density_tab)
        self.density_cell.setProperty("value", 10)
        self.density_cell.setObjectName("density_cell")
        self.horizontalLayout_2.addWidget(self.density_cell)
        spacerItem3 = QSpacerItem(40, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem3)
        self.density_class_label = QLabel(self.density_tab)
        self.density_class_label.setObjectName("density_class_label")
        self.horizontalLayout_2.addWidget(self.density_class_label)
        self.density_class = QSpinBox(self.density_tab)
        self.density_class.setProperty("value", 10)
        self.density_class.setObjectName("density_class")
        self.horizontalLayout_2.addWidget(self.density_class)
        spacerItem4 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem4)
        self.density_mxd = QPushButton(self.density_tab)
        self.density_mxd.setObjectName("density_mxd")
        self.horizontalLayout_2.addWidget(self.density_mxd)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.density_view = QGraphicsView(self.density_tab)
        self.density_view.setObjectName("density_view")
        self.verticalLayout_2.addWidget(self.density_view)
        self.verticalLayout_3.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.density_tab, "")
        self.day_tab = QWidget()
        self.day_tab.setObjectName("day_tab")
        self.verticalLayout_4 =QVBoxLayout(self.day_tab)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.verticalLayout =QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_3 =QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.day_cell_label = QLabel(self.day_tab)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.day_cell_label.sizePolicy().hasHeightForWidth())
        self.day_cell_label.setSizePolicy(sizePolicy)
        self.day_cell_label.setObjectName("day_cell_label")
        self.horizontalLayout_3.addWidget(self.day_cell_label)
        self.day_cell = QSpinBox(self.day_tab)
        self.day_cell.setProperty("value", 15)
        self.day_cell.setObjectName("day_cell")
        self.horizontalLayout_3.addWidget(self.day_cell)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem5)
        self.day_class_label = QLabel(self.day_tab)
        self.day_class_label.setObjectName("day_class_label")
        self.horizontalLayout_3.addWidget(self.day_class_label)
        self.day_class = QSpinBox(self.day_tab)
        self.day_class.setProperty("value", 10)
        self.day_class.setObjectName("day_class")
        self.horizontalLayout_3.addWidget(self.day_class)
        spacerItem6 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem6)
        self.day_mxd = QPushButton(self.day_tab)
        self.day_mxd.setObjectName("day_mxd")
        self.horizontalLayout_3.addWidget(self.day_mxd)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.day_view = QGraphicsView(self.day_tab)
        self.day_view.setObjectName("day_view")
        self.verticalLayout.addWidget(self.day_view)
        self.verticalLayout_4.addLayout(self.verticalLayout)
        self.tabWidget.addTab(self.day_tab, "")
        self.verticalLayout_5.addWidget(self.tabWidget)
        self.horizontalLayout_4 =QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.progressBar = QProgressBar(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth())
        self.progressBar.setSizePolicy(sizePolicy)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout_4.addWidget(self.progressBar)
        self.execute_button = QPushButton(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.execute_button.sizePolicy().hasHeightForWidth())
        self.execute_button.setSizePolicy(sizePolicy)
        self.execute_button.setObjectName("execute_button")
        self.horizontalLayout_4.addWidget(self.execute_button)
        self.verticalLayout_5.addLayout(self.horizontalLayout_4)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 1040, 26))
        self.menubar.setObjectName("menubar")
        self.file_menu = QMenu(self.menubar)
        self.file_menu.setObjectName("file_menu")
        self.help_menu = QMenu(self.menubar)
        self.help_menu.setObjectName("help_menu")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.action_add_data = QAction(self)
        self.action_add_data.setObjectName("action_add_data")
        self.action_help = QAction(self)
        self.action_help.setObjectName("action_help")
        self.action_about = QAction(self)
        self.action_about.setObjectName("action_about")
        self.action_save_pic = QAction(self)
        self.action_save_pic.setObjectName("action_save_pic")
        self.file_menu.addAction(self.action_add_data)
        self.file_menu.addAction(self.action_save_pic)
        self.help_menu.addAction(self.action_help)
        self.help_menu.addAction(self.action_about)
        self.menubar.addAction(self.file_menu.menuAction())
        self.menubar.addAction(self.help_menu.menuAction())

        self.retranslateUi()
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(self)
        self.center()
        self.show()

        self.target_area.activated[str].connect(self.updateTargetArea)
        self.datetime.dateChanged.connect(self.updateDatetime)
        self.density_cell.valueChanged.connect(self.updateDensityCell)
        self.density_class.valueChanged.connect(self.updateDensityClass)
        self.day_cell.valueChanged.connect(self.updateDayCell)
        self.day_class.valueChanged.connect(self.updateDayClass)

        self.action_add_data.triggered.connect(self.addData)
        self.action_save_pic.triggered.connect(self.savePic)
        self.action_about.triggered.connect(self.showAbout)
        self.action_help.triggered.connect(self.showHelp)
        self.execute_button.clicked.connect(self.execute)
        self.density_mxd.clicked.connect(self.openMxdDensity)
        self.day_mxd.clicked.connect(self.openMxdDay)


        self.density_mxd.setDisabled(True)
        self.day_mxd.setDisabled(True)
        self.action_save_pic.setDisabled(True)

    def execute(self):
        dir = u"E:/Documents/工作/雷电公报/闪电定位原始文本数据/" + self.in_parameters[u'datetime']

        if os.path.exists(dir):
            datafiles = os.listdir(dir)
            datafiles = map(lambda x:os.path.join(dir,x),datafiles)
            self.in_parameters[u'origin_data_path'] = datafiles

        if not self.in_parameters.has_key(u'origin_data_path'):
            message = u"请加载%s的数据" % self.in_parameters[u'datetime']
            msgBox = QMessageBox()
            msgBox.setText(message)
            msgBox.setIcon(QMessageBox.Information)
            icon = QIcon()
            icon.addPixmap(QPixmap('./resource/weather-thunder.png'), QIcon.Normal, QIcon.Off)
            msgBox.setWindowIcon(icon)
            msgBox.setWindowTitle(" ")
            msgBox.exec_()
            return

        self.execute_button.setDisabled(True)
        self.execute_button.setText(u'正在制图中……')
        self.progressBar.setMaximum(0)
        self.progressBar.setMinimum(0)

        self.action_add_data.setDisabled(True)
        self.target_area.setDisabled(True)
        self.datetime.setDisabled(True)
        self.density_cell.setDisabled(True)
        self.density_class.setDisabled(True)
        self.day_cell.setDisabled(True)
        self.day_class.setDisabled(True)

        # for outfile in self.in_parameters[u'origin_data_path']:
        #     infile =
        #     try:
        #         with open(infile, 'w+') as in_f:
        #             for line in in_f:
        #                 line = line.replace(u":",":")
        #                 in_f.write(line)
        #     except Exception,inst:
        #         print infile

        self.process_thread = WorkThread()
        self.process_thread.trigger.connect(self.finished)
        self.process_thread.beginRun(self.in_parameters)

    def finished(self):

        #绘制闪电密度图
        ##清除上一次的QGraphicsView对象,防止其记录上一次图片结果,影响显示效果
        self.density_view.setAttribute(Qt.WA_DeleteOnClose)
        self.verticalLayout_2.removeWidget(self.density_view)
        size = self.density_view.size()
        self.density_view.close()

        self.density_view = QGraphicsView(self.density_tab)
        self.density_view.setObjectName("density_view")
        self.density_view.resize(size)
        self.verticalLayout_2.addWidget(self.density_view)

        densityPic = ''.join([cwd,u'/bulletinTemp/',
            self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'闪电密度空间分布.tif'])

        scene = QGraphicsScene()
        pixmap_density = QPixmap(densityPic)
        scene.addPixmap(pixmap_density)
        self.density_view.setScene(scene)
        scale = float(self.density_view.width()) / pixmap_density.width()
        self.density_view.scale(scale, scale)

        #绘制雷暴日图
        self.day_view.setAttribute(Qt.WA_DeleteOnClose)
        self.verticalLayout.removeWidget(self.day_view)
        size = self.day_view.size()
        self.day_view.close()

        self.day_view = QGraphicsView(self.day_tab)
        self.day_view.setObjectName("day_view")
        self.day_view.resize(size)
        self.verticalLayout.addWidget(self.day_view)

        dayPic = ''.join([cwd,u'/bulletinTemp/',
            self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif'])

        pixmap_day = QPixmap(dayPic)
        scene = QGraphicsScene()
        scene.addPixmap(pixmap_day)
        self.day_view.resize(self.density_view.width(),self.density_view.height())
        self.day_view.setScene(scene)
        scale = float(self.day_view.width()) / pixmap_day.width()
        self.day_view.scale(scale, scale)

        #处理进度条和执行按钮状态
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(100)
        self.progressBar.setFormat(u'完成!')
        self.execute_button.setDisabled(False)
        self.execute_button.setText(u'执行')
        #改变一些控件的状态
        self.action_add_data.setDisabled(False)
        self.target_area.setDisabled(False)
        self.datetime.setDisabled(False)
        self.density_cell.setDisabled(False)
        self.density_class.setDisabled(False)
        self.day_cell.setDisabled(False)
        self.day_class.setDisabled(False)
        self.density_mxd.setDisabled(False)
        self.day_mxd.setDisabled(False)
        self.action_save_pic.setDisabled(False)

    def addData(self):
        fnames = QFileDialog.getOpenFileNames(self, u'请选择原始的电闪数据',
                                              u'E:/Documents/工作/雷电公报/闪电定位原始文本数据',
                                              'Text files (*.txt);;All(*.*)')

        self.in_parameters[u'origin_data_path'] = fnames[0]

    def savePic(self):
        densityPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'闪电密度空间分布.tif'])

        dayPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif'])

        directory = QFileDialog.getExistingDirectory(self,u'请选择图片保存位置',
                                                     u'E:/Documents/工作/雷电公报',
                                    QFileDialog.ShowDirsOnly|QFileDialog.DontResolveSymlinks)

        dest_density = os.path.join(directory,os.path.basename(densityPic))
        dest_day = os.path.join(directory,os.path.basename(dayPic))

        if os.path.isfile(dest_day) or os.path.isfile(dest_density):
            message = u"文件已经存在!"
            msgBox = QMessageBox()
            msgBox.setText(message)
            msgBox.setIcon(QMessageBox.Information)
            icon = QIcon()
            icon.addPixmap(QPixmap("./resource/weather-thunder.png"), QIcon.Normal, QIcon.Off)
            msgBox.setWindowIcon(icon)
            msgBox.setWindowTitle(" ")
            msgBox.exec_()
            return

        move(dayPic,directory)
        move(densityPic,directory)

    def openMxdDay(self):
        program  = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe'
        src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb'])
        dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']])
        src_file = ''.join([self.in_parameters[u'target_area'] , u"地闪雷暴日空间分布模板.mxd"])

        copy(os.path.join(src_dir,src_file),dest_dir)

        arguments = [os.path.join(dest_dir,src_file)]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def openMxdDensity(self):
        program  = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe'
        src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb'])
        dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']])
        src_file = ''.join([self.in_parameters[u'target_area'] ,u"闪电密度空间分布模板.mxd"])


        copy(os.path.join(src_dir,src_file),dest_dir)

        arguments = [os.path.join(dest_dir,src_file)]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def showAbout(self):
        self.about = About_Dialog()

    def showHelp(self):
        program  = u'C:/Windows/hh.exe'
        arguments = [''.join([cwd,'/help/help.CHM'])]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def updateTargetArea(self, area):
        self.in_parameters[u'target_area'] = area

    def updateDatetime(self, date):
        self.in_parameters[u'datetime'] = str(date.year()) + u'年'
        if self.in_parameters.has_key(u'origin_data_path'):
            self.in_parameters.__delitem__(u'origin_data_path')

    def updateDensityCell(self, cell):
        self.in_parameters[u'density_cell'] = str(cell)

    def updateDensityClass(self, nclass):
        self.in_parameters[u'density_class'] = nclass

    def updateDayCell(self, cell):
        self.in_parameters[u'day_cell'] = str(cell)


    def updateDayClass(self, nclass):
        self.in_parameters[u'day_class'] = nclass

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("MainWindow", "绍兴防雷中心 雷电公报制图"))
        self.datetime_label.setText(_translate("MainWindow", "年份"))
        self.datetime.setDisplayFormat(_translate("MainWindow", "yyyy"))
        self.target_area_label.setText(_translate("MainWindow", "地区"))
        self.target_area.setItemText(0, _translate("MainWindow", "绍兴市"))
        self.target_area.setItemText(1, _translate("MainWindow", "柯桥区"))
        self.target_area.setItemText(2, _translate("MainWindow", "上虞区"))
        self.target_area.setItemText(3, _translate("MainWindow", "诸暨市"))
        self.target_area.setItemText(4, _translate("MainWindow", "嵊州市"))
        self.target_area.setItemText(5, _translate("MainWindow", "新昌县"))
        self.density_cell_label.setText(_translate("MainWindow", "插值网格大小"))
        self.density_class_label.setText(_translate("MainWindow", "制图分类数目"))
        self.density_mxd.setText(_translate("MainWindow", "ArcGIS文档"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.density_tab), _translate("MainWindow", "电闪密度"))
        self.day_cell_label.setText(_translate("MainWindow", "插值网格大小"))
        self.day_class_label.setText(_translate("MainWindow", "制图分类数目"))
        self.day_mxd.setText(_translate("MainWindow", "ArcGIS文档"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.day_tab), _translate("MainWindow", "雷暴日"))
        self.execute_button.setText(_translate("MainWindow", "执行"))
        self.file_menu.setTitle(_translate("MainWindow", "文件"))
        self.help_menu.setTitle(_translate("MainWindow", "帮助"))
        self.action_add_data.setText(_translate("MainWindow", "加载数据"))
        self.action_help.setText(_translate("MainWindow", "使用说明"))
        self.action_about.setText(_translate("MainWindow", "关于"))
        self.action_save_pic.setText(_translate("MainWindow", "图片另存为"))
예제 #34
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(833, 594)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton_openfile = QPushButton(self.centralwidget)
        self.pushButton_openfile.setObjectName("pushButton_openfile")
        self.horizontalLayout.addWidget(self.pushButton_openfile)
        self.label_openfile = QLabel(self.centralwidget)
        self.label_openfile.setText("")
        self.label_openfile.setObjectName("label_openfile")
        self.horizontalLayout.addWidget(self.label_openfile)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.pushButton_start = QPushButton(self.centralwidget)
        self.pushButton_start.setObjectName("pushButton_start")
        self.horizontalLayout.addWidget(self.pushButton_start)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.pushButton_savepath = QPushButton(self.centralwidget)
        self.pushButton_savepath.setObjectName("pushButton_savepath")
        self.horizontalLayout_2.addWidget(self.pushButton_savepath)
        self.label_savepath = QLabel(self.centralwidget)
        self.label_savepath.setText("")
        self.label_savepath.setObjectName("label_savepath")
        self.horizontalLayout_2.addWidget(self.label_savepath)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.pushButton_learnedfile = QPushButton(self.centralwidget)
        self.pushButton_learnedfile.setObjectName("pushButton_learnedfile")
        self.horizontalLayout_2.addWidget(self.pushButton_learnedfile)
        self.label_learnedfile = QLabel(self.centralwidget)
        self.label_learnedfile.setText("")
        self.label_learnedfile.setObjectName("label_learnedfile")
        self.horizontalLayout_2.addWidget(self.label_learnedfile)
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem2)
        self.pushButton_download_audio = QPushButton(self.centralwidget)
        self.pushButton_download_audio.setObjectName(
            "pushButton_download_audio")
        self.horizontalLayout_2.addWidget(self.pushButton_download_audio)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.tableWidget = QTableWidget(self.centralwidget)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(0)
        self.tableWidget.setRowCount(0)
        self.verticalLayout.addWidget(self.tableWidget)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_openfile.setText(_translate("MainWindow", "打开文件"))
        self.pushButton_start.setText(_translate("MainWindow", "开始"))
        self.pushButton_savepath.setText(_translate("MainWindow", "保存路径"))
        self.pushButton_learnedfile.setText(_translate("MainWindow",
                                                       "需要剔除的单词"))
        self.pushButton_download_audio.setText(_translate(
            "MainWindow", "下载音频"))
예제 #35
0
class UIOpenPatientWindow(object):
    patient_info_initialized = QtCore.pyqtSignal(object)

    def setup_ui(self, open_patient_window_instance):
        if platform.system() == 'Darwin':
            self.stylesheet_path = "src/res/stylesheet.qss"
        else:
            self.stylesheet_path = "src/res/stylesheet-win-linux.qss"
        stylesheet = open(resource_path(self.stylesheet_path)).read()
        window_icon = QIcon()
        window_icon.addPixmap(
            QPixmap(resource_path("src/res/images/icon.ico")), QIcon.Normal,
            QIcon.Off)
        open_patient_window_instance.setObjectName("OpenPatientWindowInstance")
        open_patient_window_instance.setWindowIcon(window_icon)
        open_patient_window_instance.resize(840, 530)

        # Create a vertical box for containing the other elements and layouts
        self.open_patient_window_instance_vertical_box = QVBoxLayout()
        self.open_patient_window_instance_vertical_box.setObjectName(
            "OpenPatientWindowInstanceVerticalBox")

        # Create a label to prompt the user to enter the path to the directory that contains the DICOM files
        self.open_patient_directory_prompt = QLabel()
        self.open_patient_directory_prompt.setObjectName(
            "OpenPatientDirectoryPrompt")
        self.open_patient_directory_prompt.setAlignment(Qt.AlignLeft)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_directory_prompt)

        # Create a horizontal box to hold the input box for the directory and the choose button
        self.open_patient_directory_input_horizontal_box = QHBoxLayout()
        self.open_patient_directory_input_horizontal_box.setObjectName(
            "OpenPatientDirectoryInputHorizontalBox")
        # Create a textbox to contain the path to the directory that contains the DICOM files
        self.open_patient_directory_input_box = UIOpenPatientWindowDragAndDropEvent(
            self)

        self.open_patient_directory_input_box.setObjectName(
            "OpenPatientDirectoryInputBox")
        self.open_patient_directory_input_box.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_directory_input_box.returnPressed.connect(
            self.scan_directory_for_patient)
        self.open_patient_directory_input_horizontal_box.addWidget(
            self.open_patient_directory_input_box)

        # Create a choose button to open the file dialog
        self.open_patient_directory_choose_button = QPushButton()
        self.open_patient_directory_choose_button.setObjectName(
            "OpenPatientDirectoryChooseButton")
        self.open_patient_directory_choose_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_directory_choose_button.resize(
            self.open_patient_directory_choose_button.sizeHint().width(),
            self.open_patient_directory_input_box.height())
        self.open_patient_directory_choose_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_directory_input_horizontal_box.addWidget(
            self.open_patient_directory_choose_button)
        self.open_patient_directory_choose_button.clicked.connect(
            self.choose_button_clicked)
        # Create a widget to hold the input fields
        self.open_patient_directory_input_widget = QWidget()
        self.open_patient_directory_input_horizontal_box.setStretch(0, 4)
        self.open_patient_directory_input_widget.setLayout(
            self.open_patient_directory_input_horizontal_box)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_directory_input_widget)

        # Create a horizontal box to hold the stop button and direction to the user on where to select the patient
        self.open_patient_appear_prompt_and_stop_horizontal_box = QHBoxLayout()
        self.open_patient_appear_prompt_and_stop_horizontal_box.setObjectName(
            "OpenPatientAppearPromptAndStopHorizontalBox")
        # Create a label to show direction on where the files will appear
        self.open_patient_directory_appear_prompt = QLabel()
        self.open_patient_directory_appear_prompt.setObjectName(
            "OpenPatientDirectoryAppearPrompt")
        self.open_patient_directory_appear_prompt.setAlignment(Qt.AlignLeft)
        self.open_patient_appear_prompt_and_stop_horizontal_box.addWidget(
            self.open_patient_directory_appear_prompt)
        self.open_patient_appear_prompt_and_stop_horizontal_box.addStretch(1)
        # Create a button to stop searching
        self.open_patient_window_stop_button = QPushButton()
        self.open_patient_window_stop_button.setObjectName(
            "OpenPatientWindowStopButton")
        self.open_patient_window_stop_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_stop_button.resize(
            self.open_patient_window_stop_button.sizeHint().width(),
            self.open_patient_window_stop_button.sizeHint().height())
        self.open_patient_window_stop_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_window_stop_button.clicked.connect(
            self.stop_button_clicked)
        self.open_patient_window_stop_button.setProperty(
            "QPushButtonClass", "fail-button")
        self.open_patient_window_stop_button.setVisible(
            False)  # Button doesn't show until a search commences
        self.open_patient_appear_prompt_and_stop_horizontal_box.addWidget(
            self.open_patient_window_stop_button)
        # Create a widget to hold the layout
        self.open_patient_appear_prompt_and_stop_widget = QWidget()
        self.open_patient_appear_prompt_and_stop_widget.setLayout(
            self.open_patient_appear_prompt_and_stop_horizontal_box)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_appear_prompt_and_stop_widget)

        # Create a tree view list to list out all patients in the directory selected above
        self.open_patient_window_patients_tree = QTreeWidget()
        self.open_patient_window_patients_tree.setObjectName(
            "OpenPatientWindowPatientsTree")
        self.open_patient_window_patients_tree.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_patients_tree.resize(
            self.open_patient_window_patients_tree.sizeHint().width(),
            self.open_patient_window_patients_tree.sizeHint().height())
        self.open_patient_window_patients_tree.setHeaderHidden(True)
        self.open_patient_window_patients_tree.setHeaderLabels([""])
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_window_patients_tree)

        # Create a label to show what would happen if they select the patient
        self.open_patient_directory_result_label = QtWidgets.QLabel()
        self.open_patient_directory_result_label.setObjectName(
            "OpenPatientDirectoryResultLabel")
        self.open_patient_directory_result_label.setAlignment(Qt.AlignLeft)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_directory_result_label)

        # Create a horizontal box to hold the Cancel and Open button
        self.open_patient_window_patient_open_actions_horizontal_box = QHBoxLayout(
        )
        self.open_patient_window_patient_open_actions_horizontal_box.setObjectName(
            "OpenPatientWindowPatientOpenActionsHorizontalBox")
        self.open_patient_window_patient_open_actions_horizontal_box.addStretch(
            1)
        # Add a button to go back/exit from the application
        self.open_patient_window_exit_button = QPushButton()
        self.open_patient_window_exit_button.setObjectName(
            "OpenPatientWindowExitButton")
        self.open_patient_window_exit_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_exit_button.resize(
            self.open_patient_window_stop_button.sizeHint().width(),
            self.open_patient_window_stop_button.sizeHint().height())
        self.open_patient_window_exit_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_window_exit_button.clicked.connect(
            self.exit_button_clicked)
        self.open_patient_window_exit_button.setProperty(
            "QPushButtonClass", "fail-button")
        self.open_patient_window_patient_open_actions_horizontal_box.addWidget(
            self.open_patient_window_exit_button)

        # Add a button to confirm opening of the patient
        self.open_patient_window_confirm_button = QPushButton()
        self.open_patient_window_confirm_button.setObjectName(
            "OpenPatientWindowConfirmButton")
        self.open_patient_window_confirm_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_confirm_button.resize(
            self.open_patient_window_confirm_button.sizeHint().width(),
            self.open_patient_window_confirm_button.sizeHint().height())
        self.open_patient_window_confirm_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_window_confirm_button.clicked.connect(
            self.confirm_button_clicked)
        self.open_patient_window_confirm_button.setProperty(
            "QPushButtonClass", "success-button")
        self.open_patient_window_patient_open_actions_horizontal_box.addWidget(
            self.open_patient_window_confirm_button)

        # Create a widget to house all of the actions button for open patient window
        self.open_patient_window_patient_open_actions_widget = QWidget()
        self.open_patient_window_patient_open_actions_widget.setLayout(
            self.open_patient_window_patient_open_actions_horizontal_box)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_window_patient_open_actions_widget)

        # Set the vertical box fourth element, the tree view, to stretch out as far as possible
        self.open_patient_window_instance_vertical_box.setStretch(
            3, 4)  # Stretch the treeview out as far as possible
        self.open_patient_window_instance_central_widget = QWidget()
        self.open_patient_window_instance_central_widget.setObjectName(
            "OpenPatientWindowInstanceCentralWidget")
        self.open_patient_window_instance_central_widget.setLayout(
            self.open_patient_window_instance_vertical_box)

        # Create threadpool for multithreading
        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" %
              self.threadpool.maxThreadCount())
        # Create interrupt event for stopping the directory search
        self.interrupt_flag = threading.Event()

        # Bind all texts into the buttons and labels
        self.retranslate_ui(open_patient_window_instance)
        # Set the central widget, ready for display
        open_patient_window_instance.setCentralWidget(
            self.open_patient_window_instance_central_widget)

        # Set the current stylesheet to the instance and connect it back to the caller through slot
        open_patient_window_instance.setStyleSheet(stylesheet)
        QtCore.QMetaObject.connectSlotsByName(open_patient_window_instance)

    def retranslate_ui(self, open_patient_window_instance):
        _translate = QtCore.QCoreApplication.translate
        open_patient_window_instance.setWindowTitle(
            _translate("OpenPatientWindowInstance",
                       "OnkoDICOM - Select Patient"))
        self.open_patient_directory_prompt.setText(
            _translate(
                "OpenPatientWindowInstance",
                "Choose the path of the folder containing DICOM files to load Patient's details:"
            ))
        self.open_patient_directory_input_box.setPlaceholderText(
            _translate(
                "OpenPatientWindowInstance",
                "Enter DICOM Files Path (For example, C:\path\\to\your\DICOM\Files)"
            ))
        self.open_patient_directory_choose_button.setText(
            _translate("OpenPatientWindowInstance", "Choose"))
        self.open_patient_directory_appear_prompt.setText(
            _translate(
                "OpenPatientWindowInstance",
                "Patient File directory shown below once file path chosen. Please select the file(s) you want to open:"
            ))
        self.open_patient_directory_result_label.setText(
            "The selected directory(s) above will be opened in the OnkoDICOM program."
        )
        self.open_patient_window_stop_button.setText(
            _translate("OpenPatientWindowInstance", "Stop Search"))
        self.open_patient_window_exit_button.setText(
            _translate("OpenPatientWindowInstance", "Exit"))
        self.open_patient_window_confirm_button.setText(
            _translate("OpenPatientWindowInstance", "Confirm"))

    def exit_button_clicked(self):
        QCoreApplication.exit(0)

    def scan_directory_for_patient(self):
        self.filepath = self.open_patient_directory_input_box.text()
        # Proceed if a folder was selected
        if self.filepath != "":
            # Update the QTreeWidget to reflect data being loaded
            # First, clear the widget of any existing data
            self.open_patient_window_patients_tree.clear()

            # Next, update the tree widget
            self.open_patient_window_patients_tree.addTopLevelItem(
                QTreeWidgetItem(["Loading selected directory..."]))

            # The choose button is disabled until the thread finishes executing
            self.open_patient_directory_choose_button.setEnabled(False)

            # Reveals the Stop Search button for the duration of the search
            self.open_patient_window_stop_button.setVisible(True)

            # The interrupt flag is then un-set if a previous search has been stopped.
            self.interrupt_flag.clear()

            # Then, create a new thread that will load the selected folder
            worker = Worker(DICOMDirectorySearch.get_dicom_structure,
                            self.filepath,
                            self.interrupt_flag,
                            progress_callback=True)
            worker.signals.result.connect(self.on_search_complete)
            worker.signals.progress.connect(self.search_progress)

            # Execute the thread
            self.threadpool.start(worker)

    def choose_button_clicked(self):
        """
        Executes when the choose button is clicked.
        Gets filepath from the user and loads all files and subdirectories.
        """
        # Get folder path from pop up dialog box
        self.filepath = QtWidgets.QFileDialog.getExistingDirectory(
            None, 'Select patient folder...', '')
        self.open_patient_directory_input_box.setText(self.filepath)
        self.scan_directory_for_patient()

    def stop_button_clicked(self):
        self.interrupt_flag.set()

    def search_progress(self, progress_update):
        """
        Current progress of the file search.
        """
        self.open_patient_window_patients_tree.clear()
        self.open_patient_window_patients_tree.addTopLevelItem(
            QTreeWidgetItem([
                "Loading selected directory... (%s files searched)" %
                progress_update
            ]))

    def on_search_complete(self, dicom_structure):
        """
        Executes once the directory search is complete.
        :param dicom_structure: DICOMStructure object constructed by the directory search.
        """
        self.open_patient_directory_choose_button.setEnabled(True)
        self.open_patient_window_stop_button.setVisible(False)
        self.open_patient_window_patients_tree.clear()

        if dicom_structure is None:  # dicom_structure will be None if function was interrupted.
            return

        for patient_item in dicom_structure.get_tree_items_list():
            self.open_patient_window_patients_tree.addTopLevelItem(
                patient_item)

        if len(dicom_structure.patients) == 0:
            QMessageBox.about(self, "No files found",
                              "Selected directory contains no DICOM files.")

    def confirm_button_clicked(self):
        """
        Begins loading of the selected files.
        """
        selected_files = []
        for item in self.get_checked_leaves():
            selected_files += item.dicom_object.get_files()

        if len(selected_files) > 0:
            self.progress_window = ProgressWindow(
                self,
                QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint)
            self.progress_window.signal_loaded.connect(self.on_loaded)
            self.progress_window.signal_error.connect(self.on_loading_error)

            self.progress_window.start_loading(selected_files)
            self.progress_window.exec_()
        else:
            QMessageBox.about(self, "Unable to open selection",
                              "No files selected.")

    def on_loaded(self, results):
        """
        Executes when the progress bar finishes loaded the selected files.
        """
        if results[0] is True:  # Will be NoneType if loading was interrupted.
            self.patient_info_initialized.emit(
                results[1])  # Emits the progress window.

    def on_loading_error(self, error_code):
        """
        Error handling for progress window.
        """
        if error_code == 0:
            QMessageBox.about(
                self.progress_window, "Unable to open selection",
                "Selected files cannot be opened as they are not a DICOM-RT set."
            )
            self.progress_window.close()
        elif error_code == 1:
            QMessageBox.about(
                self.progress_window, "Unable to open selection",
                "Selected files cannot be opened as they contain unsupported DICOM classes."
            )
            self.progress_window.close()

    def get_checked_leaves(self):
        """
        :return: A list of all QTreeWidgetItems in the QTreeWidget that are both leaves and checked.
        """
        checked_items = []

        def recurse(parent_item: QTreeWidgetItem):
            for i in range(parent_item.childCount()):
                child = parent_item.child(i)
                grand_children = child.childCount()
                if grand_children > 0:
                    recurse(child)
                else:
                    if child.checkState(0) == Qt.Checked:
                        checked_items.append(child)

        recurse(self.open_patient_window_patients_tree.invisibleRootItem())
        return checked_items
class TemplateMultipleVariablesDialog(QDialog):
    """
    Class implementing a dialog for entering multiple template variables.
    """
    def __init__(self, variables, parent=None):
        """
        Constructor
        
        @param variables list of template variable names (list of strings)
        @param parent parent widget of this dialog (QWidget)
        """
        super(TemplateMultipleVariablesDialog, self).__init__(parent)

        self.TemplateMultipleVariablesDialogLayout = QVBoxLayout(self)
        self.TemplateMultipleVariablesDialogLayout.setContentsMargins(
            6, 6, 6, 6)
        self.TemplateMultipleVariablesDialogLayout.setSpacing(6)
        self.TemplateMultipleVariablesDialogLayout.setObjectName(
            "TemplateMultipleVariablesDialogLayout")
        self.setLayout(self.TemplateMultipleVariablesDialogLayout)

        # generate the scrollarea
        self.variablesView = QScrollArea(self)
        self.variablesView.setObjectName("variablesView")
        self.TemplateMultipleVariablesDialogLayout.addWidget(
            self.variablesView)
        
        self.variablesView.setWidgetResizable(True)
        self.variablesView.setFrameStyle(QFrame.NoFrame)
        
        self.top = QWidget(self)
        self.variablesView.setWidget(self.top)
        self.grid = QGridLayout(self.top)
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.grid.setSpacing(6)
        self.top.setLayout(self.grid)

        # populate the scrollarea with labels and text edits
        self.variablesEntries = {}
        row = 0
        for var in variables:
            label = QLabel("{0}:".format(var), self.top)
            self.grid.addWidget(label, row, 0, Qt.Alignment(Qt.AlignTop))
            if var.find(":") >= 0:
                formatStr = var[1:-1].split(":")[1]
                if formatStr in ["ml", "rl"]:
                    t = QTextEdit(self.top)
                    t.setTabChangesFocus(True)
                else:
                    t = QLineEdit(self.top)
            else:
                t = QLineEdit(self.top)
            self.grid.addWidget(t, row, 1)
            self.variablesEntries[var] = t
            row += 1
        # add a spacer to make the entries aligned at the top
        spacer = QSpacerItem(
            20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.grid.addItem(spacer, row, 1)
        self.variablesEntries[variables[0]].setFocus()
        self.top.adjustSize()

        # generate the buttons
        layout1 = QHBoxLayout()
        layout1.setContentsMargins(0, 0, 0, 0)
        layout1.setSpacing(6)
        layout1.setObjectName("layout1")
        
        spacer1 = QSpacerItem(
            40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        layout1.addItem(spacer1)

        self.okButton = QPushButton(self)
        self.okButton.setObjectName("okButton")
        self.okButton.setDefault(True)
        layout1.addWidget(self.okButton)

        self.cancelButton = QPushButton(self)
        self.cancelButton.setObjectName("cancelButton")
        layout1.addWidget(self.cancelButton)
        
        spacer2 = QSpacerItem(
            40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        layout1.addItem(spacer2)
        
        self.TemplateMultipleVariablesDialogLayout.addLayout(layout1)

        # set the texts of the standard widgets
        self.setWindowTitle(self.tr("Enter Template Variables"))
        self.okButton.setText(self.tr("&OK"))
        self.cancelButton.setText(self.tr("&Cancel"))

        # polish up the dialog
        self.resize(QSize(400, 480).expandedTo(self.minimumSizeHint()))

        self.okButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)

    def getVariables(self):
        """
        Public method to get the values for all variables.
        
        @return dictionary with the variable as a key and its value (string)
        """
        values = {}
        for var, textEdit in list(self.variablesEntries.items()):
            try:
                values[var] = textEdit.text()
            except AttributeError:
                values[var] = textEdit.toPlainText()
        return values
예제 #37
0
파일: myWidgets.py 프로젝트: MazeFX/pat
class MyDragDropBox(QFrame):

    _currentFile = None

    def __init__(self, *args):
        super(MyDragDropBox, self).__init__(*args)
        Lumberjack.info('spawning a << MyDragDropBox >>')
        print(Fore.GREEN + '--=== DRAGDROPBOX ===--')
        print(Fore.GREEN + 'Here come the inits!')
        print(Fore.GREEN + 'args: ', args)
        print(Fore.GREEN + '==--- DRAGDROPBOX ---==')

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        self.DropLabel = QLabel(self)
        font = QFont()
        font.setPointSize(12)
        font.setBold(False)
        font.setUnderline(False)
        font.setWeight(50)
        self.DropLabel.setFont(font)
        self.DropLabel.setAlignment(Qt.AlignCenter)
        self.DropLabel.setObjectName("DropLabel")
        self.verticalLayout.addWidget(self.DropLabel)
        self.edit = False

    def dragEnterEvent(self, event):
        Lumberjack.info('< MyDragDropBox > - -> (getRecurrenceValue)')
        print(Fore.GREEN + '-- DRAGDROPBOX -- Enter with drag')
        print(Fore.GREEN + '-- DRAGDROPBOX -- passed event: ', event)
        if event.mimeData().hasUrls:
            print(Fore.GREEN + '-- DRAGDROPBOX -- event accepted.')
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        Lumberjack.info('< MyDragDropBox > - -> (getRecurrenceValue)')
        print(Fore.GREEN + '-- DRAGDROPBOX -- Dropped something??')
        print(Fore.GREEN + '-- DRAGDROPBOX -- passed event: ', event)
        if not self.edit:
            event.accept()
            return
        if event.mimeData().hasUrls:
            event.setDropAction(Qt.CopyAction)
            event.accept()
            print(Fore.GREEN + '-- DRAGDROPBOX -- event accepted.')
            l = []
            for url in event.mimeData().urls():
                l.append(str(url.toLocalFile()))
            print(Fore.GREEN + '-- DRAGDROPBOX -- files recieved: ', l)
            self.setCurrentFile(l)
        else:
            event.ignore()

    def mouseDoubleClickEvent(self, QMouseEvent):
        Lumberjack.info('< MyDragDropBox > - -> (mouseDoubleClickEvent)')
        filename = self.getCurrentFile()
        print(Fore.GREEN + 'Current file name for opening = ', filename)
        if filename:
            if os.path.exists(filename):
                print(Fore.GREEN + 'Current file exists and now opening')
                os.startfile(filename)
        for attr in self.__dict__:
            Lumberjack.debug('(mouseDoubleClickEvent) - widget attr = {}'.format(attr))

    def getCurrentFile(self):
        Lumberjack.info('< MyDragDropBox > - -> (getCurrentFile)')
        print(Fore.GREEN + '-- DRAGDROPBOX -- Getting the file: ')
        print(Fore.GREEN + '---------------------------------------')
        print(Fore.GREEN + 'Current File = ', self._currentFile)
        print(Fore.GREEN + 'With Type = ', type(self._currentFile))
        return self._currentFile

    def setCurrentFile(self, file):
        Lumberjack.info('< MyDragDropBox > - -> (setCurrentFile)')
        print(Fore.GREEN + '-- DRAGDROPBOX -- Setting the file: ')
        print(Fore.GREEN + '---------------------------------------')
        print(Fore.GREEN + 'file value = ', file)
        print(Fore.GREEN + 'With Type = ', type(file))
        self._currentFile = file
        self.check_widget_layout()

    currentFile = pyqtProperty(str, fget=getCurrentFile, fset=setCurrentFile)

    def check_widget_layout(self):
        Lumberjack.info('< MyDragDropBox > - -> (check_widget_layout)')
        print(Fore.GREEN + '-- DRAGDROPBOX -- setting layout for: ', self.DropLabel)
        if self._currentFile:
            self.DropLabel.setText('Open File')
        else:
            self.DropLabel.setText('Drop File')
예제 #38
0
class Visualizer(QMainWindow):
    width = 640
    height = 360

    def __init__(self, *args, **kwargs):
        super(Visualizer, self).__init__(*args, **kwargs)

        self.setWindowTitle("Visualizer")
        self.resize(self.width, self.height + self.height / 2)
        self.setMinimumSize(QSize(self.width, self.height + self.height / 2))
        self.setMaximumSize(QSize(self.width, self.height + self.height / 2))
        self.centralwidget = QWidget(self)
        self.centralwidget.setEnabled(True)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setMinimumSize(
            QSize(self.width, self.height + self.height / 2))
        self.centralwidget.setMaximumSize(
            QSize(self.width, self.height + self.height / 2))
        self.centralwidget.setObjectName("centralwidget")
        self.widget = QWidget(self.centralwidget)
        # self.widget.setGeometry(QRect(0, 0, 324, 274))
        self.widget.setObjectName("widget")
        self.verticalLayout = QVBoxLayout(self.widget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setSpacing(0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.mask = QLabel(self.widget)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.mask.sizePolicy().hasHeightForWidth())
        self.mask.setSizePolicy(sizePolicy)
        self.mask.setMinimumSize(QSize(self.width / 2, self.height / 2))
        self.mask.setMaximumSize(QSize(self.width / 2, self.height / 2))
        self.mask.setObjectName("mask")
        self.horizontalLayout.addWidget(self.mask)
        self.shrink = QLabel(self.widget)
        self.shrink.setMinimumSize(QSize(self.width / 2, self.height / 2))
        self.shrink.setMaximumSize(QSize(self.width / 2, self.height / 2))
        self.shrink.setObjectName("shrink")
        self.horizontalLayout.addWidget(self.shrink)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.palette = QLabel(self.widget)
        self.palette.setMinimumSize(QSize(self.width, self.height))
        self.palette.setMaximumSize(QSize(self.width, self.height))
        self.palette.setObjectName("palette")
        self.verticalLayout.addWidget(self.palette)
        self.setCentralWidget(self.centralwidget)

    def update_palette(self, image):
        self.palette.setPixmap(convert_image(image, self.width, self.height))

    def update_shrink(self, image):
        self.shrink.setPixmap(
            convert_image(image, self.width / 2, self.height / 2))

    def update_mask(self, image):
        self.mask.setPixmap(
            convert_image(image, self.width / 2, self.height / 2))
예제 #39
0
class PreviewWidgetStyle(QGroupBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTitle(self.tr("Preview"))
        self.setMaximumHeight(220)
        self.setObjectName("groupBox")

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")

        self.tabWidget = QTabWidget(self)
        self.tabWidget.setObjectName("tabWidgetPreview")

        self.tab = QWidget()
        self.tab.setObjectName("tab")

        self.horizontalLayout = QHBoxLayout(self.tab)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.groupBox = QGroupBox(self.tab)
        self.groupBox.setTitle(self.tr("Group Box"))
        self.groupBox.setObjectName("groupBox")


        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.verticalLayout_2.setObjectName("verticalLayout_2")

        self.radioButton = QRadioButton(self.groupBox)
        self.radioButton.setText(self.tr("Radio Button"))
        self.radioButton.setChecked(True)
        self.radioButton.setObjectName("radioButton")
        self.verticalLayout_2.addWidget(self.radioButton)

        self.radioButton_2 = QRadioButton(self.groupBox)
        self.radioButton_2.setText(self.tr("Radio Button"))
        self.radioButton_2.setObjectName("radioButton_2")
        self.verticalLayout_2.addWidget(self.radioButton_2)

        self.line = QFrame(self.groupBox)
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_2.addWidget(self.line)

        self.checkBox = QCheckBox(self.groupBox)
        self.checkBox.setText(self.tr("Check Box"))
        self.checkBox.setChecked(True)
        self.checkBox.setObjectName("checkBox")
        self.verticalLayout_2.addWidget(self.checkBox)

        self.horizontalLayout.addWidget(self.groupBox)


        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")

        self.progressBar = QProgressBar(self.tab)
        self.progressBar.setProperty("value", 75)
        self.progressBar.setObjectName("progressBar")
        self.verticalLayout_3.addWidget(self.progressBar)

        self.horizontalSlider = QSlider(self.tab)
        self.horizontalSlider.setProperty("value", 45)
        self.horizontalSlider.setSliderPosition(45)
        self.horizontalSlider.setOrientation(Qt.Horizontal)
        self.horizontalSlider.setObjectName("horizontalSlider")
        self.verticalLayout_3.addWidget(self.horizontalSlider)

        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.spinBox = QSpinBox(self.tab)
        self.spinBox.setObjectName("spinBox")
        self.horizontalLayout_2.addWidget(self.spinBox)

        self.pushButton = QPushButton(self.tab)
        self.pushButton.setText(self.tr("Button"))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_2.addWidget(self.pushButton)

        self.verticalLayout_3.addLayout(self.horizontalLayout_2)

        self.comboBox = QComboBox(self.tab)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem(self.tr("Combo Box"))
        self.verticalLayout_3.addWidget(self.comboBox)

        self.horizontalLayout.addLayout(self.verticalLayout_3)

        self.verticalScrollBar = QScrollBar(self.tab)
        self.verticalScrollBar.setPageStep(50)
        self.verticalScrollBar.setOrientation(Qt.Vertical)
        self.verticalScrollBar.setObjectName("verticalScrollBar")
        self.horizontalLayout.addWidget(self.verticalScrollBar)
        self.tabWidget.addTab(self.tab, self.tr("Tab 1"))


        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, self.tr("Tab 2"))

        self.verticalLayout.addWidget(self.tabWidget)

        self.pushButton.installEventFilter(self)
        self.pushButton.setFocusPolicy(Qt.NoFocus)
        self.radioButton.installEventFilter(self)
        self.radioButton.setFocusPolicy(Qt.NoFocus)
        self.radioButton_2.installEventFilter(self)
        self.radioButton_2.setFocusPolicy(Qt.NoFocus)
        self.checkBox.installEventFilter(self)
        self.checkBox.setFocusPolicy(Qt.NoFocus)
        self.comboBox.installEventFilter(self)
        self.comboBox.setFocusPolicy(Qt.NoFocus)
        self.spinBox.installEventFilter(self)
        self.spinBox.setFocusPolicy(Qt.NoFocus)
        self.horizontalSlider.installEventFilter(self)
        self.horizontalSlider.setFocusPolicy(Qt.NoFocus)
        self.verticalScrollBar.installEventFilter(self)
        self.verticalScrollBar.setFocusPolicy(Qt.NoFocus)
        self.tab.installEventFilter(self)
        self.tab.setFocusPolicy(Qt.NoFocus)
        self.tab_2.installEventFilter(self)
        self.tab_2.setFocusPolicy(Qt.NoFocus)
        self.tabWidget.installEventFilter(self)
        self.tabWidget.setFocusPolicy(Qt.NoFocus)

        self.tabWidget.currentChanged.connect(self.noClick)

    def noClick(self, x):
        self.tabWidget.setCurrentIndex(0)

    def eventFilter(self, obj, event):
        if self.pushButton:
            if event.type() == QEvent.MouseButtonRelease:
                return True
            elif event.type() == QEvent.MouseButtonPress:
                return True
            elif event.type() == QEvent.MouseButtonDblClick:
                return True
            else:
                return False
        else:
            super().eventFilter(obj, event)
예제 #40
0
class ConfigurationWidget(QWidget):
    """
    Class implementing a dialog for the configuration of eric6.
    
    @signal preferencesChanged() emitted after settings have been changed
    @signal masterPasswordChanged(str, str) emitted after the master
        password has been changed with the old and the new password
    @signal accepted() emitted to indicate acceptance of the changes
    @signal rejected() emitted to indicate rejection of the changes
    """
    preferencesChanged = pyqtSignal()
    masterPasswordChanged = pyqtSignal(str, str)
    accepted = pyqtSignal()
    rejected = pyqtSignal()
    
    DefaultMode = 0
    HelpBrowserMode = 1
    TrayStarterMode = 2
    
    def __init__(self, parent=None, fromEric=True, displayMode=DefaultMode):
        """
        Constructor
        
        @param parent The parent widget of this dialog. (QWidget)
        @keyparam fromEric flag indicating a dialog generation from within the
            eric6 ide (boolean)
        @keyparam displayMode mode of the configuration dialog
            (DefaultMode, HelpBrowserMode, TrayStarterMode)
        @exception RuntimeError raised to indicate an invalid dialog mode
        """
        assert displayMode in (
            ConfigurationWidget.DefaultMode,
            ConfigurationWidget.HelpBrowserMode,
            ConfigurationWidget.TrayStarterMode
        )
        
        super(ConfigurationWidget, self).__init__(parent)
        self.fromEric = fromEric
        self.displayMode = displayMode
        
        self.__setupUi()
        
        self.itmDict = {}
        
        if not fromEric:
            from PluginManager.PluginManager import PluginManager
            try:
                self.pluginManager = e5App().getObject("PluginManager")
            except KeyError:
                self.pluginManager = PluginManager(self)
                e5App().registerObject("PluginManager", self.pluginManager)
        
        if displayMode == ConfigurationWidget.DefaultMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function create to
                # create the configuration page. This must have the method
                # save to save the settings.
                "applicationPage":
                [self.tr("Application"), "preferences-application.png",
                 "ApplicationPage", None, None],
                "cooperationPage":
                [self.tr("Cooperation"), "preferences-cooperation.png",
                 "CooperationPage", None, None],
                "corbaPage":
                [self.tr("CORBA"), "preferences-orbit.png",
                 "CorbaPage", None, None],
                "emailPage":
                [self.tr("Email"), "preferences-mail_generic.png",
                 "EmailPage", None, None],
                "graphicsPage":
                [self.tr("Graphics"), "preferences-graphics.png",
                 "GraphicsPage", None, None],
                "iconsPage":
                [self.tr("Icons"), "preferences-icons.png",
                 "IconsPage", None, None],
                "ircPage":
                [self.tr("IRC"), "irc.png",
                 "IrcPage", None, None],
                "networkPage":
                [self.tr("Network"), "preferences-network.png",
                 "NetworkPage", None, None],
                "notificationsPage":
                [self.tr("Notifications"),
                 "preferences-notifications.png",
                 "NotificationsPage", None, None],
                "pluginManagerPage":
                [self.tr("Plugin Manager"),
                 "preferences-pluginmanager.png",
                 "PluginManagerPage", None, None],
                "printerPage":
                [self.tr("Printer"), "preferences-printer.png",
                 "PrinterPage", None, None],
                "pythonPage":
                [self.tr("Python"), "preferences-python.png",
                 "PythonPage", None, None],
                "qtPage":
                [self.tr("Qt"), "preferences-qtlogo.png",
                 "QtPage", None, None],
                "securityPage":
                [self.tr("Security"), "preferences-security.png",
                 "SecurityPage", None, None],
                "shellPage":
                [self.tr("Shell"), "preferences-shell.png",
                 "ShellPage", None, None],
                "tasksPage":
                [self.tr("Tasks"), "task.png",
                 "TasksPage", None, None],
                "templatesPage":
                [self.tr("Templates"), "preferences-template.png",
                 "TemplatesPage", None, None],
                "trayStarterPage":
                [self.tr("Tray Starter"), "erict.png",
                 "TrayStarterPage", None, None],
                "vcsPage":
                [self.tr("Version Control Systems"),
                 "preferences-vcs.png",
                 "VcsPage", None, None],
                
                "0debuggerPage":
                [self.tr("Debugger"), "preferences-debugger.png",
                 None, None, None],
                "debuggerGeneralPage":
                [self.tr("General"), "preferences-debugger.png",
                 "DebuggerGeneralPage", "0debuggerPage", None],
                "debuggerPythonPage":
                [self.tr("Python"), "preferences-pyDebugger.png",
                 "DebuggerPythonPage", "0debuggerPage", None],
                "debuggerPython3Page":
                [self.tr("Python3"), "preferences-pyDebugger.png",
                 "DebuggerPython3Page", "0debuggerPage", None],
                "debuggerRubyPage":
                [self.tr("Ruby"), "preferences-rbDebugger.png",
                 "DebuggerRubyPage", "0debuggerPage", None],
                
                "0editorPage":
                [self.tr("Editor"), "preferences-editor.png",
                 None, None, None],
                "editorAPIsPage":
                [self.tr("APIs"), "preferences-api.png",
                 "EditorAPIsPage", "0editorPage", None],
                "editorAutocompletionPage":
                [self.tr("Autocompletion"),
                 "preferences-autocompletion.png",
                 "EditorAutocompletionPage", "0editorPage", None],
                "editorAutocompletionQScintillaPage":
                [self.tr("QScintilla"), "qscintilla.png",
                 "EditorAutocompletionQScintillaPage",
                 "editorAutocompletionPage", None],
                "editorCalltipsPage":
                [self.tr("Calltips"), "preferences-calltips.png",
                 "EditorCalltipsPage", "0editorPage", None],
                "editorCalltipsQScintillaPage":
                [self.tr("QScintilla"), "qscintilla.png",
                 "EditorCalltipsQScintillaPage", "editorCalltipsPage", None],
                "editorGeneralPage":
                [self.tr("General"), "preferences-general.png",
                 "EditorGeneralPage", "0editorPage", None],
                "editorFilePage":
                [self.tr("Filehandling"),
                 "preferences-filehandling.png",
                 "EditorFilePage", "0editorPage", None],
                "editorSearchPage":
                [self.tr("Searching"), "preferences-search.png",
                 "EditorSearchPage", "0editorPage", None],
                "editorSpellCheckingPage":
                [self.tr("Spell checking"),
                 "preferences-spellchecking.png",
                 "EditorSpellCheckingPage", "0editorPage", None],
                "editorStylesPage":
                [self.tr("Style"), "preferences-styles.png",
                 "EditorStylesPage", "0editorPage", None],
                "editorSyntaxPage":
                [self.tr("Code Checkers"), "preferences-debugger.png",
                 "EditorSyntaxPage", "0editorPage", None],
                "editorTypingPage":
                [self.tr("Typing"), "preferences-typing.png",
                 "EditorTypingPage", "0editorPage", None],
                "editorExportersPage":
                [self.tr("Exporters"), "preferences-exporters.png",
                 "EditorExportersPage", "0editorPage", None],
                
                "1editorLexerPage":
                [self.tr("Highlighters"),
                 "preferences-highlighting-styles.png",
                 None, "0editorPage", None],
                "editorHighlightersPage":
                [self.tr("Filetype Associations"),
                 "preferences-highlighter-association.png",
                 "EditorHighlightersPage", "1editorLexerPage", None],
                "editorHighlightingStylesPage":
                [self.tr("Styles"),
                 "preferences-highlighting-styles.png",
                 "EditorHighlightingStylesPage", "1editorLexerPage", None],
                "editorKeywordsPage":
                [self.tr("Keywords"), "preferences-keywords.png",
                 "EditorKeywordsPage", "1editorLexerPage", None],
                "editorPropertiesPage":
                [self.tr("Properties"), "preferences-properties.png",
                 "EditorPropertiesPage", "1editorLexerPage", None],
                
                "0helpPage":
                [self.tr("Help"), "preferences-help.png",
                 None, None, None],
                "helpAppearancePage":
                [self.tr("Appearance"), "preferences-styles.png",
                 "HelpAppearancePage", "0helpPage", None],
                "helpDocumentationPage":
                [self.tr("Help Documentation"),
                 "preferences-helpdocumentation.png",
                 "HelpDocumentationPage", "0helpPage", None],
                "helpViewersPage":
                [self.tr("Help Viewers"),
                 "preferences-helpviewers.png",
                 "HelpViewersPage", "0helpPage", None],
                "helpVirusTotalPage":
                [self.tr("VirusTotal Interface"), "virustotal.png",
                 "HelpVirusTotalPage", "0helpPage", None],
                "helpWebBrowserPage":
                [self.tr("eric6 Web Browser"), "ericWeb.png",
                 "HelpWebBrowserPage", "0helpPage", None],
                
                "0projectPage":
                [self.tr("Project"), "preferences-project.png",
                 None, None, None],
                "projectBrowserPage":
                [self.tr("Project Viewer"), "preferences-project.png",
                 "ProjectBrowserPage", "0projectPage", None],
                "projectPage":
                [self.tr("Project"), "preferences-project.png",
                 "ProjectPage", "0projectPage", None],
                "multiProjectPage":
                [self.tr("Multiproject"),
                 "preferences-multiproject.png",
                 "MultiProjectPage", "0projectPage", None],
                
                "0interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 None, None, None],
                "interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 "InterfacePage", "0interfacePage", None],
                "viewmanagerPage":
                [self.tr("Viewmanager"), "preferences-viewmanager.png",
                 "ViewmanagerPage", "0interfacePage", None],
            }
            
            self.configItems.update(
                e5App().getObject("PluginManager").getPluginConfigData())
        elif displayMode == ConfigurationWidget.HelpBrowserMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function create to
                # create the configuration page. This must have the method
                # save to save the settings.
                "interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 "HelpInterfacePage", None, None],
                "networkPage":
                [self.tr("Network"), "preferences-network.png",
                 "NetworkPage", None, None],
                "printerPage":
                [self.tr("Printer"), "preferences-printer.png",
                 "PrinterPage", None, None],
                "securityPage":
                [self.tr("Security"), "preferences-security.png",
                 "SecurityPage", None, None],
                
                "0helpPage":
                [self.tr("Help"), "preferences-help.png",
                 None, None, None],
                "helpAppearancePage":
                [self.tr("Appearance"), "preferences-styles.png",
                 "HelpAppearancePage", "0helpPage", None],
                "helpDocumentationPage":
                [self.tr("Help Documentation"),
                 "preferences-helpdocumentation.png",
                 "HelpDocumentationPage", "0helpPage", None],
                "helpVirusTotalPage":
                [self.tr("VirusTotal Interface"), "virustotal.png",
                 "HelpVirusTotalPage", "0helpPage", None],
                "helpWebBrowserPage":
                [self.tr("eric6 Web Browser"), "ericWeb.png",
                 "HelpWebBrowserPage", "0helpPage", None],
            }
        elif displayMode == ConfigurationWidget.TrayStarterMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function create to
                # create the configuration page. This must have the method
                # save to save the settings.
                "trayStarterPage":
                [self.tr("Tray Starter"), "erict.png",
                 "TrayStarterPage", None, None],
            }
        else:
            raise RuntimeError("Illegal mode value: {0}".format(displayMode))
        
        # generate the list entries
        for key in sorted(self.configItems.keys()):
            pageData = self.configItems[key]
            if pageData[3]:
                pitm = self.itmDict[pageData[3]]  # get the parent item
            else:
                pitm = self.configList
            self.itmDict[key] = ConfigurationPageItem(pitm, pageData[0], key,
                                                      pageData[1])
            self.itmDict[key].setExpanded(True)
        self.configList.sortByColumn(0, Qt.AscendingOrder)
        
        # set the initial size of the splitter
        self.configSplitter.setSizes([200, 600])
        
        self.configList.itemActivated.connect(self.__showConfigurationPage)
        self.configList.itemClicked.connect(self.__showConfigurationPage)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.rejected)
        
        if displayMode != ConfigurationWidget.TrayStarterMode:
            self.__initLexers()
        
    def accept(self):
        """
        Public slot to accept the buttonBox accept signal.
        """
        if not isMacPlatform():
            wdg = self.focusWidget()
            if wdg == self.configList:
                return
        
        self.accepted.emit()
        
    def __setupUi(self):
        """
        Private method to perform the general setup of the configuration
        widget.
        """
        self.setObjectName("ConfigurationDialog")
        self.resize(900, 650)
        self.verticalLayout_2 = QVBoxLayout(self)
        self.verticalLayout_2.setSpacing(6)
        self.verticalLayout_2.setContentsMargins(6, 6, 6, 6)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        
        self.configSplitter = QSplitter(self)
        self.configSplitter.setOrientation(Qt.Horizontal)
        self.configSplitter.setObjectName("configSplitter")
        
        self.configListWidget = QWidget(self.configSplitter)
        self.leftVBoxLayout = QVBoxLayout(self.configListWidget)
        self.leftVBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.leftVBoxLayout.setSpacing(0)
        self.leftVBoxLayout.setObjectName("leftVBoxLayout")
        self.configListFilter = E5ClearableLineEdit(
            self, self.tr("Enter filter text..."))
        self.configListFilter.setObjectName("configListFilter")
        self.leftVBoxLayout.addWidget(self.configListFilter)
        self.configList = QTreeWidget()
        self.configList.setObjectName("configList")
        self.leftVBoxLayout.addWidget(self.configList)
        self.configListFilter.textChanged.connect(self.__filterTextChanged)
        
        self.scrollArea = QScrollArea(self.configSplitter)
        self.scrollArea.setFrameShape(QFrame.NoFrame)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setWidgetResizable(False)
        self.scrollArea.setObjectName("scrollArea")
        
        self.configStack = QStackedWidget()
        self.configStack.setFrameShape(QFrame.Box)
        self.configStack.setFrameShadow(QFrame.Sunken)
        self.configStack.setObjectName("configStack")
        self.scrollArea.setWidget(self.configStack)
        
        self.emptyPage = QWidget()
        self.emptyPage.setGeometry(QRect(0, 0, 372, 591))
        self.emptyPage.setObjectName("emptyPage")
        self.vboxlayout = QVBoxLayout(self.emptyPage)
        self.vboxlayout.setSpacing(6)
        self.vboxlayout.setContentsMargins(6, 6, 6, 6)
        self.vboxlayout.setObjectName("vboxlayout")
        spacerItem = QSpacerItem(
            20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem)
        self.emptyPagePixmap = QLabel(self.emptyPage)
        self.emptyPagePixmap.setAlignment(Qt.AlignCenter)
        self.emptyPagePixmap.setObjectName("emptyPagePixmap")
        self.emptyPagePixmap.setPixmap(
            QPixmap(os.path.join(getConfig('ericPixDir'), 'eric.png')))
        self.vboxlayout.addWidget(self.emptyPagePixmap)
        self.textLabel1 = QLabel(self.emptyPage)
        self.textLabel1.setAlignment(Qt.AlignCenter)
        self.textLabel1.setObjectName("textLabel1")
        self.vboxlayout.addWidget(self.textLabel1)
        spacerItem1 = QSpacerItem(
            20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem1)
        self.configStack.addWidget(self.emptyPage)
        
        self.verticalLayout_2.addWidget(self.configSplitter)
        
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Apply | QDialogButtonBox.Cancel |
            QDialogButtonBox.Ok | QDialogButtonBox.Reset)
        self.buttonBox.setObjectName("buttonBox")
        if not self.fromEric and \
                self.displayMode == ConfigurationWidget.DefaultMode:
            self.buttonBox.button(QDialogButtonBox.Apply).hide()
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
        self.verticalLayout_2.addWidget(self.buttonBox)

        self.setWindowTitle(self.tr("Preferences"))
        
        self.configList.header().hide()
        self.configList.header().setSortIndicator(0, Qt.AscendingOrder)
        self.configList.setSortingEnabled(True)
        self.textLabel1.setText(
            self.tr("Please select an entry of the list \n"
                    "to display the configuration page."))
        
        QMetaObject.connectSlotsByName(self)
        self.setTabOrder(self.configList, self.configStack)
        
        self.configStack.setCurrentWidget(self.emptyPage)
        
        self.configList.setFocus()
    
    def __filterTextChanged(self, filter):
        """
        Private slot to handle a change of the filter.
        
        @param filter text of the filter line edit (string)
        """
        self.__filterChildItems(self.configList.invisibleRootItem(), filter)
    
    def __filterChildItems(self, parent, filter):
        """
        Private method to filter child items based on a filter string.
        
        @param parent reference to the parent item (QTreeWidgetItem)
        @param filter filter string (string)
        @return flag indicating a visible child item (boolean)
        """
        childVisible = False
        filter = filter.lower()
        for index in range(parent.childCount()):
            itm = parent.child(index)
            if itm.childCount() > 0:
                visible = self.__filterChildItems(itm, filter)
            else:
                visible = filter == "" or filter in itm.text(0).lower()
            if visible:
                childVisible = True
            itm.setHidden(not visible)
        
        return childVisible
    
    def __initLexers(self):
        """
        Private method to initialize the dictionary of preferences lexers.
        """
        import QScintilla.Lexers
        from .PreferencesLexer import PreferencesLexer, \
            PreferencesLexerLanguageError
        
        self.lexers = {}
        for language in QScintilla.Lexers.getSupportedLanguages():
            if language not in self.lexers:
                try:
                    self.lexers[language] = PreferencesLexer(language, self)
                except PreferencesLexerLanguageError:
                    pass
        
    def __importConfigurationPage(self, name):
        """
        Private method to import a configuration page module.
        
        @param name name of the configuration page module (string)
        @return reference to the configuration page module
        """
        modName = "Preferences.ConfigurationPages.{0}".format(name)
        try:
            mod = __import__(modName)
            components = modName.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)
            return mod
        except ImportError:
            E5MessageBox.critical(
                self,
                self.tr("Configuration Page Error"),
                self.tr("""<p>The configuration page <b>{0}</b>"""
                        """ could not be loaded.</p>""").format(name))
            return None
        
    def __showConfigurationPage(self, itm, column):
        """
        Private slot to show a selected configuration page.
        
        @param itm reference to the selected item (QTreeWidgetItem)
        @param column column that was selected (integer) (ignored)
        """
        pageName = itm.getPageName()
        self.showConfigurationPageByName(pageName, setCurrent=False)
        
    def __initPage(self, pageData):
        """
        Private method to initialize a configuration page.
        
        @param pageData data structure for the page to initialize
        @return reference to the initialized page
        """
        page = None
        if isinstance(pageData[2], types.FunctionType):
            page = pageData[2](self)
        else:
            mod = self.__importConfigurationPage(pageData[2])
            if mod:
                page = mod.create(self)
        if page is not None:
            self.configStack.addWidget(page)
            pageData[-1] = page
            try:
                page.setMode(self.displayMode)
            except AttributeError:
                pass
        return page
        
    def showConfigurationPageByName(self, pageName, setCurrent=True):
        """
        Public slot to show a named configuration page.
        
        @param pageName name of the configuration page to show (string)
        @param setCurrent flag indicating to set the current item (boolean)
        """
        if pageName == "empty":
            page = self.emptyPage
        else:
            pageData = self.configItems[pageName]
            if pageData[-1] is None and pageData[2] is not None:
                # the page was not loaded yet, create it
                page = self.__initPage(pageData)
            else:
                page = pageData[-1]
            if page is None:
                page = self.emptyPage
            elif setCurrent:
                items = self.configList.findItems(
                    pageData[0],
                    Qt.MatchFixedString | Qt.MatchRecursive)
                if items:
                    self.configList.setCurrentItem(items[0])
        self.configStack.setCurrentWidget(page)
        ssize = self.scrollArea.size()
        if self.scrollArea.horizontalScrollBar():
            ssize.setHeight(
                ssize.height() -
                self.scrollArea.horizontalScrollBar().height() - 2)
        if self.scrollArea.verticalScrollBar():
            ssize.setWidth(
                ssize.width() -
                self.scrollArea.verticalScrollBar().width() - 2)
        psize = page.minimumSizeHint()
        self.configStack.resize(max(ssize.width(), psize.width()),
                                max(ssize.height(), psize.height()))
        
        if page != self.emptyPage:
            page.polishPage()
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(True)
        else:
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
        
        # reset scrollbars
        for sb in [self.scrollArea.horizontalScrollBar(),
                   self.scrollArea.verticalScrollBar()]:
            if sb:
                sb.setValue(0)
        
        self.__currentConfigurationPageName = pageName
        
    def getConfigurationPageName(self):
        """
        Public method to get the page name of the current page.
        
        @return page name of the current page (string)
        """
        return self.__currentConfigurationPageName
        
    def calledFromEric(self):
        """
        Public method to check, if invoked from within eric.
        
        @return flag indicating invocation from within eric (boolean)
        """
        return self.fromEric
        
    def getPage(self, pageName):
        """
        Public method to get a reference to the named page.
        
        @param pageName name of the configuration page (string)
        @return reference to the page or None, indicating page was
            not loaded yet
        """
        return self.configItems[pageName][-1]
        
    def getLexers(self):
        """
        Public method to get a reference to the lexers dictionary.
        
        @return reference to the lexers dictionary
        """
        return self.lexers
        
    def setPreferences(self):
        """
        Public method called to store the selected values into the preferences
        storage.
        """
        for key, pageData in list(self.configItems.items()):
            if pageData[-1]:
                pageData[-1].save()
                # page was loaded (and possibly modified)
                QApplication.processEvents()    # ensure HMI is responsive
        
    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.buttonBox.button(QDialogButtonBox.Apply):
            self.on_applyButton_clicked()
        elif button == self.buttonBox.button(QDialogButtonBox.Reset):
            self.on_resetButton_clicked()
        
    @pyqtSlot()
    def on_applyButton_clicked(self):
        """
        Private slot called to apply the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            page = self.configStack.currentWidget()
            savedState = page.saveState()
            page.save()
            self.preferencesChanged.emit()
            if savedState is not None:
                page.setState(savedState)
        
    @pyqtSlot()
    def on_resetButton_clicked(self):
        """
        Private slot called to reset the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            currentPage = self.configStack.currentWidget()
            savedState = currentPage.saveState()
            pageName = self.configList.currentItem().getPageName()
            self.configStack.removeWidget(currentPage)
            if pageName == "editorHighlightingStylesPage":
                self.__initLexers()
            self.configItems[pageName][-1] = None
            
            self.showConfigurationPageByName(pageName)
            if savedState is not None:
                self.configStack.currentWidget().setState(savedState)
예제 #41
0
class UIPreviewer(E5MainWindow):
    """
    Class implementing the UI Previewer main window.
    """
    def __init__(self, filename=None, parent=None, name=None):
        """
        Constructor
        
        @param filename name of a UI file to load
        @param parent parent widget of this window (QWidget)
        @param name name of this window (string)
        """
        self.mainWidget = None
        self.currentFile = QDir.currentPath()
        
        super(UIPreviewer, self).__init__(parent)
        if not name:
            self.setObjectName("UIPreviewer")
        else:
            self.setObjectName(name)
        
        self.setStyle(Preferences.getUI("Style"),
                      Preferences.getUI("StyleSheet"))
        
        self.resize(QSize(600, 480).expandedTo(self.minimumSizeHint()))
        self.statusBar()
        
        self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
        self.setWindowTitle(self.tr("UI Previewer"))

        self.cw = QWidget(self)
        self.cw.setObjectName("centralWidget")
        
        self.UIPreviewerLayout = QVBoxLayout(self.cw)
        self.UIPreviewerLayout.setContentsMargins(6, 6, 6, 6)
        self.UIPreviewerLayout.setSpacing(6)
        self.UIPreviewerLayout.setObjectName("UIPreviewerLayout")

        self.styleLayout = QHBoxLayout()
        self.styleLayout.setContentsMargins(0, 0, 0, 0)
        self.styleLayout.setSpacing(6)
        self.styleLayout.setObjectName("styleLayout")

        self.styleLabel = QLabel(self.tr("Select GUI Theme"), self.cw)
        self.styleLabel.setObjectName("styleLabel")
        self.styleLayout.addWidget(self.styleLabel)

        self.styleCombo = QComboBox(self.cw)
        self.styleCombo.setObjectName("styleCombo")
        self.styleCombo.setEditable(False)
        self.styleCombo.setToolTip(self.tr("Select the GUI Theme"))
        self.styleLayout.addWidget(self.styleCombo)
        self.styleCombo.addItems(sorted(QStyleFactory().keys()))
        currentStyle = Preferences.Prefs.settings.value('UIPreviewer/style')
        if currentStyle is not None:
            self.styleCombo.setCurrentIndex(int(currentStyle))
        
        styleSpacer = QSpacerItem(
            40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.styleLayout.addItem(styleSpacer)
        self.UIPreviewerLayout.addLayout(self.styleLayout)

        self.previewSV = QScrollArea(self.cw)
        self.previewSV.setObjectName("preview")
        self.previewSV.setFrameShape(QFrame.NoFrame)
        self.previewSV.setFrameShadow(QFrame.Plain)
        self.previewSV.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.UIPreviewerLayout.addWidget(self.previewSV)

        self.setCentralWidget(self.cw)
        
        self.styleCombo.activated[str].connect(self.__guiStyleSelected)
        
        self.__initActions()
        self.__initMenus()
        self.__initToolbars()
        
        self.__updateActions()
        
        # defere loading of a UI file until we are shown
        self.fileToLoad = filename
        
    def show(self):
        """
        Public slot to show this dialog.
        
        This overloaded slot loads a UI file to be previewed after
        the main window has been shown. This way, previewing a dialog
        doesn't interfere with showing the main window.
        """
        super(UIPreviewer, self).show()
        if self.fileToLoad is not None:
            fn, self.fileToLoad = (self.fileToLoad, None)
            self.__loadFile(fn)
            
    def __initActions(self):
        """
        Private method to define the user interface actions.
        """
        self.openAct = QAction(
            UI.PixmapCache.getIcon("openUI.png"),
            self.tr('&Open File'), self)
        self.openAct.setShortcut(
            QKeySequence(self.tr("Ctrl+O", "File|Open")))
        self.openAct.setStatusTip(self.tr('Open a UI file for display'))
        self.openAct.setWhatsThis(self.tr(
            """<b>Open File</b>"""
            """<p>This opens a new UI file for display.</p>"""
        ))
        self.openAct.triggered.connect(self.__openFile)
        
        self.printAct = QAction(
            UI.PixmapCache.getIcon("print.png"),
            self.tr('&Print'), self)
        self.printAct.setShortcut(
            QKeySequence(self.tr("Ctrl+P", "File|Print")))
        self.printAct.setStatusTip(self.tr('Print a screen capture'))
        self.printAct.setWhatsThis(self.tr(
            """<b>Print</b>"""
            """<p>Print a screen capture.</p>"""
        ))
        self.printAct.triggered.connect(self.__printImage)
        
        self.printPreviewAct = QAction(
            UI.PixmapCache.getIcon("printPreview.png"),
            self.tr('Print Preview'), self)
        self.printPreviewAct.setStatusTip(self.tr(
            'Print preview a screen capture'))
        self.printPreviewAct.setWhatsThis(self.tr(
            """<b>Print Preview</b>"""
            """<p>Print preview a screen capture.</p>"""
        ))
        self.printPreviewAct.triggered.connect(self.__printPreviewImage)
        
        self.imageAct = QAction(
            UI.PixmapCache.getIcon("screenCapture.png"),
            self.tr('&Screen Capture'), self)
        self.imageAct.setShortcut(
            QKeySequence(self.tr("Ctrl+S", "File|Screen Capture")))
        self.imageAct.setStatusTip(self.tr(
            'Save a screen capture to an image file'))
        self.imageAct.setWhatsThis(self.tr(
            """<b>Screen Capture</b>"""
            """<p>Save a screen capture to an image file.</p>"""
        ))
        self.imageAct.triggered.connect(self.__saveImage)
        
        self.exitAct = QAction(
            UI.PixmapCache.getIcon("exit.png"), self.tr('&Quit'), self)
        self.exitAct.setShortcut(
            QKeySequence(self.tr("Ctrl+Q", "File|Quit")))
        self.exitAct.setStatusTip(self.tr('Quit the application'))
        self.exitAct.setWhatsThis(self.tr(
            """<b>Quit</b>"""
            """<p>Quit the application.</p>"""
        ))
        self.exitAct.triggered.connect(qApp.closeAllWindows)
        
        self.copyAct = QAction(
            UI.PixmapCache.getIcon("editCopy.png"), self.tr('&Copy'), self)
        self.copyAct.setShortcut(
            QKeySequence(self.tr("Ctrl+C", "Edit|Copy")))
        self.copyAct.setStatusTip(
            self.tr('Copy screen capture to clipboard'))
        self.copyAct.setWhatsThis(self.tr(
            """<b>Copy</b>"""
            """<p>Copy screen capture to clipboard.</p>"""
        ))
        self.copyAct.triggered.connect(self.__copyImageToClipboard)
        
        self.whatsThisAct = QAction(
            UI.PixmapCache.getIcon("whatsThis.png"),
            self.tr('&What\'s This?'), self)
        self.whatsThisAct.setShortcut(QKeySequence(self.tr("Shift+F1")))
        self.whatsThisAct.setStatusTip(self.tr('Context sensitive help'))
        self.whatsThisAct.setWhatsThis(self.tr(
            """<b>Display context sensitive help</b>"""
            """<p>In What's This? mode, the mouse cursor shows an arrow"""
            """ with a question mark, and you can click on the interface"""
            """ elements to get a short description of what they do and"""
            """ how to use them. In dialogs, this feature can be accessed"""
            """ using the context help button in the titlebar.</p>"""
        ))
        self.whatsThisAct.triggered.connect(self.__whatsThis)

        self.aboutAct = QAction(self.tr('&About'), self)
        self.aboutAct.setStatusTip(self.tr(
            'Display information about this software'))
        self.aboutAct.setWhatsThis(self.tr(
            """<b>About</b>"""
            """<p>Display some information about this software.</p>"""
        ))
        self.aboutAct.triggered.connect(self.__about)
                     
        self.aboutQtAct = QAction(self.tr('About &Qt'), self)
        self.aboutQtAct.setStatusTip(
            self.tr('Display information about the Qt toolkit'))
        self.aboutQtAct.setWhatsThis(self.tr(
            """<b>About Qt</b>"""
            """<p>Display some information about the Qt toolkit.</p>"""
        ))
        self.aboutQtAct.triggered.connect(self.__aboutQt)

    def __initMenus(self):
        """
        Private method to create the menus.
        """
        mb = self.menuBar()

        menu = mb.addMenu(self.tr('&File'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.openAct)
        menu.addAction(self.imageAct)
        menu.addSeparator()
        menu.addAction(self.printPreviewAct)
        menu.addAction(self.printAct)
        menu.addSeparator()
        menu.addAction(self.exitAct)
        
        menu = mb.addMenu(self.tr("&Edit"))
        menu.setTearOffEnabled(True)
        menu.addAction(self.copyAct)
        
        mb.addSeparator()
        
        menu = mb.addMenu(self.tr('&Help'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.aboutAct)
        menu.addAction(self.aboutQtAct)
        menu.addSeparator()
        menu.addAction(self.whatsThisAct)

    def __initToolbars(self):
        """
        Private method to create the toolbars.
        """
        filetb = self.addToolBar(self.tr("File"))
        filetb.setIconSize(UI.Config.ToolBarIconSize)
        filetb.addAction(self.openAct)
        filetb.addAction(self.imageAct)
        filetb.addSeparator()
        filetb.addAction(self.printPreviewAct)
        filetb.addAction(self.printAct)
        filetb.addSeparator()
        filetb.addAction(self.exitAct)
        
        edittb = self.addToolBar(self.tr("Edit"))
        edittb.setIconSize(UI.Config.ToolBarIconSize)
        edittb.addAction(self.copyAct)
        
        helptb = self.addToolBar(self.tr("Help"))
        helptb.setIconSize(UI.Config.ToolBarIconSize)
        helptb.addAction(self.whatsThisAct)

    def __whatsThis(self):
        """
        Private slot called in to enter Whats This mode.
        """
        QWhatsThis.enterWhatsThisMode()
        
    def __guiStyleSelected(self, selectedStyle):
        """
        Private slot to handle the selection of a GUI style.
        
        @param selectedStyle name of the selected style (string)
        """
        if self.mainWidget:
            self.__updateChildren(selectedStyle)
    
    def __about(self):
        """
        Private slot to show the about information.
        """
        E5MessageBox.about(
            self,
            self.tr("UI Previewer"),
            self.tr(
                """<h3> About UI Previewer </h3>"""
                """<p>The UI Previewer loads and displays Qt User-Interface"""
                """ files with various styles, which are selectable via a"""
                """ selection list.</p>"""
            )
        )
    
    def __aboutQt(self):
        """
        Private slot to show info about Qt.
        """
        E5MessageBox.aboutQt(self, self.tr("UI Previewer"))

    def __openFile(self):
        """
        Private slot to load a new file.
        """
        fn = E5FileDialog.getOpenFileName(
            self,
            self.tr("Select UI file"),
            self.currentFile,
            self.tr("Qt User-Interface Files (*.ui)"))
        if fn:
            self.__loadFile(fn)
        
    def __loadFile(self, fn):
        """
        Private slot to load a ui file.
        
        @param fn name of the ui file to be laoded (string)
        """
        if self.mainWidget:
            self.mainWidget.close()
            self.previewSV.takeWidget()
            del self.mainWidget
            self.mainWidget = None
            
        # load the file
        try:
            self.mainWidget = uic.loadUi(fn)
        except:
            pass
        
        if self.mainWidget:
            self.currentFile = fn
            self.__updateChildren(self.styleCombo.currentText())
            if isinstance(self.mainWidget, QDialog) or \
               isinstance(self.mainWidget, QMainWindow):
                self.mainWidget.show()
                self.mainWidget.installEventFilter(self)
            else:
                self.previewSV.setWidget(self.mainWidget)
                self.mainWidget.show()
        else:
            E5MessageBox.warning(
                self,
                self.tr("Load UI File"),
                self.tr(
                    """<p>The file <b>{0}</b> could not be loaded.</p>""")
                .format(fn))
        self.__updateActions()
    
    def __updateChildren(self, sstyle):
        """
        Private slot to change the style of the show UI.
        
        @param sstyle name of the selected style (string)
        """
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        qstyle = QStyleFactory.create(sstyle)
        self.mainWidget.setStyle(qstyle)
        
        lst = self.mainWidget.findChildren(QWidget)
        for obj in lst:
            try:
                obj.setStyle(qstyle)
            except AttributeError:
                pass
        del lst
        
        self.mainWidget.hide()
        self.mainWidget.show()
        
        self.lastQStyle = qstyle
        self.lastStyle = sstyle
        Preferences.Prefs.settings.setValue(
            'UIPreviewer/style', self.styleCombo.currentIndex())
        QApplication.restoreOverrideCursor()
    
    def __updateActions(self):
        """
        Private slot to update the actions state.
        """
        if self.mainWidget:
            self.imageAct.setEnabled(True)
            self.printAct.setEnabled(True)
            if self.printPreviewAct:
                self.printPreviewAct.setEnabled(True)
            self.copyAct.setEnabled(True)
            self.styleCombo.setEnabled(True)
        else:
            self.imageAct.setEnabled(False)
            self.printAct.setEnabled(False)
            if self.printPreviewAct:
                self.printPreviewAct.setEnabled(False)
            self.copyAct.setEnabled(False)
            self.styleCombo.setEnabled(False)

    def __handleCloseEvent(self):
        """
        Private slot to handle the close event of a viewed QMainWidget.
        """
        if self.mainWidget:
            self.mainWidget.removeEventFilter(self)
            del self.mainWidget
            self.mainWidget = None
        self.__updateActions()
    
    def eventFilter(self, obj, ev):
        """
        Public method called to filter an event.
        
        @param obj object, that generated the event (QObject)
        @param ev the event, that was generated by object (QEvent)
        @return flag indicating if event was filtered out
        """
        if obj == self.mainWidget:
            if ev.type() == QEvent.Close:
                self.__handleCloseEvent()
            return True
        else:
            if isinstance(self.mainWidget, QDialog):
                return QDialog.eventFilter(self, obj, ev)
            elif isinstance(self.mainWidget, QMainWindow):
                return QMainWindow.eventFilter(self, obj, ev)
            else:
                return False
    
    def __saveImage(self):
        """
        Private slot to handle the Save Image menu action.
        """
        if self.mainWidget is None:
            E5MessageBox.critical(
                self,
                self.tr("Save Image"),
                self.tr("""There is no UI file loaded."""))
            return
        
        defaultExt = "PNG"
        filters = ""
        formats = QImageWriter.supportedImageFormats()
        for format in formats:
            filters = "{0}*.{1} ".format(
                filters, bytes(format).decode().lower())
        filter = self.tr("Images ({0})").format(filters[:-1])
        
        fname = E5FileDialog.getSaveFileName(
            self,
            self.tr("Save Image"),
            "",
            filter)
        if not fname:
            return
            
        ext = QFileInfo(fname).suffix().upper()
        if not ext:
            ext = defaultExt
            fname.append(".{0}".format(defaultExt.lower()))
        
        if qVersion() >= "5.0.0":
            pix = self.mainWidget.grab()
        else:
            pix = QPixmap.grabWidget(self.mainWidget)
        self.__updateChildren(self.lastStyle)
        if not pix.save(fname, str(ext)):
            E5MessageBox.critical(
                self,
                self.tr("Save Image"),
                self.tr(
                    """<p>The file <b>{0}</b> could not be saved.</p>""")
                .format(fname))

    def __copyImageToClipboard(self):
        """
        Private slot to handle the Copy Image menu action.
        """
        if self.mainWidget is None:
            E5MessageBox.critical(
                self,
                self.tr("Save Image"),
                self.tr("""There is no UI file loaded."""))
            return
        
        cb = QApplication.clipboard()
        if qVersion() >= "5.0.0":
            cb.setPixmap(self.mainWidget.grab())
        else:
            cb.setPixmap(QPixmap.grabWidget(self.mainWidget))
        self.__updateChildren(self.lastStyle)
    
    def __printImage(self):
        """
        Private slot to handle the Print Image menu action.
        """
        if self.mainWidget is None:
            E5MessageBox.critical(
                self,
                self.tr("Print Image"),
                self.tr("""There is no UI file loaded."""))
            return
        
        settings = Preferences.Prefs.settings
        printer = QPrinter(QPrinter.HighResolution)
        printer.setFullPage(True)
        
        printerName = Preferences.getPrinter("UIPreviewer/printername")
        if printerName:
            printer.setPrinterName(printerName)
        printer.setPageSize(
            QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize"))))
        printer.setPageOrder(
            QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder"))))
        printer.setOrientation(QPrinter.Orientation(
            int(settings.value("UIPreviewer/orientation"))))
        printer.setColorMode(
            QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode"))))
        
        printDialog = QPrintDialog(printer, self)
        if printDialog.exec_() == QDialog.Accepted:
            self.statusBar().showMessage(self.tr("Printing the image..."))
            self.__print(printer)
            
            settings.setValue("UIPreviewer/printername", printer.printerName())
            settings.setValue("UIPreviewer/pagesize", printer.pageSize())
            settings.setValue("UIPreviewer/pageorder", printer.pageOrder())
            settings.setValue("UIPreviewer/orientation", printer.orientation())
            settings.setValue("UIPreviewer/colormode", printer.colorMode())
        
        self.statusBar().showMessage(
            self.tr("Image sent to printer..."), 2000)

    def __printPreviewImage(self):
        """
        Private slot to handle the Print Preview menu action.
        """
        from PyQt5.QtPrintSupport import QPrintPreviewDialog
        
        if self.mainWidget is None:
            E5MessageBox.critical(
                self,
                self.tr("Print Preview"),
                self.tr("""There is no UI file loaded."""))
            return
        
        settings = Preferences.Prefs.settings
        printer = QPrinter(QPrinter.HighResolution)
        printer.setFullPage(True)
        
        printerName = Preferences.getPrinter("UIPreviewer/printername")
        if printerName:
            printer.setPrinterName(printerName)
        printer.setPageSize(
            QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize"))))
        printer.setPageOrder(
            QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder"))))
        printer.setOrientation(QPrinter.Orientation(
            int(settings.value("UIPreviewer/orientation"))))
        printer.setColorMode(
            QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode"))))
        
        preview = QPrintPreviewDialog(printer, self)
        preview.paintRequested.connect(self.__print)
        preview.exec_()
        
    def __print(self, printer):
        """
        Private slot to the actual printing.
        
        @param printer reference to the printer object (QPrinter)
        """
        p = QPainter(printer)
        marginX = (printer.pageRect().x() - printer.paperRect().x()) // 2
        marginY = (printer.pageRect().y() - printer.paperRect().y()) // 2

        # double the margin on bottom of page
        if printer.orientation() == QPrinter.Portrait:
            width = printer.width() - marginX * 2
            height = printer.height() - marginY * 3
        else:
            marginX *= 2
            width = printer.width() - marginX * 2
            height = printer.height() - marginY * 2
        if qVersion() >= "5.0.0":
            img = self.mainWidget.grab().toImage()
        else:
            img = QPixmap.grabWidget(self.mainWidget).toImage()
        self.__updateChildren(self.lastStyle)
        p.drawImage(marginX, marginY,
                    img.scaled(width, height,
                               Qt.KeepAspectRatio, Qt.SmoothTransformation))
        p.end()
예제 #42
0
class ABM(VistaBase):

    #diccionario que guarda los controles que se agreguen al abm
    controles = {}

    #modelo sobre el que se hace el abm
    model = None

    #indica si es un alta o una modificacion
    tipo = "A"

    #campos a mostrar en la grilla
    camposAMostrar = None

    #condicion para filtrar la tabla
    condicion = None

    #limite de registros
    limite = 100

    #orden de busqueda
    ordenBusqueda = None

    #campo
    campoClave = None

    #campo clave autoincremental
    autoincremental = True

    #campo para el foco
    campoFoco = None

    def __init__(self, *args, **kwargs):
        VistaBase.__init__(self, *args, **kwargs)
        self.controles = {}
        self.initUi()

    @inicializar_y_capturar_excepciones
    def initUi(self, *args, **kwargs):
        self.resize(906, 584)
        nombre_tabla = self.model._meta.table_name.title(
        ) if self.model else ''
        self.setWindowTitle("ABM de {}".format(nombre_tabla))
        self.verticalLayout = QVBoxLayout(self)
        self.lblTitulo = Etiqueta(tamanio=15,
                                  texto="ABM de {}".format(nombre_tabla))
        self.verticalLayout.addWidget(self.lblTitulo)

        self.tabWidget = QTabWidget()
        self.tabLista = QWidget()
        self.gridLayout = QGridLayout(self.tabLista)

        self.lineEditBusqueda = EntradaTexto(self.tabLista,
                                             placeholderText="Busqueda")
        self.lineEditBusqueda.setObjectName("lineEditBusqueda")
        self.gridLayout.addWidget(self.lineEditBusqueda, 0, 0, 1, 1)

        self.tableView = Grilla(self.tabLista)
        self.tableView.setObjectName("tableView")
        self.tableView.enabled = True

        # extraigo los nombres de las columnas
        if self.camposAMostrar:
            self.tableView.cabeceras = [
                x.verbose_name.capitalize()
                if x.verbose_name else x.column_name.capitalize()
                for x in self.camposAMostrar
            ]
        else:
            self.tableView.cabeceras = []
        self.tableView.ArmaCabeceras()
        self.gridLayout.addWidget(self.tableView, 1, 0, 1, 1)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.BotonesAdicionales()

        self.btnAgregar = Boton(self.tabLista,
                                texto='Nuevo',
                                imagen=imagen('new.png'),
                                tamanio=QSize(32, 32),
                                tooltip='Agrega nuevo registro')
        self.btnAgregar.setObjectName("btnAgregar")
        self.horizontalLayout.addWidget(self.btnAgregar)

        self.btnEditar = Boton(self.tabLista,
                               imagen=imagen('edit.png'),
                               tamanio=QSize(32, 32),
                               tooltip='Modifica registro',
                               texto='Editar')
        self.btnEditar.setObjectName("btnEditar")
        self.horizontalLayout.addWidget(self.btnEditar)

        self.btnBorrar = Boton(self.tabLista,
                               imagen=imagen('delete.png'),
                               tamanio=QSize(32, 32),
                               tooltip='Borrar registro',
                               texto='Borrar')
        self.btnBorrar.setObjectName("btnBorrar")
        self.horizontalLayout.addWidget(self.btnBorrar)

        self.btnCerrar = Boton(self.tabLista,
                               imagen=imagen('close.png'),
                               tamanio=QSize(32, 32),
                               tooltip='Cerrar ABM',
                               texto='Cerrar')

        self.btnCerrar.setObjectName("btnCerrar")
        self.horizontalLayout.addWidget(self.btnCerrar)
        self.gridLayout.addLayout(self.horizontalLayout, 2, 0, 1, 1)

        self.tabWidget.addTab(self.tabLista, "Lista")
        self.tabDetalle = QWidget()
        self.tabWidget.addTab(self.tabDetalle, "Detalle")
        self.tabDetalle.setEnabled(False)

        self.verticalLayout.addWidget(self.tabWidget)

        self.ArmaDatos()
        self.ArmaTabla()
        self.ConectaWidgets()

    def BotonesAdicionales(self):
        pass

    def ArmaTabla(self):
        self.tableView.setRowCount(0)
        if not self.model:  #si no esta establecido el modelo no hago nada
            return

        data = self.model.select().dicts()
        if self.condicion:
            for c in self.condicion:
                data = data.where(c)

        if self.lineEditBusqueda.text():
            if self.ordenBusqueda:
                data = data.where(
                    self.ordenBusqueda.contains(self.lineEditBusqueda.text()))
            else:
                Ventanas.showAlert(
                    "Sistema",
                    "Orden no establecido y no se puede realizar la busqueda")

        data = data.limit(self.limite)
        for d in data:
            if self.camposAMostrar:
                item = [d[x.column_name] for x in self.camposAMostrar]
            else:
                item = [d[x] for x in d]
            self.tableView.AgregaItem(item)

    def ArmaDatos(self):
        self.verticalLayoutDatos = QVBoxLayout(self.tabDetalle)
        self.verticalLayoutDatos.setObjectName("verticalLayoutDatos")
        self.ArmaCarga()
        fila = 0

        self.grdBotones = QGridLayout()
        self.grdBotones.setObjectName("grdBotones")
        self.btnAceptar = Boton(self.tabDetalle,
                                texto='Guardar',
                                imagen=imagen('save.png'),
                                tamanio=QSize(32, 32),
                                tooltip="Guardar cambios")
        self.btnAceptar.setObjectName("btnAceptar")
        self.grdBotones.addWidget(self.btnAceptar, 0, 0, 1, 1)

        self.btnCancelar = Boton(self.tabDetalle,
                                 texto='Cerrar',
                                 imagen=imagen('close.png'),
                                 tamanio=QSize(32, 32),
                                 tooltip="Cerrar sin guardar")
        self.btnCancelar.setObjectName("btnCancelar")
        self.grdBotones.addWidget(self.btnCancelar, 0, 1, 1, 1)
        self.verticalLayoutDatos.addLayout(self.grdBotones)
        self.verticalLayout.addWidget(self.tabWidget)
        self.btnCancelar.clicked.connect(self.btnCancelarClicked)
        self.btnAceptar.clicked.connect(self.btnAceptarClicked)
        self.verticalLayoutDatos.addStretch(1)

    def Busqueda(self):
        self.ArmaTabla()

    def ConectaWidgets(self):
        self.lineEditBusqueda.textChanged.connect(self.Busqueda)
        self.btnCerrar.clicked.connect(self.cerrarformulario)
        self.btnBorrar.clicked.connect(self.Borrar)
        self.btnEditar.clicked.connect(self.Modifica)
        self.btnAgregar.clicked.connect(self.Agrega)

    @inicializar_y_capturar_excepciones
    def Borrar(self, *args, **kwargs):
        if not self.tableView.currentRow() != -1:
            return

        if not self.campoClave:
            Ventanas.showAlert(
                "Sistema",
                "No tenes establecido el campo clave y no podemos continuar")

        id = self.tableView.ObtenerItem(
            fila=self.tableView.currentRow(),
            col=self.campoClave.column_name.capitalize())
        data = self.model.get_by_id(id)
        data.delete_instance()
        self.ArmaTabla()

    def Modifica(self):

        self.tipo = 'M'
        if not self.tableView.currentRow() != -1:
            return

        if not self.campoClave:
            Ventanas.showAlert(
                "Sistema",
                "No tenes establecido el campo clave y no podemos continuar")

        id = self.tableView.ObtenerItem(
            fila=self.tableView.currentRow(),
            col=self.campoClave.column_name.capitalize())
        print(self.tableView.currentRow(), id)
        data = self.model.select().where(self.campoClave == id).dicts()
        self.tabDetalle.setEnabled(True)
        self.tabWidget.setCurrentIndex(1)
        self.CargaDatos(data)
        if self.campoFoco:
            self.campoFoco.setFocus()
        self.PostModifica()

    def CargaDatos(self, data=None):
        # self.tipo = 'A'
        if not data:
            return
        for d in data:
            print(d)
            for k in d:
                if k in self.controles:
                    if k == self.campoClave.column_name:
                        self.controles[k].setEnabled(False)
                    if isinstance(self.controles[k], QLineEdit):
                        if isinstance(d[k], (int, decimal.Decimal)):
                            self.controles[k].setText(str(d[k]))
                        else:
                            self.controles[k].setText(d[k])
                    elif isinstance(self.controles[k], Spinner):
                        self.controles[k].setText(d[k])
                    elif isinstance(self.controles[k], (QCheckBox, CheckBox)):
                        if EsVerdadero(d[k]) or d[k]:
                            self.controles[k].setChecked(True)
                        else:
                            self.controles[k].setChecked(False)
                    elif isinstance(self.controles[k], QComboBox):
                        if isinstance(d[k], (bytes, )):
                            if EsVerdadero(self.cursor[k]):
                                self.controles[k].setCurrentIndex(
                                    self.controles[k].findData('Si'))
                            else:
                                self.controles[k].setCurrentIndex(
                                    self.controles[k].findData('No'))
                        else:
                            self.controles[k].setCurrentIndex(
                                self.controles[k].findData(d[k]))
                    self.controles[k].setStyleSheet("background-color: white")

    def ArmaEntrada(self,
                    nombre="",
                    boxlayout=None,
                    texto='',
                    *args,
                    **kwargs):
        if not nombre:
            return
        if not boxlayout:
            boxlayout = QHBoxLayout()
            lAgrega = True
        else:
            lAgrega = False

        if not texto:
            if isinstance(nombre, str):
                texto = nombre.capitalize()
            else:
                texto = nombre.verbose_name if nombre.verbose_name else nombre.name.capitalize(
                )

        if not isinstance(
                nombre, str
        ):  #si no es un campo texto intento convertir de un campo de pewee
            nombre = nombre.name

        labelNombre = Etiqueta(texto=texto)
        labelNombre.setObjectName("labelNombre")
        boxlayout.addWidget(labelNombre)

        if 'control' in kwargs:
            lineEditNombre = kwargs['control']
        else:
            lineEditNombre = EntradaTexto()

        if 'relleno' in kwargs:
            lineEditNombre.relleno = kwargs['relleno']

        if 'inputmask' in kwargs:
            lineEditNombre.setInputMask(kwargs['inputmask'])

        #print(type(lineEditNombre))
        lineEditNombre.setObjectName(nombre)
        boxlayout.addWidget(lineEditNombre)
        if 'enabled' in kwargs:
            lineEditNombre.setEnabled(kwargs['enabled'])

        self.controles[nombre] = lineEditNombre

        if lAgrega:
            self.verticalLayoutDatos.addLayout(boxlayout)
        return boxlayout

    def btnCancelarClicked(self):
        self.tabWidget.setCurrentIndex(0)
        self.tabDetalle.setEnabled(False)

    @inicializar_y_capturar_excepciones
    def btnAceptarClicked(self, *args, **kwargs):
        # data = self.model.get_by_id(self.controles[self.campoClave.column_name].text())
        # data.nombre = self.controles['nombre'].text()
        self.ArmaTabla()
        self.btnCancelarClicked()

    def ArmaCarga(self):
        pass

    def Agrega(self):
        self.tipo = 'A'
        for x in self.controles:
            if self.autoincremental:
                if x == self.campoClave.column_name:
                    self.controles[x].setEnabled(False)
            self.controles[x].setText('')
            self.controles[x].setStyleSheet("background-color: white")
        self.tabDetalle.setEnabled(True)
        self.tabWidget.setCurrentIndex(1)
        if self.campoFoco:
            self.campoFoco.setFocus()
        self.PostAgrega()

    def PostModifica(self):
        pass

    def PostAgrega(self):
        pass
예제 #43
0
파일: ui_tip.py 프로젝트: 892768447/ucics
class Ui_Tip(object):
    def setupUi(self, Tip, name = "", head = "", mood = "", pic1 = "", pic2 = "", pic3 = ""):
        Tip.setObjectName("Tip")
        Tip.resize(275, 180)
        size = QSize(275, 180)
        Tip.setMinimumSize(size)
        Tip.setMaximumSize(size)
        Tip.setWindowTitle("")
        self.name = name
        self.head = head
        self.mood = mood
        self.pic1 = pic1
        self.pic2 = pic2
        self.pic3 = pic3

        self.mainWidget = QWidget(Tip)
        self.mainWidget.setObjectName("tip")

        self.verticalLayout = QVBoxLayout(self.mainWidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.widget = QWidget(self.mainWidget)
        self.widget.setObjectName("widget")
        self.widget.setMinimumHeight(80)
        self.widget.setMaximumHeight(80)

        self.horizontalLayout_2 = QHBoxLayout(self.widget)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.itemHeadLabel = QLabel(self.widget)
        self.itemHeadLabel.setMinimumSize(QSize(80, 80))
        self.itemHeadLabel.setMaximumSize(QSize(80, 80))
        self.itemHeadLabel.setOpenExternalLinks(True)
        self.itemHeadLabel.setObjectName("itemHeadLabel")
        self.horizontalLayout_2.addWidget(self.itemHeadLabel)
        self.widget_3 = QWidget(self.widget)

        self.verticalLayout_2 = QVBoxLayout(self.widget_3)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.itemNameLabel = QLabel(self.widget_3)

        # self.itemNameLabel.setOpenExternalLinks(True)
        self.itemNameLabel.setObjectName("itemNameLabel")
        self.verticalLayout_2.addWidget(self.itemNameLabel)
        self.itemMoodLabel = QLabel(self.widget_3)

        # self.itemMoodLabel.setOpenExternalLinks(True)
        self.itemMoodLabel.setObjectName("itemMoodLabel")
        self.verticalLayout_2.addWidget(self.itemMoodLabel)
        self.horizontalLayout_2.addWidget(self.widget_3)
        self.verticalLayout.addWidget(self.widget)
        self.widget_2 = QWidget(self.mainWidget)
        self.widget_2.setMinimumSize(QSize(0, 80))
        self.widget_2.setMaximumSize(QSize(16777215, 80))
        self.widget_2.setObjectName("widget_2")
        self.horizontalLayout = QHBoxLayout(self.widget_2)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.itemPicLabel_1 = QLabel(self.widget_2)
        self.itemPicLabel_1.setObjectName("itemPicLabel_1")
        self.horizontalLayout.addWidget(self.itemPicLabel_1)
        self.itemPicLabel_2 = QLabel(self.widget_2)
        self.itemPicLabel_2.setObjectName("itemPicLabel_2")
        self.horizontalLayout.addWidget(self.itemPicLabel_2)
        self.itemPicLabel_3 = QLabel(self.widget_2)
        self.itemPicLabel_3.setObjectName("itemPicLabel_3")
        self.horizontalLayout.addWidget(self.itemPicLabel_3)
        self.verticalLayout.addWidget(self.widget_2)

        self.mainWidget.setLayout(self.verticalLayout)

        self.retranslateUi(self.mainWidget)
        QMetaObject.connectSlotsByName(Tip)

    def retranslateUi(self, Tip):
        _translate = QCoreApplication.translate
        if self.head:
            self.itemHeadLabel.setStyleSheet("QLabel#itemHeadLabel {\n    image: url(%s);\n}" % self.head)
        self.itemHeadLabel.setToolTip(_translate("Tip", "进入空间"))
        if self.name:
            self.itemNameLabel.setToolTip(_translate("Tip", "%s 点击查看详细资料" % self.name))
            self.itemNameLabel.setText(_translate("Tip", "<html><head/><body><p><a href=\"http://www.baidu.com\"><span style=\"color: black;text-decoration: none;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;\">%s</span></a></p></body></html>" % self.name))
        self.itemMoodLabel.setToolTip(_translate("Tip", "点击查看心情"))
        self.itemMoodLabel.setText(_translate("Tip", "<html><head/><body><p><a href=\"http://www.baidu.com\"><span style=\"color: black;text-decoration: none;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;\">%s</span></a></p></body></html>" % self.mood if self.mood else "这个家伙太懒!什么都没说..."))
예제 #44
0
class ddh(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # Создание главного окна
        x = (QDesktopWidget().screenGeometry().width() -
             QDesktopWidget().screenGeometry().width() // 2) // 2
        y = (QDesktopWidget().screenGeometry().height() -
             QDesktopWidget().screenGeometry().height() // 2) // 2
        self.setGeometry(x, y,
                         QDesktopWidget().screenGeometry().width() / 2,
                         QDesktopWidget().screenGeometry().height() / 2)
        self.setObjectName('main_window')
        self.setWindowTitle('DDH')
        self.setStyleSheet('background: #fafafa;')

        # Создание виджета главного окна
        self.main_window_widget = QWidget(self)
        self.main_window_widget.setObjectName('main_window_widget')
        self.main_window_widget.setStyleSheet('background: #fafafa;')

        # Создание сетки главного окна
        self.main_window_grid = QGridLayout(self.main_window_widget)
        self.main_window_grid.setObjectName('main_window_grid')

        # Создание виджета для кнопок
        self.btn_widget = QWidget(self.main_window_widget)
        self.btn_widget.setObjectName('btn_widget')
        self.btn_widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.btn_widget.setMinimumSize(QtCore.QSize(300, 270))
        self.btn_widget.setMaximumSize(QtCore.QSize(300, 270))

        # Создание блока кнопок
        self.btn_block = QVBoxLayout(self.btn_widget)
        self.btn_block.setObjectName('btn_block')
        self.btn_block.setContentsMargins(50, 25, 50, 25)
        self.btn_block.setSpacing(35)

        # Создание кнопок для редактирования json файла
        btn_create_info = (('add', 'добавить', self.add_func),
                           ('change', 'изменить', self.change_func),
                           ('del', 'удалить', self.del_func),
                           ('exp', 'экспортировать', self.exp_func))

        for obj_name, name, btn_func in btn_create_info:
            self.btn = QPushButton(self.btn_widget)
            self.btn.setObjectName('btn_' + obj_name)
            self.btn.setText(name.upper())
            self.btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            self.btn.setMinimumSize(QtCore.QSize(200, 50))
            self.btn_block.addWidget(self.btn)
            self.btn.clicked.connect(btn_func)
            self.btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
            self.btn.setStyleSheet(
                'QPushButton {background: #212121; color: #fafafa;'
                'font-family: Arial Black; font-size: 10px;'
                'border: none;}'
                'QPushButton:hover {background: #383838;}')

        # Добавление сеток друг в друга
        self.main_window_grid.addWidget(self.btn_widget, 1, 1, 1, 1)
        self.setCentralWidget(self.main_window_widget)

    # Добавление функции в json файл
    def add_func(self):
        ans1, ok_pressed1 = QInputDialog.getText(self, 'Добавить функцию',
                                                 'Введите название функции')
        ans2, ok_pressed2, wrong_value = '', False, False

        try:
            ans2, ok_pressed2 = QInputDialog.getText(
                self, 'Добавить функцию', 'Введите количество аргументов')

            if ans2.isalpha() or int(ans2) < 0:
                QMessageBox.information(self, 'Ошибка', 'Неверное значение!')
                wrong_value = True

        except Exception:
            pass

        if ok_pressed1 and ok_pressed2 and not wrong_value and ans2 != '':
            self.dialog = func_window(ans1, int(ans2))
            self.dialog.show()

    # Изменение существующей функции из json файла
    def change_func(self):
        ans, ok_pressed = QInputDialog.getText(self, 'Изменить функцию',
                                               'Введите название функции')

        try:
            with open('base.json', 'r', encoding='utf-8') as file:
                base = json.load(file)

                if not ans in base:
                    QMessageBox.information(self, 'Ошибка',
                                            'Функция не найдена!')
                    base = {}
        except Exception:
            base = {}

        if ok_pressed and ans in base:
            self.dialog = func_window(ans)
            self.dialog.show()

    # Удаление функции из json файла
    def del_func(self):
        ans, ok_pressed = QInputDialog(self).getText(
            self, 'Удалить функцию', 'Введите название функции')

        try:
            with open('base.json', 'r', encoding='utf-8') as file:
                base = json.load(file)
                if ok_pressed:
                    del base[ans]

            with open('base.json', 'w+', encoding='utf-8') as file:
                json.dump(base, file)

            del_result_text = ('Удалено', 'Функция успешно удалена')

        except Exception:
            del_result_text = ('Ошибка', 'Функция не найдена')

        if ans != '':
            QMessageBox.information(self, *del_result_text)

    # Выбор формата для экспорта json файла
    def exp_func(self):
        exp_format, ok_pressed = QInputDialog.getItem(
            self, 'Экспортировать', 'Выберите формат экспорта',
            ('html', 'docx'), 0, False)

        if ok_pressed:
            try:
                with open('base.json', 'r', encoding='utf-8') as file:
                    base = json.load(file)
            except Exception:
                base = {}

            if exp_format == 'html':
                html_file = '''<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta charset="utf-8"><title>DDH</title><style type="text/css">@import url('https://fonts.googleapis.com/css?family=montserrat:300,400,500,600');html,body{font-family:'montserrat',sans-serif;overflow-x:hidden;width:100%;padding:0;margin:0;-webkit-transition:all 0.3s ease;-moz-transition:all 0.3s ease;-o-transition:all 0.3s ease;transition:all 0.3s ease}header,main,footer,section,nav,ul,li{display:block;padding:0;margin:0;z-index:1}h1,h2,h3,h4,h5,h6,p,i,b,a,textarea,input,button{text-decoration:none;outline:0;padding:0;margin:0}a:hover,textarea:hover,input:hover,button:hover{text-decoration:none}textarea:focus,input:focus,button:focus{outline:0}.close-search-overlay{position:fixed;top:0;right:0;left:0;bottom:0;width:100vw;height:100vh}.search-overlay{display:flex;flex-direction:column;justify-content:center;align-items:center;overflow-y:hidden;-webkit-transition:all 0.3s ease;-moz-transition:all 0.3s ease;-o-transition:all 0.3s ease;transition:all 0.3s ease;background:#000;position:fixed;top:0;right:0;left:0;bottom:0;width:100vw;height:100vh;color:#fff;z-index:2;opacity:0.85}.search-error-p{-webkit-transition:all 0.3s ease;-moz-transition:all 0.3s ease;-o-transition:all 0.3s ease;transition:all 0.3s ease;opacity:0;z-index:-1}.search-overlay__element{display:flex;flex-direction:column;justify-content:center;align-items:center;margin:0 0 77.5px 0}.search-overlay input{border:none;background:transparent;border-bottom:2px solid #000;color:#fff;font-size:27.5px;font-weight:300}.search-overlay p{color:#fff;font-size:50px;font-weight:300;margin:0 0 50px 0}.search{display:flex;justify-content:flex-end;align-items:center;margin:0 70px 0 0;height:100px;opacity:0}.open-search-overlay{-webkit-transition:all 0.5s ease;-moz-transition:all 0.5s ease;-o-transition:all 0.5s ease;transition:all 0.5s ease}.open-search-overlay:hover{opacity:0.5}.open-search-overlay img{width:40px}.func{display:flex;flex-direction:column;justify-content:center;align-items:center;margin:35px}.func-name h2{text-align:center;font-weight:400;font-size:35px}.func h3{font-weight:500;font-size:22.5px}.func h4{color:#5a5a5a;font-weight:600;text-align:center;font-size:17.5px}.func h5{color:#5a5a5a;font-weight:600;font-size:17.5px}.func-p{font-weight:300;font-size:17.5px}.arg-p{color:#5a5a5a;font-weight:400;font-size:15px;margin:0 0 0 15px}.description,.syntax,.return-value{width:1000px;margin:0 0 15px 0}.args{width:1000px;margin:0 0 5px 0}@media (max-width:1100px){.description,.syntax,.args,.return-value{width:90%}}.func__element{margin:5px 0 5px 15px}.arg{margin:15px 50px}@media (max-width:750px){.arg{margin:15px 0}}</style></head><body><nav class="search"><a href="#" class="open-search-overlay"><img src="search.png"></a></nav><main class="main"><div class="main__element"><div class="func-name"><h2></h2></div><div class="func"><div class="description"></div><div class="syntax"></div><div class="args"></div><div class="return-value"></div></div></div></main><div class="search-overlay"><div class="search-overlay__element"><p class="search-error-p">Функция не найдена!</p><input id="search-form" type="text" name="func-search" placeholder="Введите имя_функции()"></div></div><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script><script type="text/javascript">base=place-to-paste-json-file;contentonPage=false;$(document).ready(()=>{$('#search-form')[0].focus();});$(document).keyup((e)=>{$('.search-error-p').css('opacity', '0');$('.search-error-p').css('z-index', '-1');if(e.which==13){for(func_name in base){if(func_name==$('#search-form')[0].value){$('.search-overlay').css('opacity', '0');$('.search-overlay').css('z-index', '-1');func_info(base[func_name], func_name);$('.search').css('opacity', '1');contentonPage = true;break}else{$('.search-error-p').css('opacity', '1');$('.search-error-p').css('z-index', '2');};};$('#search-form')[0].value = '';};});$('.open-search-overlay').click(()=>{$('.search-overlay').css('opacity', '0.85');$('.search-overlay').css('z-index', '2');$('.search-error-p').css('opacity', '0');$('.search-error-p').css('z-index', '-1');$('#search-form')[0].focus();});$('.search-overlay').click(()=>{if (contentonPage == true){$('.search-overlay').css('opacity', '0');$('.search-overlay').css('z-index', '-1');};});function func_info(func_info, func_name){if(func_name!=''){$('.func-name')[0].innerHTML='<h2>'+func_name+'</h2>';};if(func_info['description']!=''){$('.description')[0].innerHTML='<h3>Описание</h3><p class="func__element func-p">'+func_info['description']+'</p>';};if(func_info['syntax']!=''){$('.syntax')[0].innerHTML='<h3>Синтаксис</h3><p class="func__element func-p">'+func_info['syntax']+'</p>';};if(func_info['args']!={}){$('.args')[0].innerHTML='<h3>Аргументы</h3><div class="func__element func_args"></div>';};if (func_info['return_value']!=''){$('.return-value')[0].innerHTML='<h3>Возвращаемое значение</h3><p class="func__element func-p func_return-value">'+func_info['return_value']+'</p>';};args_info='';for (arg in func_info['args']){arg_info='<div class="arg">';arg_info+='<div class="arg__name"><h4>'+arg+'</h4></div>';arg_info+='<div class="arg__description"><h5>Описание</h5><p class="arg-p">'+func_info['args'][arg]['description']+'</p></div>';arg_info+='<div class="arg__type"><h5>Тип</h5><p class="arg-p">'+func_info['args'][arg]['type']+'</p></div>';arg_info+='<div class="arg__default-value"><h5>Значение по умолчанию</h5><p class="arg-p">'+func_info['args'][arg]['default_value']+'</p></div>';arg_info+='<div class="arg__addition"><h5>Примечание</h5><p class="arg-p">'+func_info['args'][arg]['addition']+'</p></div></div>';args_info+=arg_info;};$('.func_args')[0].innerHTML = args_info;};</script></body></html>'''\
                    .replace('place-to-paste-json-file', str(base))
                # Содержимое итогового html файла

                with open('ddh.html', 'w+', encoding='utf-8') as file:
                    file.write(html_file)

            elif exp_format == 'docx':
                # Создание документа
                doc = Document()

                # Стили документа
                styles = doc.styles

                # Изменение шрифта для заглавия
                style = styles.add_style('Big_size', WD_STYLE_TYPE.CHARACTER)
                big = doc.styles['Big_size']
                big_font = big.font
                big_font.name = 'Arial'
                big_font.size = Pt(24)

                # Изменение шрифта постепенно
                normal = doc.styles['Normal']
                font = normal.font
                font.name = 'Arial'
                font.size = Pt(16)
                style2 = styles.add_style('Citation', WD_STYLE_TYPE.PARAGRAPH)
                small = doc.styles['Citation']
                small_font = small.font
                small_font.name = 'Arial'
                small_font.size = Pt(14)
                style1 = styles.add_style('Smallest_small',
                                          WD_STYLE_TYPE.PARAGRAPH)
                smallest = doc.styles['Smallest_small']
                smallest_font = smallest.font
                smallest_font.name = 'Arial'
                smallest_font.size = Pt(12)

                # Добавление заглавия
                run = doc.add_paragraph()
                paragraph_format = run.paragraph_format
                paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
                run.add_run('Справка по функциям',
                            style='Big_size').bold = True

                # Списки функций, их аргументов и других элементов
                functions = []
                for i in base:
                    functions.append(i)
                elementals = []
                for i in functions:
                    for j in base[i]:
                        elementals.append(base[i][j])
                args = []
                for i in functions:
                    i = base[i]['args'].keys()
                    a = []
                    for j in i:
                        a.append(j)
                        if len(a) != 0:
                            args.append(a)

                elementals_args = []
                for i in functions:
                    for j in base[i]['args']:
                        for g in base[i]['args'][j]:
                            elementals_args.append(base[i]['args'][j][g])

                for k in range(len(functions)):
                    p = doc.add_paragraph()
                    p.add_run(functions[k]).bold = True
                    for key in base[functions[k]]:
                        if key == 'description':
                            p1 = doc.add_paragraph('Описание функции:',
                                                   style='Citation')
                        if key == 'syntax':
                            p1 = doc.add_paragraph('Синтакс функции:',
                                                   style='Citation')
                        if key == 'return_value':
                            p1 = doc.add_paragraph(
                                'Возвращаемое значение функции:',
                                style='Citation')
                        if key == 'args' and len(
                                base[functions[k]]['args']) != 0:
                            p1 = doc.add_paragraph('Аргументы функции:',
                                                   style='Citation')
                        paragraph_format1 = p1.paragraph_format
                        for value1 in range(len(elementals)):
                            if key == 'description' and value1 == 0:
                                p2 = doc.add_paragraph(elementals[value1],
                                                       style='Citation')
                            if key == 'syntax' and value1 == 1:
                                p2 = doc.add_paragraph(elementals[value1],
                                                       style='Citation')
                            if key == 'return_value' and value1 == 3:
                                p2 = doc.add_paragraph(elementals[value1],
                                                       style='Citation')
                        paragraph_format1.first_line_indent = Inches(0.25)
                        paragraph_format2 = p2.paragraph_format
                        paragraph_format2.first_line_indent = Inches(0.50)
                        if key == 'args' and len(
                                base[functions[k]]['args']) != 0:
                            for l in range(len(args[k])):
                                p3 = doc.add_paragraph(args[k][l] + ':',
                                                       style='Citation')
                                paragraph_format3 = p3.paragraph_format
                                paragraph_format3.first_line_indent = Inches(
                                    0.50)
                                for f in base[functions[k]]['args'][args[k]
                                                                    [l]]:
                                    for value2 in range(len(elementals_args)):
                                        if f == 'description' and value2 == 0:
                                            p4 = doc.add_paragraph(
                                                'Описане аргумента:',
                                                style='Smallest_small')
                                            p5 = doc.add_paragraph(
                                                elementals_args[value2],
                                                style='Smallest_small')
                                        if f == 'type' and value2 == 1:
                                            p4 = doc.add_paragraph(
                                                'Тип аргумента:',
                                                style='Smallest_small')
                                            p5 = doc.add_paragraph(
                                                elementals_args[value2],
                                                style='Smallest_small')
                                        if f == 'default_value' and value2 == 2:
                                            p4 = doc.add_paragraph(
                                                'Начальное значение аргумента:',
                                                style='Smallest_small')
                                            p5 = doc.add_paragraph(
                                                elementals_args[value2],
                                                style='Smallest_small')
                                        if f == 'addition' and value2 == 3:
                                            p4 = doc.add_paragraph(
                                                'Примичание:',
                                                style='Smallest_small')
                                            p5 = doc.add_paragraph(
                                                elementals_args[value2],
                                                style='Smallest_small')
                                        paragraph_format5 = p5.paragraph_format
                                        paragraph_format5.first_line_indent = Inches(
                                            1.0)
                                        paragraph_format4 = p4.paragraph_format
                                        paragraph_format4.first_line_indent = Inches(
                                            0.75)
                                elementals_args = elementals_args[4:]
                    elementals = elementals[4:]
                    p6 = doc.add_paragraph()
                doc.add_page_break()
                doc.save('ddh.docx')
class PyRegExpWizardCharactersDialog(
        QDialog, Ui_PyRegExpWizardCharactersDialog):
    """
    Class implementing a dialog for entering character classes.
    """
    specialChars = {
        4: "\\a",
        5: "\\f",
        6: "\\n",
        7: "\\r",
        8: "\\t",
        9: "\\v"
    }
    
    predefinedClasses = ["\\s", "\\S", "\\w", "\\W", "\\d", "\\D"]
    
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent parent widget (QWidget)
        """
        super(PyRegExpWizardCharactersDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.comboItems = []
        self.singleComboItems = []      # these are in addition to the above
        self.comboItems.append(self.tr("Normal character"))
        self.comboItems.append(
            self.tr("Unicode character in hexadecimal notation"))
        self.comboItems.append(
            self.tr("Unicode character in octal notation"))
        self.singleComboItems.append(self.tr("---"))
        self.singleComboItems.append(self.tr("Bell character (\\a)"))
        self.singleComboItems.append(self.tr("Page break (\\f)"))
        self.singleComboItems.append(self.tr("Line feed (\\n)"))
        self.singleComboItems.append(self.tr("Carriage return (\\r)"))
        self.singleComboItems.append(self.tr("Horizontal tabulator (\\t)"))
        self.singleComboItems.append(self.tr("Vertical tabulator (\\v)"))
        
        self.charValidator = QRegExpValidator(QRegExp(".{0,1}"), self)
        self.hexValidator = QRegExpValidator(QRegExp("[0-9a-fA-F]{0,4}"), self)
        self.octValidator = QRegExpValidator(QRegExp("[0-3]?[0-7]{0,2}"), self)
        
        # generate dialog part for single characters
        self.singlesBoxLayout = QVBoxLayout(self.singlesBox)
        self.singlesBoxLayout.setObjectName("singlesBoxLayout")
        self.singlesBoxLayout.setSpacing(6)
        self.singlesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesBox.setLayout(self.singlesBoxLayout)
        self.singlesView = QScrollArea(self.singlesBox)
        self.singlesView.setObjectName("singlesView")
        self.singlesBoxLayout.addWidget(self.singlesView)
        
        self.singlesItemsBox = QWidget(self)
        self.singlesView.setWidget(self.singlesItemsBox)
        self.singlesItemsBox.setObjectName("singlesItemsBox")
        self.singlesItemsBoxLayout = QVBoxLayout(self.singlesItemsBox)
        self.singlesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesItemsBoxLayout.setSpacing(6)
        self.singlesItemsBox.setLayout(self.singlesItemsBoxLayout)
        self.singlesEntries = []
        self.__addSinglesLine()
        
        hlayout0 = QHBoxLayout()
        hlayout0.setContentsMargins(0, 0, 0, 0)
        hlayout0.setSpacing(6)
        hlayout0.setObjectName("hlayout0")
        self.moreSinglesButton = QPushButton(
            self.tr("Additional Entries"), self.singlesBox)
        self.moreSinglesButton.setObjectName("moreSinglesButton")
        hlayout0.addWidget(self.moreSinglesButton)
        hspacer0 = QSpacerItem(
            30, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        hlayout0.addItem(hspacer0)
        self.singlesBoxLayout.addLayout(hlayout0)
        self.moreSinglesButton.clicked.connect(self.__addSinglesLine)
        
        # generate dialog part for character ranges
        self.rangesBoxLayout = QVBoxLayout(self.rangesBox)
        self.rangesBoxLayout.setObjectName("rangesBoxLayout")
        self.rangesBoxLayout.setSpacing(6)
        self.rangesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesBox.setLayout(self.rangesBoxLayout)
        self.rangesView = QScrollArea(self.rangesBox)
        self.rangesView.setObjectName("rangesView")
        self.rangesBoxLayout.addWidget(self.rangesView)
        
        self.rangesItemsBox = QWidget(self)
        self.rangesView.setWidget(self.rangesItemsBox)
        self.rangesItemsBox.setObjectName("rangesItemsBox")
        self.rangesItemsBoxLayout = QVBoxLayout(self.rangesItemsBox)
        self.rangesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesItemsBoxLayout.setSpacing(6)
        self.rangesItemsBox.setLayout(self.rangesItemsBoxLayout)
        self.rangesEntries = []
        self.__addRangesLine()
        
        hlayout1 = QHBoxLayout()
        hlayout1.setContentsMargins(0, 0, 0, 0)
        hlayout1.setSpacing(6)
        hlayout1.setObjectName("hlayout1")
        self.moreRangesButton = QPushButton(
            self.tr("Additional Entries"), self.rangesBox)
        self.moreSinglesButton.setObjectName("moreRangesButton")
        hlayout1.addWidget(self.moreRangesButton)
        hspacer1 = QSpacerItem(
            30, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        hlayout1.addItem(hspacer1)
        self.rangesBoxLayout.addLayout(hlayout1)
        self.moreRangesButton.clicked.connect(self.__addRangesLine)
        
    def __addSinglesLine(self):
        """
        Private slot to add a line of entry widgets for single characters.
        """
        hbox = QWidget(self.singlesItemsBox)
        hboxLayout = QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(6)
        hbox.setLayout(hboxLayout)
        cb1 = QComboBox(hbox)
        cb1.setEditable(False)
        cb1.addItems(self.comboItems)
        cb1.addItems(self.singleComboItems)
        hboxLayout.addWidget(cb1)
        le1 = QLineEdit(hbox)
        le1.setValidator(self.charValidator)
        hboxLayout.addWidget(le1)
        cb2 = QComboBox(hbox)
        cb2.setEditable(False)
        cb2.addItems(self.comboItems)
        cb2.addItems(self.singleComboItems)
        hboxLayout.addWidget(cb2)
        le2 = QLineEdit(hbox)
        le2.setValidator(self.charValidator)
        hboxLayout.addWidget(le2)
        self.singlesItemsBoxLayout.addWidget(hbox)
        
        cb1.activated[int].connect(self.__singlesCharTypeSelected)
        cb2.activated[int].connect(self.__singlesCharTypeSelected)
        hbox.show()
        
        self.singlesItemsBox.adjustSize()
        
        self.singlesEntries.append([cb1, le1])
        self.singlesEntries.append([cb2, le2])
        
    def __addRangesLine(self):
        """
        Private slot to add a line of entry widgets for character ranges.
        """
        hbox = QWidget(self.rangesItemsBox)
        hboxLayout = QHBoxLayout(hbox)
        hboxLayout.setContentsMargins(0, 0, 0, 0)
        hboxLayout.setSpacing(6)
        hbox.setLayout(hboxLayout)
        cb1 = QComboBox(hbox)
        cb1.setEditable(False)
        cb1.addItems(self.comboItems)
        hboxLayout.addWidget(cb1)
        l1 = QLabel(self.tr("Between:"), hbox)
        hboxLayout.addWidget(l1)
        le1 = QLineEdit(hbox)
        le1.setValidator(self.charValidator)
        hboxLayout.addWidget(le1)
        l2 = QLabel(self.tr("And:"), hbox)
        hboxLayout.addWidget(l2)
        le2 = QLineEdit(hbox)
        le2.setValidator(self.charValidator)
        hboxLayout.addWidget(le2)
        self.rangesItemsBoxLayout.addWidget(hbox)
        
        cb1.activated[int].connect(self.__rangesCharTypeSelected)
        
        hbox.show()
        
        self.rangesItemsBox.adjustSize()
        
        self.rangesEntries.append([cb1, le1, le2])
        
    def __performSelectedAction(self, index, lineedit):
        """
        Private method performing some actions depending on the input.
        
        @param index selected list index (integer)
        @param lineedit line edit widget to act on (QLineEdit)
        """
        if index < 3:
            lineedit.setEnabled(True)
            if index == 0:
                lineedit.setValidator(self.charValidator)
            elif index == 1:
                lineedit.setValidator(self.hexValidator)
            elif index == 2:
                lineedit.setValidator(self.octValidator)
        elif index > 3:
            lineedit.setEnabled(False)
        lineedit.clear()
        
    def __singlesCharTypeSelected(self, index):
        """
        Private slot to handle the activated(int) signal of the single chars
        combo boxes.
        
        @param index selected list index (integer)
        """
        combo = self.sender()
        for entriesList in self.singlesEntries:
            if combo == entriesList[0]:
                self.__performSelectedAction(index, entriesList[1])
                break
        
    def __rangesCharTypeSelected(self, index):
        """
        Private slot to handle the activated(int) signal of the char ranges
        combo boxes.
        
        @param index selected list index (integer)
        """
        combo = self.sender()
        for entriesList in self.rangesEntries:
            if combo == entriesList[0]:
                self.__performSelectedAction(index, entriesList[1])
                self.__performSelectedAction(index, entriesList[2])
                break
        
    def __formatCharacter(self, index, char):
        """
        Private method to format the characters entered into the dialog.
        
        @param index selected list index (integer)
        @param char character string enetered into the dialog (string)
        @return formated character string (string)
        """
        if index == 0:
            return char
        elif index == 1:
            return "\\x{0}".format(char.lower())
        elif index == 2:
            return "\\0{0}".format(char)
        else:
            try:
                return self.specialChars[index]
            except KeyError:
                return ""
        
    def getCharacters(self):
        """
        Public method to return the character string assembled via the dialog.
        
        @return formatted string for character classes (string)
        """
        regexp = ""
        
        # negative character range
        if self.negativeCheckBox.isChecked():
            regexp += "^"
            
        # predefined character ranges
        if self.wordCharCheckBox.isChecked():
            regexp += "\\w"
        if self.nonWordCharCheckBox.isChecked():
            regexp += "\\W"
        if self.digitsCheckBox.isChecked():
            regexp += "\\d"
        if self.nonDigitsCheckBox.isChecked():
            regexp += "\\D"
        if self.whitespaceCheckBox.isChecked():
            regexp += "\\s"
        if self.nonWhitespaceCheckBox.isChecked():
            regexp += "\\S"
            
        # single characters
        for entrieslist in self.singlesEntries:
            index = entrieslist[0].currentIndex()
            char = entrieslist[1].text()
            regexp += self.__formatCharacter(index, char)
        
        # character ranges
        for entrieslist in self.rangesEntries:
            if entrieslist[1].text() == "" or \
               entrieslist[2].text() == "":
                continue
            index = entrieslist[0].currentIndex()
            char1 = entrieslist[1].text()
            char2 = entrieslist[2].text()
            regexp += "{0}-{1}".format(
                self.__formatCharacter(index, char1),
                self.__formatCharacter(index, char2))
        
        if regexp:
            if (len(regexp) == 2 and
                (regexp in self.predefinedClasses or
                 regexp in self.specialChars)) or \
               len(regexp) == 1:
                return regexp
            else:
                return "[{0}]".format(regexp)
        else:
            return ""
예제 #46
0
class func_window(QMainWindow):
    def __init__(self, func_name_str, arg_amount=-1):
        super().__init__()
        self.arg_amount, self.func_name_str, self.args_info_form = \
            arg_amount, func_name_str, []
        self.is_change_func = True if arg_amount == -1 else False
        self.setupUi()

    def setupUi(self):
        # Параметры окна
        self.setObjectName('func_window')
        x = (QDesktopWidget().screenGeometry().width() -
             QDesktopWidget().screenGeometry().width() // 2) // 2
        y = (QDesktopWidget().screenGeometry().height() -
             QDesktopWidget().screenGeometry().height() // 2) // 2
        self.setGeometry(x, y,
                         QDesktopWidget().screenGeometry().width() / 2,
                         QDesktopWidget().screenGeometry().height() / 2)
        self.setWindowTitle(self.func_name_str)
        self.setStyleSheet('background: #fafafa;')

        # Виджет окна
        self.func_window_grid = QWidget(self)
        self.func_window_grid.setObjectName('func_window_grid')

        # Основная сетка окна
        self.vertical_layout_1 = QVBoxLayout(self.func_window_grid)
        self.vertical_layout_1.setObjectName('vertical_layout_1')

        # Скролл-область
        self.scroll_area = QScrollArea(self.func_window_grid)
        self.scroll_area.setObjectName('scroll_area')
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area_widget = QWidget(self)
        self.scroll_area_widget.setObjectName('scroll_area_widget')

        # Блок параметров
        self.vertical_layout_2 = QVBoxLayout(self.scroll_area_widget)
        self.vertical_layout_2.setObjectName('vertical_layout_2')

        # Блок описания и добавление его в скролл-область
        self.func_description_layout_2 = QVBoxLayout()
        self.func_description_layout_2.setObjectName(
            'func_description_layout_2')
        self.func_description_label_2 = QLabel(self.scroll_area_widget)

        # Название блока описания
        self.func_description_label_2.setObjectName('func_description_label_2')
        self.func_description_label_2.setText('Описание')
        self.func_description_layout_2.addWidget(self.func_description_label_2)

        # Форма редактирования блока описания
        self.func_description_edit_2 = QLineEdit(self.scroll_area_widget)
        self.func_description_edit_2.setObjectName('func_description_edit_2')
        self.func_description_layout_2.addWidget(self.func_description_edit_2)

        # Добавление блока описания в блок параметров
        self.vertical_layout_2.addLayout(self.func_description_layout_2)

        # Блок синтаксиса и добавление его в скролл-область
        self.func_syntax_layout_2 = QVBoxLayout()
        self.func_syntax_layout_2.setObjectName('func_syntax_layout_2')
        self.func_syntax_label_2 = QLabel(self.scroll_area_widget)

        # Название блока синтаксиса
        self.func_syntax_label_2.setObjectName('func_syntax_label_2')
        self.func_syntax_label_2.setText('Синтаксис')
        self.func_syntax_layout_2.addWidget(self.func_syntax_label_2)

        # Форма редактирования блока синтаксиса
        self.func_syntax_edit_2 = QLineEdit(self.scroll_area_widget)
        self.func_syntax_edit_2.setObjectName('func_syntax_edit_2')
        self.func_syntax_layout_2.addWidget(self.func_syntax_edit_2)

        # Добавление блока синтаксиса в блок параметров
        self.vertical_layout_2.addLayout(self.func_syntax_layout_2)

        # Блок возвращаемого значения и добавление его в скролл-область
        self.func_return_value_layout_2 = QVBoxLayout()
        self.func_return_value_layout_2.setObjectName(
            'func_return_value_layout_2')
        self.func_return_value_label_2 = QLabel(self.scroll_area_widget)

        # Название возвращаемого значения
        self.func_return_value_label_2.setObjectName(
            'func_return_value_label_2')
        self.func_return_value_label_2.setText('Возвращаемое значение')
        self.func_return_value_layout_2.addWidget(
            self.func_return_value_label_2)

        # Форма редактирования возвращаемого значения
        self.func_return_value_edit_2 = QLineEdit(self.scroll_area_widget)
        self.func_return_value_edit_2.setObjectName('func_return_value_edit_2')
        self.func_return_value_layout_2.addWidget(
            self.func_return_value_edit_2)

        # Добавление блока возвращаемого значения в блок параметров
        self.vertical_layout_2.addLayout(self.func_return_value_layout_2)

        # Добавление скролл-области в основную сетку окна
        self.scroll_area.setWidget(self.scroll_area_widget)
        self.vertical_layout_1.addWidget(self.scroll_area)

        # Блок навигации
        self.func_window_nav = QHBoxLayout()
        self.func_window_nav.setObjectName('func_window_nav')

        # Кнопка 'сохравнить и выйти'
        self.save_btn = QPushButton(self.func_window_grid)
        self.save_btn.setObjectName('save_btn')
        self.save_btn.setText('Сохравнить и выйти')
        self.save_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.save_btn.setMinimumSize(QtCore.QSize(200, 30))
        self.save_btn.setMaximumSize(QtCore.QSize(200, 30))
        self.save_btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.save_btn.setStyleSheet(
            'QPushButton {background: #212121;'
            ' color: #fafafa; font-family: Arial Black; '
            'font-size: 10px; border: none;} '
            'QPushButton:hover {background: #383838;}')
        self.save_btn.clicked.connect(self.save)

        # Добавление кнопки 'сохравнить и выйти' в блок навигации
        self.func_window_nav.addWidget(self.save_btn)

        # Добавление блока навигации в основную сетку окна
        self.vertical_layout_1.addLayout(self.func_window_nav)

        # Проверка колличества аргументов
        if self.arg_amount > 0:
            # Блок аргументов
            self.args_layout = QVBoxLayout()
            self.args_layout.setObjectName('args_layout')

            # Название блока аргументов
            self.label_args = QLabel(self.scroll_area_widget)
            self.label_args.setObjectName('label_args')
            self.label_args.setText('Аргументы')
            self.args_layout.addWidget(self.label_args)

            # Добавление блока аргументов в блок параметров
            self.vertical_layout_2.addLayout(self.args_layout)

        # Назначение основного виджета окна
        self.setCentralWidget(self.func_window_grid)

        if self.is_change_func:
            try:
                with open('base.json', 'r', encoding='utf-8') as file:
                    base = json.load(file)
                self.arg_amount = len(base[self.func_name_str]['args'])
            except Exception:
                QMessageBox.information(self, 'Ошибка', 'Функция не найдена!')

        self.n = 0
        for i in range(self.arg_amount):
            self.add_arg()

        if self.is_change_func:
            self.fill_window()

# Добавление одного аргумента

    def add_arg(self):
        self.n += 1
        self.a = 0
        self.grid_args = QVBoxLayout()
        self.label_name_arg = QLabel('аргумент #' + str(self.n),
                                     self.scroll_area_widget)
        self.grid_args.addWidget(self.label_name_arg)
        self.vertical_layout_2.addLayout(self.grid_args)
        self.label_name_arg.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.vertical_layout_2.addLayout(self.grid_args)
        arg_info = (('Название аргумента', 'arg_name_', 'name_arg_lineEdit_'),
                    ('Описаниее аргумента', 'label_description_arg_',
                     'description_arg_lineEdit_'),
                    ('Тип аргумента', 'label_type_arg_', 'type_arg_lineEdit_'),
                    ('Начальное значение аргумента', 'label_default_value_',
                     'default_value_lineEdit_'),
                    ('Примечание', 'label_additions', 'additions_lineEdit_'))
        self.arg_info_form = []
        for name, label, lineEdit in arg_info:
            self.grid_arg = QVBoxLayout()
            self.arg_name = QLabel(name, self.scroll_area_widget)
            self.grid_arg.addWidget(self.arg_name)
            self.arg_lineEdit = QLineEdit()
            self.grid_arg.addWidget(self.arg_lineEdit)
            self.arg_name.setObjectName(label + str(self.a))
            self.arg_lineEdit.setObjectName(lineEdit + str(self.a))
            self.vertical_layout_2.addLayout(self.grid_arg)
            self.a += 1
            self.arg_info_form.append((self.arg_lineEdit))

        self.args_info_form.append(self.arg_info_form)

# Сохранение введённых данных

    def save(self):
        try:
            with open('base.json', 'r', encoding='utf-8') as file:
                base = json.load(file)
        except Exception:
            base = {}

        func = {
            self.func_name_str: {
                'description': self.func_description_edit_2.text(),
                'syntax': self.func_syntax_edit_2.text(),
                'args': {
                    self.args_info_form[i][0].text(): {
                        'description': self.args_info_form[i][1].text(),
                        'type': self.args_info_form[i][2].text(),
                        'default_value': self.args_info_form[i][3].text(),
                        'addition': self.args_info_form[i][4].text()
                    }
                    for i in range(len(self.args_info_form))
                },
                'return_value': self.func_return_value_edit_2.text()
            }
        }

        base[self.func_name_str] = func[self.func_name_str]

        with open('base.json', 'w+', encoding='utf-8') as file:
            json.dump(base, file)

        self.close()


# Заполнение параметров функции, после нажатия на кнопку изменить

    def fill_window(self):
        try:
            with open('base.json', 'r', encoding='utf-8') as file:
                base = json.load(file)

            self.func_description_edit_2.setText(
                base[self.func_name_str]['description'])
            self.func_syntax_edit_2.setText(base[self.func_name_str]['syntax'])
            self.func_return_value_edit_2.setText(
                base[self.func_name_str]['return_value'])
            i = 0
            for arg in base[self.func_name_str]['args']:
                self.args_info_form[i][0].setText(arg)
                self.args_info_form[i][1].setText(
                    base[self.func_name_str]['args'][arg]['description'])
                self.args_info_form[i][2].setText(
                    base[self.func_name_str]['args'][arg]['type'])
                self.args_info_form[i][3].setText(
                    base[self.func_name_str]['args'][arg]['default_value'])
                self.args_info_form[i][4].setText(
                    base[self.func_name_str]['args'][arg]['addition'])
                i += 1

        except Exception:
            QMessageBox.information(self, 'Функция не найдена!')
class TemplateMultipleVariablesDialog(QDialog):
    """
    Class implementing a dialog for entering multiple template variables.
    """

    def __init__(self, variables, parent=None):
        """
        Constructor
        
        @param variables list of template variable names (list of strings)
        @param parent parent widget of this dialog (QWidget)
        """
        super(TemplateMultipleVariablesDialog, self).__init__(parent)

        self.TemplateMultipleVariablesDialogLayout = QVBoxLayout(self)
        self.TemplateMultipleVariablesDialogLayout.setContentsMargins(6, 6, 6, 6)
        self.TemplateMultipleVariablesDialogLayout.setSpacing(6)
        self.TemplateMultipleVariablesDialogLayout.setObjectName("TemplateMultipleVariablesDialogLayout")
        self.setLayout(self.TemplateMultipleVariablesDialogLayout)

        # generate the scrollarea
        self.variablesView = QScrollArea(self)
        self.variablesView.setObjectName("variablesView")
        self.TemplateMultipleVariablesDialogLayout.addWidget(self.variablesView)

        self.variablesView.setWidgetResizable(True)
        self.variablesView.setFrameStyle(QFrame.NoFrame)

        self.top = QWidget(self)
        self.variablesView.setWidget(self.top)
        self.grid = QGridLayout(self.top)
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.grid.setSpacing(6)
        self.top.setLayout(self.grid)

        # populate the scrollarea with labels and text edits
        self.variablesEntries = {}
        row = 0
        for var in variables:
            label = QLabel("{0}:".format(var), self.top)
            self.grid.addWidget(label, row, 0, Qt.Alignment(Qt.AlignTop))
            if var.find(":") >= 0:
                formatStr = var[1:-1].split(":")[1]
                if formatStr in ["ml", "rl"]:
                    t = QTextEdit(self.top)
                    t.setTabChangesFocus(True)
                else:
                    t = QLineEdit(self.top)
            else:
                t = QLineEdit(self.top)
            self.grid.addWidget(t, row, 1)
            self.variablesEntries[var] = t
            row += 1
        # add a spacer to make the entries aligned at the top
        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.grid.addItem(spacer, row, 1)
        self.variablesEntries[variables[0]].setFocus()
        self.top.adjustSize()

        # generate the buttons
        layout1 = QHBoxLayout()
        layout1.setContentsMargins(0, 0, 0, 0)
        layout1.setSpacing(6)
        layout1.setObjectName("layout1")

        spacer1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        layout1.addItem(spacer1)

        self.okButton = QPushButton(self)
        self.okButton.setObjectName("okButton")
        self.okButton.setDefault(True)
        layout1.addWidget(self.okButton)

        self.cancelButton = QPushButton(self)
        self.cancelButton.setObjectName("cancelButton")
        layout1.addWidget(self.cancelButton)

        spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        layout1.addItem(spacer2)

        self.TemplateMultipleVariablesDialogLayout.addLayout(layout1)

        # set the texts of the standard widgets
        self.setWindowTitle(self.tr("Enter Template Variables"))
        self.okButton.setText(self.tr("&OK"))
        self.cancelButton.setText(self.tr("&Cancel"))

        # polish up the dialog
        self.resize(QSize(400, 480).expandedTo(self.minimumSizeHint()))

        self.okButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)

    def getVariables(self):
        """
        Public method to get the values for all variables.
        
        @return dictionary with the variable as a key and its value (string)
        """
        values = {}
        for var, textEdit in list(self.variablesEntries.items()):
            try:
                values[var] = textEdit.text()
            except AttributeError:
                values[var] = textEdit.toPlainText()
        return values
예제 #48
0
class TopNavigationBarContainers(GUIObserver):

    def on_message(self, message: dict):
        self.location_box.setText(str(message["data"]["value"]).split('-')[2])

    @property
    def class_name(self):
        return GUIClassNames.TOP_NAVIGATION_BAR_CONTAINERS

    def __init__(self, gui_concentrate_handler):
        gui_concentrate_handler.attach(self)

        super(TopNavigationBarContainers, self).__init__()

    def setup_ui(self, containers: QFrame, main_gridLayout: QGridLayout):
        self.frame_location_box = QFrame(containers)
        self.frame_location_box.setFrameShape(QFrame.StyledPanel)
        self.frame_location_box.setFrameShadow(QFrame.Raised)
        self.frame_location_box.setObjectName("frame_location_box")

        self.vlayout_location_box = QVBoxLayout(self.frame_location_box)
        self.vlayout_location_box.setContentsMargins(0, 0, 71, 0)
        self.vlayout_location_box.setObjectName("vlayout_location_box")
        self.location_box = QLabel(self.frame_location_box)
        self.location_box.setText("MainPage")
        self.location_box.setCursor(QCursor(Qt.PointingHandCursor))
        self.location_box.setObjectName(TopNavigationBarContainersStyles.location_box_style[0])
        self.location_box.setStyleSheet(TopNavigationBarContainersStyles.location_box_style[1])
        self.location_box.setAlignment(Qt.AlignCenter)
        self.location_box.setOpenExternalLinks(False)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.location_box.sizePolicy().hasHeightForWidth())
        self.location_box.setSizePolicy(sizePolicy)
        self.location_box.setMinimumSize(QSize(370, 33))
        self.location_box.setMaximumSize(QSize(370, 33))
        del sizePolicy
        self.vlayout_location_box.addWidget(self.location_box, 0, Qt.AlignHCenter)
        main_gridLayout.addWidget(self.frame_location_box, 0, 2, 1, 1)

        self.components_frame = QFrame(containers)
        self.components_frame.setMinimumSize(QSize(181, 51))
        self.components_frame.setMaximumSize(QSize(181, 51))
        self.components_frame.setFrameShape(QFrame.StyledPanel)
        self.components_frame.setFrameShadow(QFrame.Raised)
        self.components_frame.setObjectName("components_frame")

        self.item_user = QLabel(self.components_frame)
        self.item_user.setGeometry(QRect(0, 10, 34, 34))
        self.item_user.setCursor(QCursor(Qt.PointingHandCursor))
        self.item_user.setAccessibleName(TopNavigationBarContainersStyles.item_notification_style[0])
        self.item_user.setStyleSheet(TopNavigationBarContainersStyles.item_notification_style[1])
        self.item_user.setPixmap(QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH + "/main_window/user_logo.svg"))
        self.item_user.setAlignment(Qt.AlignCenter)
        self.item_user.setObjectName("item_user")

        self.item_message = QLabel(self.components_frame)
        self.item_message.setObjectName("item_message")
        self.item_message.setStyleSheet(TopNavigationBarContainersStyles.item_notification_style[1])
        self.item_message.setGeometry(QRect(95, 10, 34, 34))
        self.item_message.setCursor(QCursor(Qt.PointingHandCursor))
        self.item_message.setPixmap(QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH + "/main_window/message_logo.svg"))
        self.item_message.setAlignment(Qt.AlignCenter)

        self.item_notification = QLabel(self.components_frame)
        self.item_notification.setGeometry(QRect(47, 10, 34, 34))
        self.item_notification.setCursor(QCursor(Qt.PointingHandCursor))
        self.item_notification.setAccessibleName(TopNavigationBarContainersStyles.item_notification_style[0])
        self.item_notification.setStyleSheet(TopNavigationBarContainersStyles.item_notification_style[1])
        self.item_notification.setPixmap(QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH + "/main_window/notification_logo.svg"))
        self.item_notification.setAlignment(Qt.AlignCenter)
        self.item_notification.setObjectName("item_notification")

        self.item_search = QLabel(self.components_frame)
        self.item_search.setObjectName("item_search")
        self.item_search.setGeometry(QRect(142, 10, 34, 34))
        self.item_search.setCursor(QCursor(Qt.PointingHandCursor))
        self.item_search.setAccessibleName(TopNavigationBarContainersStyles.item_notification_style[0])
        self.item_search.setStyleSheet(TopNavigationBarContainersStyles.item_notification_style[1])
        self.item_search.setPixmap(QPixmap(AppPaths.GUI_ASSETS_ICONS_PATH + "/main_window/search_logo.svg"))
        self.item_search.setAlignment(Qt.AlignCenter)

        self.lbl_number_of_message = QLabel(self.components_frame)
        self.lbl_number_of_message.setGeometry(QRect(110, 5, 31, 26))
        self.lbl_number_of_message.setText("+25")
        self.lbl_number_of_message.setAlignment(Qt.AlignCenter)
        self.lbl_number_of_message.setObjectName(TopNavigationBarContainersStyles.notify_number_of_box_style[0])
        self.lbl_number_of_message.setStyleSheet(TopNavigationBarContainersStyles.notify_number_of_box_style[1])

        self.lbl_number_of_notification = QLabel(self.components_frame)
        self.lbl_number_of_notification.setGeometry(QRect(60, 5, 31, 26))
        self.lbl_number_of_notification.setText("+99")
        self.lbl_number_of_notification.setAlignment(Qt.AlignCenter)
        self.lbl_number_of_notification.setObjectName(TopNavigationBarContainersStyles.notify_number_of_box_style[0])
        self.lbl_number_of_notification.setStyleSheet(TopNavigationBarContainersStyles.notify_number_of_box_style[1])

        main_gridLayout.addWidget(self.components_frame, 0, 0, 1, 1)
예제 #49
0
class ControlWidget(QWidget):
    def __init__(self, winParent):
        super(ControlWidget, self).__init__()
        self.winParent = winParent

        self.rgbdwn = RGBMIN
        self.rgbup = RGBMAX
        self.hsvdwn = HSVMIN
        self.hsvup = HSVMAX
        self.yuvdwn = YUVMIN
        self.yuvup = YUVMAX
        self.initUI()

    def initUI(self):

        self.setMinimumSize(1340, 200)
        self.setMaximumSize(1340, 200)

        """Radio buttons for Original/RGB/HSV/YUV images"""
        self.origButton = QRadioButton("Original")
        self.rgbButton = QRadioButton("RGB")
        self.hsvButton = QRadioButton("HSV")
        self.yuvButton = QRadioButton("YUV")

        """Signals for toggled radio buttons"""
        self.origButton.toggled.connect(lambda: self.origButtonState())
        self.rgbButton.toggled.connect(lambda: self.rgbButtonState())
        self.hsvButton.toggled.connect(lambda: self.hsvButtonState())
        self.yuvButton.toggled.connect(lambda: self.yuvButtonState())

        self.origButton.setChecked(True)

        """Main layout of the widget will contain several vertical layouts"""
        self.hLayout = QHBoxLayout(self)
        self.hLayout.setObjectName("hLayout")

        """ Vertical Layout for radio buttons """
        self.radioLayout = QVBoxLayout()
        self.radioLayout.setObjectName("radioLayout")
        self.radioLayout.addWidget(self.origButton)
        self.radioLayout.addWidget(self.rgbButton)
        self.radioLayout.addWidget(self.hsvButton)
        self.radioLayout.addWidget(self.yuvButton)
        self.vSpacer = QSpacerItem(30, 500, QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.radioLayout.addItem(self.vSpacer)

        hmin, smin, vmin = HSVMIN
        hmax, smax, vmax = HSVMAX
        """ Vertical Layout for HMIN Slider"""
        self.hminLayout = QVBoxLayout()
        self.hminLayout.setObjectName("hminLayout")
        self.hminLabel = QLabel("HMin")
        self.hminValue = QLabel("0")
        self.hminValue.setAlignment(Qt.AlignCenter)
        self.hminSlider = QSlider(Qt.Vertical)
        self.hminSlider.setMinimum(hmin)
        self.hminSlider.setMaximum(hmax)
        self.hminSlider.setValue(hmin)
        self.hminLayout.addWidget(self.hminLabel)
        self.hminLayout.addWidget(self.hminValue)
        self.hminLayout.addWidget(self.hminSlider)

        """ Vertical Layout for HMAX Slider"""
        self.hmaxLayout = QVBoxLayout()
        self.hmaxLayout.setObjectName("hmaxLayout")
        self.hmaxLabel = QLabel("HMax")
        self.hmaxValue = QLabel("6")
        self.hmaxValue.setAlignment(Qt.AlignCenter)
        self.hmaxSlider = QSlider(Qt.Vertical)
        self.hmaxSlider.setMinimum(hmin)
        self.hmaxSlider.setMaximum(hmax)
        self.hmaxSlider.setValue(hmax)
        self.hmaxLayout.addWidget(self.hmaxLabel)
        self.hmaxLayout.addWidget(self.hmaxValue)
        self.hmaxLayout.addWidget(self.hmaxSlider)

        """ Vertical Layout for SMIN Slider"""
        self.sminLayout = QVBoxLayout()
        self.sminLayout.setObjectName("sminLayout")
        self.sminLabel = QLabel("SMin")
        self.sminValue = QLabel("0")
        self.sminValue.setAlignment(Qt.AlignCenter)
        self.sminSlider = QSlider(Qt.Vertical)
        self.sminSlider.setMinimum(smin)
        self.sminSlider.setMaximum(smax)
        self.sminSlider.setValue(smin)
        self.sminLayout.addWidget(self.sminLabel)
        self.sminLayout.addWidget(self.sminValue)
        self.sminLayout.addWidget(self.sminSlider)

        """ Vertical Layout for SMAX Slider"""
        self.smaxLayout = QVBoxLayout()
        self.smaxLayout.setObjectName("smaxLayout")
        self.smaxLabel = QLabel("SMax")
        self.smaxValue = QLabel("1")
        self.smaxValue.setAlignment(Qt.AlignCenter)
        self.smaxSlider = QSlider(Qt.Vertical)
        self.smaxSlider.setMinimum(smin)
        self.smaxSlider.setMaximum(smax)
        self.smaxSlider.setValue(smax)
        self.smaxLayout.addWidget(self.smaxLabel)
        self.smaxLayout.addWidget(self.smaxValue)
        self.smaxLayout.addWidget(self.smaxSlider)

        """ Vertical Layout for VMIN Slider"""
        self.vminLayout = QVBoxLayout()
        self.vminLayout.setObjectName("vminLayout")
        self.vminLabel = QLabel("VMin")
        self.vminValue = QLabel("0")
        self.vminValue.setAlignment(Qt.AlignCenter)
        self.vminSlider = QSlider(Qt.Vertical)
        self.vminSlider.setMinimum(vmin)
        self.vminSlider.setMaximum(vmax)
        self.vminSlider.setValue(vmin)
        self.vminLayout.addWidget(self.vminLabel)
        self.vminLayout.addWidget(self.vminValue)
        self.vminLayout.addWidget(self.vminSlider)

        """ Vertical Layout for VMAX Slider"""
        self.vmaxLayout = QVBoxLayout()
        self.vmaxLayout.setObjectName("vmaxLayout")
        self.vmaxLabel = QLabel("VMax")
        self.vmaxValue = QLabel("255")
        self.vmaxValue.setAlignment(Qt.AlignCenter)
        self.vmaxSlider = QSlider(Qt.Vertical)
        self.vmaxSlider.setMinimum(vmin)
        self.vmaxSlider.setMaximum(vmax)
        self.vmaxSlider.setValue(vmax)
        self.vmaxLayout.addWidget(self.vmaxLabel)
        self.vmaxLayout.addWidget(self.vmaxValue)
        self.vmaxLayout.addWidget(self.vmaxSlider)

        """Adding all the vertical layouts to the main horizontal layout"""
        self.hLayout.addLayout(self.radioLayout)
        self.hLayout.addLayout(self.hminLayout)
        self.hLayout.addLayout(self.hmaxLayout)
        self.hLayout.addLayout(self.sminLayout)
        self.hLayout.addLayout(self.smaxLayout)
        self.hLayout.addLayout(self.vminLayout)
        self.hLayout.addLayout(self.vmaxLayout)
        self.setLayout(self.hLayout)

        """Signals for sliders value changes"""
        self.hminSlider.valueChanged.connect(self.changeHmin)
        self.hmaxSlider.valueChanged.connect(self.changeHmax)
        self.sminSlider.valueChanged.connect(self.changeSmin)
        self.smaxSlider.valueChanged.connect(self.changeSmax)
        self.vminSlider.valueChanged.connect(self.changeVmin)
        self.vmaxSlider.valueChanged.connect(self.changeVmax)

    # Show filtered image. Don't manually disable radio button, API does it for you!
    """Methods for showing images depending on the current checked radio button"""

    def origButtonState(self):
        if self.origButton.isChecked():
            self.winParent.setFilterName("Orig")

    def rgbButtonState(self):
        if self.rgbButton.isChecked():
            self.winParent.setFilterName("RGB")

            rmin, gmin, bmin = RGBMIN
            rmax, gmax, bmax = RGBMAX
            print(RGBMAX)
            rd, gd, bd = self.rgbdwn
            ru, gu, bu = self.rgbup
            self.hminLabel.setText("Rmin")
            self.hminValue.setText(str(rd))
            self.hminSlider.setMinimum(rmin)
            self.hminSlider.setMaximum(rmax)
            self.hminSlider.setValue(rd)

            self.hmaxLabel.setText("RMax")
            self.hmaxValue.setText(str(ru))
            self.hmaxSlider.setMinimum(rmin)
            self.hmaxSlider.setMaximum(rmax)
            self.hmaxSlider.setValue(ru)

            self.sminLabel.setText("GMin")
            self.sminValue.setText(str(gd))
            self.sminSlider.setMinimum(gmin)
            self.sminSlider.setMaximum(gmax)
            self.sminSlider.setValue(gd)

            self.smaxLabel.setText("GMax")
            self.smaxValue.setText(str(gu))
            self.smaxSlider.setMinimum(gmin)
            self.smaxSlider.setMaximum(gmax)
            self.smaxSlider.setValue(gu)

            self.vminLabel.setText("BMin")
            self.vminValue.setText(str(bd))
            self.vminSlider.setMinimum(bmin)
            self.vminSlider.setMaximum(bmax)
            self.vminSlider.setValue(bd)

            self.vmaxLabel.setText("BMax")
            self.vmaxValue.setText(str(bu))
            self.vmaxSlider.setMinimum(bmin)
            self.vmaxSlider.setMaximum(bmax)
            self.vmaxSlider.setValue(bu)

    def hsvButtonState(self):
        if self.hsvButton.isChecked():
            self.winParent.setFilterName("HSV")

            hmin, smin, vmin = HSVMIN
            hmax, smax, vmax = HSVMAX

            hd, sd, vd = self.hsvdwn
            hu, su, vu = self.hsvup

            self.hminLabel.setText("HMin")
            self.hminValue.setText(str(hd))
            self.hminSlider.setMinimum(hmin)
            self.hminSlider.setMaximum(hmax)
            self.hminSlider.setValue(hd)

            self.hmaxLabel.setText("HMax")
            self.hmaxValue.setText(str(hu))
            self.hmaxSlider.setMinimum(hmin)
            self.hmaxSlider.setMaximum(hmax)
            self.hmaxSlider.setValue(hu)

            self.sminLabel.setText("SMin")
            self.sminValue.setText(str(sd))
            self.sminSlider.setMinimum(smin)
            self.sminSlider.setMaximum(smax)
            self.sminSlider.setValue(sd)

            self.smaxLabel.setText("SMax")
            self.smaxValue.setText(str(su))
            self.smaxSlider.setMinimum(smin)
            self.smaxSlider.setMaximum(smax)
            self.smaxSlider.setValue(su)

            self.vminLabel.setText("VMin")
            self.vminValue.setText(str(vd))
            self.vminSlider.setMinimum(vmin)
            self.vminSlider.setMaximum(vmax)
            self.vminSlider.setValue(vd)

            self.vmaxLabel.setText("VMax")
            self.vmaxValue.setText(str(vu))
            self.vmaxSlider.setMinimum(vmin)
            self.vmaxSlider.setMaximum(vmax)
            self.vmaxSlider.setValue(vu)

    def yuvButtonState(self):
        if self.yuvButton.isChecked():
            self.winParent.setFilterName("YUV")

            ymin, umin, vmin = YUVMIN
            ymax, umax, vmax = YUVMAX

            yd, ud, vd = self.yuvdwn
            yu, uu, vu = self.yuvup

            self.hminLabel.setText("YMin")
            self.hminValue.setText(str(yd))
            self.hminSlider.setMinimum(ymin)
            self.hminSlider.setMaximum(ymax)
            self.hminSlider.setValue(yd)

            self.hmaxLabel.setText("YMax")
            self.hmaxValue.setText(str(yu))
            self.hmaxSlider.setMinimum(ymin)
            self.hmaxSlider.setMaximum(ymax)
            self.hmaxSlider.setValue(yu)

            self.sminLabel.setText("UMin")
            self.sminValue.setText(str(ud))
            self.sminSlider.setMinimum(umin)
            self.sminSlider.setMaximum(umax)
            self.sminSlider.setValue(ud)

            self.smaxLabel.setText("UMax")
            self.smaxValue.setText(str(uu))
            self.smaxSlider.setMinimum(umin)
            self.smaxSlider.setMaximum(umax)
            self.smaxSlider.setValue(uu)

            self.vminLabel.setText("VMin")
            self.vminValue.setText(str(vd))
            self.vminSlider.setMinimum(vmin)
            self.vminSlider.setMaximum(vmax)
            self.vminSlider.setValue(vd)

            self.vmaxLabel.setText("VMax")
            self.vmaxValue.setText(str(vu))
            self.vmaxSlider.setMinimum(vmin)
            self.vmaxSlider.setMaximum(vmax)
            self.vmaxSlider.setValue(vu)

    """Methods to get the slider value and update value labels"""

    def changeHmin(self):
        value = self.hminSlider.value()
        if self.hsvButton.isChecked():
            self.hsvdwn[0] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[0] = value
        elif self.yuvButton.isChecked():
            value = self.hminSlider.value()
            self.yuvdwn[0] = value
        self.hminValue.setText(str(value))
        self.setMIN()

    def changeHmax(self):
        value = self.hmaxSlider.value()
        if self.hsvButton.isChecked():
            self.hsvup[0] = value
        elif self.rgbButton.isChecked():
            self.rgbup[0] = value
        elif self.yuvButton.isChecked():
            self.yuvup[0] = value

        self.hmaxValue.setText(str(value))
        self.setMAX()

    def changeSmin(self):
        value = self.sminSlider.value()
        if self.hsvButton.isChecked():
            self.hsvdwn[1] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[1] = value
        elif self.yuvButton.isChecked():
            self.yuvdwn[1] = value

        self.sminValue.setText(str(value))
        self.setMIN()

    def changeSmax(self):
        value = self.smaxSlider.value()
        if self.hsvButton.isChecked():
            self.hsvup[1] = value
        elif self.rgbButton.isChecked():
            self.rgbup[1] = value
        elif self.yuvButton.isChecked():
            self.yuvup[1] = value

        self.smaxValue.setText(str(value))
        self.setMAX()

    def changeVmin(self):
        value = self.vminSlider.value()
        if self.hsvButton.isChecked():
            self.hsvdwn[2] = value
        elif self.rgbButton.isChecked():
            self.rgbdwn[2] = value
        elif self.yuvButton.isChecked():
            self.yuvdwn[2] = value

        self.vminValue.setText(str(value))
        self.setMIN()

    def changeVmax(self):
        value = self.vmaxSlider.value()
        if self.hsvButton.isChecked():
            self.hsvup[2] = value
        elif self.rgbButton.isChecked():
            self.rgbup[2] = value
        elif self.yuvButton.isChecked():
            self.yuvup[2] = value

        self.vmaxValue.setText(str(value))
        self.setMAX()

    def setMAX(self):

        filt = self.winParent.getFilterName()
        if self.hsvButton.isChecked():
            h, s, v = self.hsvup
            self.winParent.getCamera().getFilter(filt).setUpLimit(h, s, v)
        elif self.rgbButton.isChecked():
            h, s, v = self.rgbup
            self.winParent.getCamera().getFilter(filt).setUpLimit(h, s, v)
        elif self.yuvButton.isChecked():
            h, s, v = self.yuvup
            self.winParent.getCamera().getFilter(filt).setUpLimit(h, s, v)

    def setMIN(self):
        filt = self.winParent.getFilterName()
        if self.hsvButton.isChecked():
            h, s, v = self.hsvdwn
            self.winParent.getCamera().getFilter(filt).setDownLimit(h, s, v)
        elif self.rgbButton.isChecked():
            h, s, v = self.rgbdwn
            self.winParent.getCamera().getFilter(filt).setDownLimit(h, s, v)
        elif self.yuvButton.isChecked():
            h, s, v = self.yuvdwn
            self.winParent.getCamera().getFilter(filt).setDownLimit(h, s, v)

    """Close event, for finalize the program"""

    def closeEvent(self, event):
        self.winParent.closeimagesWidget()
예제 #50
-1
class ConfigurationWidget(QWidget):
    """
    Class implementing a dialog for the configuration of eric6.
    
    @signal preferencesChanged() emitted after settings have been changed
    @signal masterPasswordChanged(str, str) emitted after the master
        password has been changed with the old and the new password
    @signal accepted() emitted to indicate acceptance of the changes
    @signal rejected() emitted to indicate rejection of the changes
    """
    preferencesChanged = pyqtSignal()
    masterPasswordChanged = pyqtSignal(str, str)
    accepted = pyqtSignal()
    rejected = pyqtSignal()
    
    DefaultMode = 0
    HelpBrowserMode = 1
    TrayStarterMode = 2
    HexEditorMode = 3
    
    def __init__(self, parent=None, fromEric=True, displayMode=DefaultMode,
                 expandedEntries=[]):
        """
        Constructor
        
        @param parent The parent widget of this dialog. (QWidget)
        @keyparam fromEric flag indicating a dialog generation from within the
            eric6 ide (boolean)
        @keyparam displayMode mode of the configuration dialog
            (DefaultMode, HelpBrowserMode, TrayStarterMode, HexEditorMode)
        @exception RuntimeError raised to indicate an invalid dialog mode
        @keyparam expandedEntries list of entries to be shown expanded
            (list of strings)
        """
        assert displayMode in (
            ConfigurationWidget.DefaultMode,
            ConfigurationWidget.HelpBrowserMode,
            ConfigurationWidget.TrayStarterMode,
            ConfigurationWidget.HexEditorMode,
        )
        
        super(ConfigurationWidget, self).__init__(parent)
        self.fromEric = fromEric
        self.displayMode = displayMode
        
        self.__setupUi()
        
        self.itmDict = {}
        
        if not fromEric:
            from PluginManager.PluginManager import PluginManager
            try:
                self.pluginManager = e5App().getObject("PluginManager")
            except KeyError:
                self.pluginManager = PluginManager(self)
                e5App().registerObject("PluginManager", self.pluginManager)
        
        if displayMode == ConfigurationWidget.DefaultMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "applicationPage":
                [self.tr("Application"), "preferences-application.png",
                 "ApplicationPage", None, None],
                "cooperationPage":
                [self.tr("Cooperation"), "preferences-cooperation.png",
                 "CooperationPage", None, None],
                "corbaPage":
                [self.tr("CORBA"), "preferences-orbit.png",
                 "CorbaPage", None, None],
                "emailPage":
                [self.tr("Email"), "preferences-mail_generic.png",
                 "EmailPage", None, None],
                "graphicsPage":
                [self.tr("Graphics"), "preferences-graphics.png",
                 "GraphicsPage", None, None],
                "hexEditorPage":
                [self.tr("Hex Editor"), "hexEditor.png",
                 "HexEditorPage", None, None],
                "iconsPage":
                [self.tr("Icons"), "preferences-icons.png",
                 "IconsPage", None, None],
                "ircPage":
                [self.tr("IRC"), "irc.png",
                 "IrcPage", None, None],
                "logViewerPage":
                [self.tr("Log-Viewer"), "preferences-logviewer.png",
                 "LogViewerPage", None, None],
                "mimeTypesPage":
                [self.tr("Mimetypes"), "preferences-mimetypes.png",
                 "MimeTypesPage", None, None],
                "networkPage":
                [self.tr("Network"), "preferences-network.png",
                 "NetworkPage", None, None],
                "notificationsPage":
                [self.tr("Notifications"),
                 "preferences-notifications.png",
                 "NotificationsPage", None, None],
                "pluginManagerPage":
                [self.tr("Plugin Manager"),
                 "preferences-pluginmanager.png",
                 "PluginManagerPage", None, None],
                "printerPage":
                [self.tr("Printer"), "preferences-printer.png",
                 "PrinterPage", None, None],
                "pythonPage":
                [self.tr("Python"), "preferences-python.png",
                 "PythonPage", None, None],
                "qtPage":
                [self.tr("Qt"), "preferences-qtlogo.png",
                 "QtPage", None, None],
                "securityPage":
                [self.tr("Security"), "preferences-security.png",
                 "SecurityPage", None, None],
                "shellPage":
                [self.tr("Shell"), "preferences-shell.png",
                 "ShellPage", None, None],
                "tasksPage":
                [self.tr("Tasks"), "task.png",
                 "TasksPage", None, None],
                "templatesPage":
                [self.tr("Templates"), "preferences-template.png",
                 "TemplatesPage", None, None],
                "trayStarterPage":
                [self.tr("Tray Starter"), "erict.png",
                 "TrayStarterPage", None, None],
                "vcsPage":
                [self.tr("Version Control Systems"),
                 "preferences-vcs.png",
                 "VcsPage", None, None],
                
                "0debuggerPage":
                [self.tr("Debugger"), "preferences-debugger.png",
                 None, None, None],
                "debuggerGeneralPage":
                [self.tr("General"), "preferences-debugger.png",
                 "DebuggerGeneralPage", "0debuggerPage", None],
                "debuggerPythonPage":
                [self.tr("Python"), "preferences-pyDebugger.png",
                 "DebuggerPythonPage", "0debuggerPage", None],
                "debuggerPython3Page":
                [self.tr("Python3"), "preferences-pyDebugger.png",
                 "DebuggerPython3Page", "0debuggerPage", None],
                
                "0editorPage":
                [self.tr("Editor"), "preferences-editor.png",
                 None, None, None],
                "editorAPIsPage":
                [self.tr("APIs"), "preferences-api.png",
                 "EditorAPIsPage", "0editorPage", None],
                "editorAutocompletionPage":
                [self.tr("Autocompletion"),
                 "preferences-autocompletion.png",
                 "EditorAutocompletionPage", "0editorPage", None],
                "editorAutocompletionQScintillaPage":
                [self.tr("QScintilla"), "qscintilla.png",
                 "EditorAutocompletionQScintillaPage",
                 "editorAutocompletionPage", None],
                "editorCalltipsPage":
                [self.tr("Calltips"), "preferences-calltips.png",
                 "EditorCalltipsPage", "0editorPage", None],
                "editorCalltipsQScintillaPage":
                [self.tr("QScintilla"), "qscintilla.png",
                 "EditorCalltipsQScintillaPage", "editorCalltipsPage", None],
                "editorGeneralPage":
                [self.tr("General"), "preferences-general.png",
                 "EditorGeneralPage", "0editorPage", None],
                "editorFilePage":
                [self.tr("Filehandling"),
                 "preferences-filehandling.png",
                 "EditorFilePage", "0editorPage", None],
                "editorSearchPage":
                [self.tr("Searching"), "preferences-search.png",
                 "EditorSearchPage", "0editorPage", None],
                "editorSpellCheckingPage":
                [self.tr("Spell checking"),
                 "preferences-spellchecking.png",
                 "EditorSpellCheckingPage", "0editorPage", None],
                "editorStylesPage":
                [self.tr("Style"), "preferences-styles.png",
                 "EditorStylesPage", "0editorPage", None],
                "editorSyntaxPage":
                [self.tr("Code Checkers"), "preferences-debugger.png",
                 "EditorSyntaxPage", "0editorPage", None],
                "editorTypingPage":
                [self.tr("Typing"), "preferences-typing.png",
                 "EditorTypingPage", "0editorPage", None],
                "editorExportersPage":
                [self.tr("Exporters"), "preferences-exporters.png",
                 "EditorExportersPage", "0editorPage", None],
                
                "1editorLexerPage":
                [self.tr("Highlighters"),
                 "preferences-highlighting-styles.png",
                 None, "0editorPage", None],
                "editorHighlightersPage":
                [self.tr("Filetype Associations"),
                 "preferences-highlighter-association.png",
                 "EditorHighlightersPage", "1editorLexerPage", None],
                "editorHighlightingStylesPage":
                [self.tr("Styles"),
                 "preferences-highlighting-styles.png",
                 "EditorHighlightingStylesPage", "1editorLexerPage", None],
                "editorKeywordsPage":
                [self.tr("Keywords"), "preferences-keywords.png",
                 "EditorKeywordsPage", "1editorLexerPage", None],
                "editorPropertiesPage":
                [self.tr("Properties"), "preferences-properties.png",
                 "EditorPropertiesPage", "1editorLexerPage", None],
                
                "1editorMouseClickHandlers":
                [self.tr("Mouse Click Handlers"),
                 "preferences-mouse-click-handler.png",
                 "EditorMouseClickHandlerPage", "0editorPage", None],
                
                "0helpPage":
                [self.tr("Help"), "preferences-help.png",
                 None, None, None],
                "helpDocumentationPage":
                [self.tr("Help Documentation"),
                 "preferences-helpdocumentation.png",
                 "HelpDocumentationPage", "0helpPage", None],
                "helpViewersPage":
                [self.tr("Help Viewers"),
                 "preferences-helpviewers.png",
                 "HelpViewersPage", "0helpPage", None],
                
                "0projectPage":
                [self.tr("Project"), "preferences-project.png",
                 None, None, None],
                "projectBrowserPage":
                [self.tr("Project Viewer"), "preferences-project.png",
                 "ProjectBrowserPage", "0projectPage", None],
                "projectPage":
                [self.tr("Project"), "preferences-project.png",
                 "ProjectPage", "0projectPage", None],
                "multiProjectPage":
                [self.tr("Multiproject"),
                 "preferences-multiproject.png",
                 "MultiProjectPage", "0projectPage", None],
                
                "0interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 None, None, None],
                "interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 "InterfacePage", "0interfacePage", None],
                "viewmanagerPage":
                [self.tr("Viewmanager"), "preferences-viewmanager.png",
                 "ViewmanagerPage", "0interfacePage", None],
            }
            try:
                from PyQt5 import QtWebKit      # __IGNORE_WARNING__
                self.configItems.update({
                    "helpAppearancePage":
                    [self.tr("Appearance"), "preferences-styles.png",
                     "HelpAppearancePage", "0helpPage", None],
                    "helpFlashCookieManagerPage":
                    [self.tr("Flash Cookie Manager"),
                     "flashCookie16.png",
                     "HelpFlashCookieManagerPage", "0helpPage", None],
                    "helpVirusTotalPage":
                    [self.tr("VirusTotal Interface"), "virustotal.png",
                     "HelpVirusTotalPage", "0helpPage", None],
                    "helpWebBrowserPage":
                    [self.tr("eric6 Web Browser"), "ericWeb.png",
                     "HelpWebBrowserPage", "0helpPage", None],
                })
            except ImportError:
                pass
            
            self.configItems.update(
                e5App().getObject("PluginManager").getPluginConfigData())
        
        elif displayMode == ConfigurationWidget.HelpBrowserMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "interfacePage":
                [self.tr("Interface"), "preferences-interface.png",
                 "HelpInterfacePage", None, None],
                "networkPage":
                [self.tr("Network"), "preferences-network.png",
                 "NetworkPage", None, None],
                "printerPage":
                [self.tr("Printer"), "preferences-printer.png",
                 "PrinterPage", None, None],
                "securityPage":
                [self.tr("Security"), "preferences-security.png",
                 "SecurityPage", None, None],
                
                "0helpPage":
                [self.tr("Help"), "preferences-help.png",
                 None, None, None],
                "helpDocumentationPage":
                [self.tr("Help Documentation"),
                 "preferences-helpdocumentation.png",
                 "HelpDocumentationPage", "0helpPage", None],
            }
            try:
                from PyQt5 import QtWebKit      # __IGNORE_WARNING__
                self.configItems.update({
                    "helpAppearancePage":
                    [self.tr("Appearance"), "preferences-styles.png",
                     "HelpAppearancePage", "0helpPage", None],
                    "helpFlashCookieManagerPage":
                    [self.tr("Flash Cookie Manager"),
                     "flashCookie16.png",
                     "HelpFlashCookieManagerPage", "0helpPage", None],
                    "helpVirusTotalPage":
                    [self.tr("VirusTotal Interface"), "virustotal.png",
                     "HelpVirusTotalPage", "0helpPage", None],
                    "helpWebBrowserPage":
                    [self.tr("eric6 Web Browser"), "ericWeb.png",
                     "HelpWebBrowserPage", "0helpPage", None],
                })
            except ImportError:
                pass
        
        elif displayMode == ConfigurationWidget.TrayStarterMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "trayStarterPage":
                [self.tr("Tray Starter"), "erict.png",
                 "TrayStarterPage", None, None],
            }
        
        elif displayMode == ConfigurationWidget.HexEditorMode:
            self.configItems = {
                # key : [display string, pixmap name, dialog module name or
                #        page creation function, parent key,
                #        reference to configuration page (must always be last)]
                # The dialog module must have the module function 'create' to
                # create the configuration page. This must have the method
                # 'save' to save the settings.
                "hexEditorPage":
                [self.tr("Hex Editor"), "hexEditor.png",
                 "HexEditorPage", None, None],
            }
        
        else:
            raise RuntimeError("Illegal mode value: {0}".format(displayMode))
        
        # generate the list entries
        self.__expandedEntries = []
        for key in sorted(self.configItems.keys()):
            pageData = self.configItems[key]
            if pageData[3]:
                if pageData[3] in self.itmDict:
                    pitm = self.itmDict[pageData[3]]  # get the parent item
                else:
                    continue
            else:
                pitm = self.configList
            self.itmDict[key] = ConfigurationPageItem(pitm, pageData[0], key,
                                                      pageData[1])
            self.itmDict[key].setData(0, Qt.UserRole, key)
            if (not self.fromEric or
                displayMode != ConfigurationWidget.DefaultMode or
                    key in expandedEntries):
                self.itmDict[key].setExpanded(True)
        self.configList.sortByColumn(0, Qt.AscendingOrder)
        
        # set the initial size of the splitter
        self.configSplitter.setSizes([200, 600])
        
        self.configList.itemActivated.connect(self.__showConfigurationPage)
        self.configList.itemClicked.connect(self.__showConfigurationPage)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.rejected)
        
        if displayMode in [ConfigurationWidget.HelpBrowserMode,
                           ConfigurationWidget.TrayStarterMode,
                           ConfigurationWidget.HexEditorMode]:
            self.configListSearch.hide()
        
        if displayMode not in [ConfigurationWidget.TrayStarterMode,
                               ConfigurationWidget.HexEditorMode]:
            self.__initLexers()
        
    def accept(self):
        """
        Public slot to accept the buttonBox accept signal.
        """
        if not isMacPlatform():
            wdg = self.focusWidget()
            if wdg == self.configList:
                return
        
        self.accepted.emit()
        
    def __setupUi(self):
        """
        Private method to perform the general setup of the configuration
        widget.
        """
        self.setObjectName("ConfigurationDialog")
        self.resize(900, 650)
        self.verticalLayout_2 = QVBoxLayout(self)
        self.verticalLayout_2.setSpacing(6)
        self.verticalLayout_2.setContentsMargins(6, 6, 6, 6)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        
        self.configSplitter = QSplitter(self)
        self.configSplitter.setOrientation(Qt.Horizontal)
        self.configSplitter.setObjectName("configSplitter")
        
        self.configListWidget = QWidget(self.configSplitter)
        self.leftVBoxLayout = QVBoxLayout(self.configListWidget)
        self.leftVBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.leftVBoxLayout.setSpacing(0)
        self.leftVBoxLayout.setObjectName("leftVBoxLayout")
        self.configListSearch = E5ClearableLineEdit(
            self, self.tr("Enter search text..."))
        self.configListSearch.setObjectName("configListSearch")
        self.leftVBoxLayout.addWidget(self.configListSearch)
        self.configList = QTreeWidget()
        self.configList.setObjectName("configList")
        self.leftVBoxLayout.addWidget(self.configList)
        self.configListSearch.textChanged.connect(self.__searchTextChanged)
        
        self.scrollArea = QScrollArea(self.configSplitter)
        self.scrollArea.setFrameShape(QFrame.NoFrame)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scrollArea.setWidgetResizable(False)
        self.scrollArea.setObjectName("scrollArea")
        
        self.configStack = QStackedWidget()
        self.configStack.setFrameShape(QFrame.Box)
        self.configStack.setFrameShadow(QFrame.Sunken)
        self.configStack.setObjectName("configStack")
        self.scrollArea.setWidget(self.configStack)
        
        self.emptyPage = QWidget()
        self.emptyPage.setGeometry(QRect(0, 0, 372, 591))
        self.emptyPage.setObjectName("emptyPage")
        self.vboxlayout = QVBoxLayout(self.emptyPage)
        self.vboxlayout.setSpacing(6)
        self.vboxlayout.setContentsMargins(6, 6, 6, 6)
        self.vboxlayout.setObjectName("vboxlayout")
        spacerItem = QSpacerItem(
            20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem)
        self.emptyPagePixmap = QLabel(self.emptyPage)
        self.emptyPagePixmap.setAlignment(Qt.AlignCenter)
        self.emptyPagePixmap.setObjectName("emptyPagePixmap")
        self.emptyPagePixmap.setPixmap(
            QPixmap(os.path.join(getConfig('ericPixDir'), 'eric.png')))
        self.vboxlayout.addWidget(self.emptyPagePixmap)
        self.textLabel1 = QLabel(self.emptyPage)
        self.textLabel1.setAlignment(Qt.AlignCenter)
        self.textLabel1.setObjectName("textLabel1")
        self.vboxlayout.addWidget(self.textLabel1)
        spacerItem1 = QSpacerItem(
            20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.vboxlayout.addItem(spacerItem1)
        self.configStack.addWidget(self.emptyPage)
        
        self.verticalLayout_2.addWidget(self.configSplitter)
        
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Apply | QDialogButtonBox.Cancel |
            QDialogButtonBox.Ok | QDialogButtonBox.Reset)
        self.buttonBox.setObjectName("buttonBox")
        if not self.fromEric and \
                self.displayMode == ConfigurationWidget.DefaultMode:
            self.buttonBox.button(QDialogButtonBox.Apply).hide()
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
        self.verticalLayout_2.addWidget(self.buttonBox)

        self.setWindowTitle(self.tr("Preferences"))
        
        self.configList.header().hide()
        self.configList.header().setSortIndicator(0, Qt.AscendingOrder)
        self.configList.setSortingEnabled(True)
        self.textLabel1.setText(
            self.tr("Please select an entry of the list \n"
                    "to display the configuration page."))
        
        QMetaObject.connectSlotsByName(self)
        self.setTabOrder(self.configList, self.configStack)
        
        self.configStack.setCurrentWidget(self.emptyPage)
        
        self.configList.setFocus()
    
    def __searchTextChanged(self, text):
        """
        Private slot to handle a change of the search text.
        
        @param text text to search for (string)
        """
        self.__searchChildItems(self.configList.invisibleRootItem(), text)
    
    def __searchChildItems(self, parent, text):
        """
        Private method to enable child items based on a search string.
        
        @param parent reference to the parent item (QTreeWidgetItem)
        @param text text to search for (string)
        @return flag indicating an enabled child item (boolean)
        """
        childEnabled = False
        text = text.lower()
        for index in range(parent.childCount()):
            itm = parent.child(index)
            if itm.childCount() > 0:
                enable = self.__searchChildItems(itm, text) or \
                    text == "" or text in itm.text(0).lower()
            else:
                enable = text == "" or text in itm.text(0).lower()
            if enable:
                childEnabled = True
            itm.setDisabled(not enable)
        
        return childEnabled
    
    def __initLexers(self):
        """
        Private method to initialize the dictionary of preferences lexers.
        """
        import QScintilla.Lexers
        from .PreferencesLexer import PreferencesLexer, \
            PreferencesLexerLanguageError
        
        self.lexers = {}
        for language in QScintilla.Lexers.getSupportedLanguages():
            if language not in self.lexers:
                try:
                    self.lexers[language] = PreferencesLexer(language, self)
                except PreferencesLexerLanguageError:
                    pass
        
    def __importConfigurationPage(self, name):
        """
        Private method to import a configuration page module.
        
        @param name name of the configuration page module (string)
        @return reference to the configuration page module
        """
        modName = "Preferences.ConfigurationPages.{0}".format(name)
        try:
            mod = __import__(modName)
            components = modName.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)
            return mod
        except ImportError:
            E5MessageBox.critical(
                self,
                self.tr("Configuration Page Error"),
                self.tr("""<p>The configuration page <b>{0}</b>"""
                        """ could not be loaded.</p>""").format(name))
            return None
        
    def __showConfigurationPage(self, itm, column):
        """
        Private slot to show a selected configuration page.
        
        @param itm reference to the selected item (QTreeWidgetItem)
        @param column column that was selected (integer) (ignored)
        """
        pageName = itm.getPageName()
        self.showConfigurationPageByName(pageName, setCurrent=False)
        
    def __initPage(self, pageData):
        """
        Private method to initialize a configuration page.
        
        @param pageData data structure for the page to initialize
        @return reference to the initialized page
        """
        page = None
        if isinstance(pageData[2], types.FunctionType):
            page = pageData[2](self)
        else:
            mod = self.__importConfigurationPage(pageData[2])
            if mod:
                page = mod.create(self)
        if page is not None:
            self.configStack.addWidget(page)
            pageData[-1] = page
            try:
                page.setMode(self.displayMode)
            except AttributeError:
                pass
        return page
        
    def showConfigurationPageByName(self, pageName, setCurrent=True):
        """
        Public slot to show a named configuration page.
        
        @param pageName name of the configuration page to show (string)
        @param setCurrent flag indicating to set the current item (boolean)
        """
        if pageName == "empty" or pageName not in self.configItems:
            page = self.emptyPage
        else:
            pageData = self.configItems[pageName]
            if pageData[-1] is None and pageData[2] is not None:
                # the page was not loaded yet, create it
                page = self.__initPage(pageData)
            else:
                page = pageData[-1]
            if page is None:
                page = self.emptyPage
            elif setCurrent:
                items = self.configList.findItems(
                    pageData[0],
                    Qt.MatchFixedString | Qt.MatchRecursive)
                for item in items:
                    if item.data(0, Qt.UserRole) == pageName:
                        self.configList.setCurrentItem(item)
        self.configStack.setCurrentWidget(page)
        ssize = self.scrollArea.size()
        if self.scrollArea.horizontalScrollBar():
            ssize.setHeight(
                ssize.height() -
                self.scrollArea.horizontalScrollBar().height() - 2)
        if self.scrollArea.verticalScrollBar():
            ssize.setWidth(
                ssize.width() -
                self.scrollArea.verticalScrollBar().width() - 2)
        psize = page.minimumSizeHint()
        self.configStack.resize(max(ssize.width(), psize.width()),
                                max(ssize.height(), psize.height()))
        
        if page != self.emptyPage:
            page.polishPage()
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(True)
        else:
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
            self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
        
        # reset scrollbars
        for sb in [self.scrollArea.horizontalScrollBar(),
                   self.scrollArea.verticalScrollBar()]:
            if sb:
                sb.setValue(0)
        
        self.__currentConfigurationPageName = pageName
        
    def getConfigurationPageName(self):
        """
        Public method to get the page name of the current page.
        
        @return page name of the current page (string)
        """
        return self.__currentConfigurationPageName
        
    def calledFromEric(self):
        """
        Public method to check, if invoked from within eric.
        
        @return flag indicating invocation from within eric (boolean)
        """
        return self.fromEric
        
    def getPage(self, pageName):
        """
        Public method to get a reference to the named page.
        
        @param pageName name of the configuration page (string)
        @return reference to the page or None, indicating page was
            not loaded yet
        """
        return self.configItems[pageName][-1]
        
    def getLexers(self):
        """
        Public method to get a reference to the lexers dictionary.
        
        @return reference to the lexers dictionary
        """
        return self.lexers
        
    def setPreferences(self):
        """
        Public method called to store the selected values into the preferences
        storage.
        """
        for key, pageData in list(self.configItems.items()):
            if pageData[-1]:
                pageData[-1].save()
                # page was loaded (and possibly modified)
                QApplication.processEvents()    # ensure HMI is responsive
        
    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.buttonBox.button(QDialogButtonBox.Apply):
            self.on_applyButton_clicked()
        elif button == self.buttonBox.button(QDialogButtonBox.Reset):
            self.on_resetButton_clicked()
        
    @pyqtSlot()
    def on_applyButton_clicked(self):
        """
        Private slot called to apply the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            page = self.configStack.currentWidget()
            savedState = page.saveState()
            page.save()
            self.preferencesChanged.emit()
            if savedState is not None:
                page.setState(savedState)
            page.polishPage()
        
    @pyqtSlot()
    def on_resetButton_clicked(self):
        """
        Private slot called to reset the settings of the current page.
        """
        if self.configStack.currentWidget() != self.emptyPage:
            currentPage = self.configStack.currentWidget()
            savedState = currentPage.saveState()
            pageName = self.configList.currentItem().getPageName()
            self.configStack.removeWidget(currentPage)
            if pageName == "editorHighlightingStylesPage":
                self.__initLexers()
            self.configItems[pageName][-1] = None
            
            self.showConfigurationPageByName(pageName)
            if savedState is not None:
                self.configStack.currentWidget().setState(savedState)
        
    def getExpandedEntries(self):
        """
        Public method to get a list of expanded entries.
        
        @return list of expanded entries (list of string)
        """
        return self.__expandedEntries
    
    @pyqtSlot(QTreeWidgetItem)
    def on_configList_itemCollapsed(self, item):
        """
        Private slot handling a list entry being collapsed.
        
        @param item reference to the collapsed item (QTreeWidgetItem)
        """
        pageName = item.data(0, Qt.UserRole)
        if pageName in self.__expandedEntries:
            self.__expandedEntries.remove(pageName)
    
    @pyqtSlot(QTreeWidgetItem)
    def on_configList_itemExpanded(self, item):
        """
        Private slot handling a list entry being expanded.
        
        @param item reference to the expanded item (QTreeWidgetItem)
        """
        pageName = item.data(0, Qt.UserRole)
        if pageName not in self.__expandedEntries:
            self.__expandedEntries.append(pageName)