Exemplo n.º 1
0
class ParmerPanel(QWidget):
    """参数面板类"""
    send_message_signal = Signal(str, str)

    def __init__(self, username):
        super(ParmerPanel, self).__init__()

        self.username = username
        self.id = None

        self.setObjectName("parmPanel")

        self.setupUI()

        dayu_theme.apply(self)

    # 设置UI界面
    def setupUI(self):

        self.setMaximumWidth(Data.getWindowWidth() / 3)

        self.ui = loadUi(file_path + "\\res\\UI\\ParameterWindow.ui")

        self.ui.setParent(self)
        self.setLayout(QVBoxLayout())
        self.layout().addWidget(self.ui)

        self.widget_1 = self.ui.findChild(QWidget, "widget")
        self.widget_2 = self.ui.findChild(QWidget, "widget_2")
        self.widget_3 = self.ui.findChild(QWidget, "widget_3")
        self.widget_4 = self.ui.findChild(QWidget, "widget_4")
        self.widget_1.setLayout(QVBoxLayout())
        self.widget_2.setLayout(QVBoxLayout())
        self.widget_4.setLayout(QVBoxLayout())
        self.widget_2.layout().setSpacing(8)
        #设置布局

        tab_card = MTabWidget()
        self.label_filePic = MLabel("")
        self.widget_1.setMinimumSize(Data.getWindowHeight() / 2.8,
                                     Data.getWindowHeight() / 2.8)
        tab_card.addTab(self.label_filePic, u'预览图')

        # Todo 加载3d视口
        # self.model_widget = QWidget()
        self.model_widget = CefBrowser(self, url="editor")
        # self.model_widget.setLayout(QVBoxLayout())
        tab_card.addTab(self.model_widget, u'3D视口')

        self.widget_1.layout().addWidget(tab_card)
        self.widget_1.layout().setContentsMargins(0, 0, 0, 0)

        self.widget_2.layout().addWidget(MDivider(u'操作面板'))

        self.let_filename = MLineEdit(text='filename')
        tool_button = MLabel(text=u'文件名').mark().secondary()
        tool_button.setAlignment(Qt.AlignCenter)
        tool_button.setFixedWidth(80)
        self.let_filename.set_prefix_widget(tool_button)
        self.widget_2.layout().addWidget(self.let_filename)

        self.let_path = MLineEdit(text='filepath')
        tool_button_2 = MLabel(text=u'文件地址').mark().secondary()
        tool_button_2.setAlignment(Qt.AlignCenter)
        tool_button_2.setFixedWidth(80)
        self.let_path.set_prefix_widget(tool_button_2)
        self.widget_2.layout().addWidget(self.let_path)
        self.widget_2.layout().addWidget(MLabel(u'标签'))

        self.let_tag = MLineEdit(text='tag')
        self.btn_reviseTag = MPushButton(text=u'修改').primary()
        self.btn_reviseTag.setFixedWidth(80)
        self.let_tag.set_suffix_widget(self.btn_reviseTag)
        self.widget_2.layout().addWidget(self.let_tag)
        self.btn_export = MPushButton(u'导出到houdini').primary()
        self.widget_2.layout().addWidget(self.btn_export)
        self.btn_exportToMaya = MPushButton(u'导出到Maya').primary()
        self.widget_2.layout().addWidget(self.btn_exportToMaya)

        self.timer = QTimer()
        self.timer.setInterval(0.1)
        self.timer.timeout.connect(self.slot_timeout)
        self.auto_color_progress = MProgressBar().auto_color()

        self.widget_2.layout().addWidget(self.auto_color_progress)

        self.widget_4.layout().addWidget(MDivider(u'操作记录'))
        self.setWindowTitle(u"参数面板")

        # #获取控件

        self.tableWidget_operationNote = self.ui.findChild(
            QTableWidget, "tableWidget_operationNote")

        self.tableWidget_operationNote.setStyleSheet(Data.getQSS())
        #设置默认值
        self.let_filename.setReadOnly(True)  #只读
        self.let_path.setReadOnly(True)  #只读
        self.let_tag.setReadOnly(True)  #只读
        self.tableWidget_operationNote.setHorizontalHeaderLabels(
            [u'用户', u'操作', u'时间'])

        # #连接信号与槽
        self.btn_export.clicked.connect(self.slot_run)
        self.btn_reviseTag.clicked.connect(lambda: self.reviseTag())
        # self.tableWidget_operationNote.setColumnCount(3)
        setSectionResizeMode(self.tableWidget_operationNote.horizontalHeader(),
                             QHeaderView.Stretch)  # 自适应

    def setParam(self, type, name, path):
        self.type = type
        self.filename = name
        self.filepath = path

        # 根据图片类型设置图片
        if (type == "jpg" or type == "jpeg" or type == "png"):
            self.setPic(path)
        elif (type == "obj" or type == "fbx"):
            self.setObjPic()

        filepath = os.path.dirname(path)
        filename = filepath.split("/")[-1]

        self.let_filename.setText(filename)
        self.let_path.setText(filepath)

        tags = ""
        assetdb = client[type]
        assetcol = assetdb[name]
        for tagdic in assetcol.find({}, {"Tag": 1}):
            if "Tag" in tagdic:
                tag = tagdic["Tag"]
                tags += tag + ","
        self.let_tag.setText(tags)

        #设置资产操作记录表:
        assetdb = client[type]
        assetcol = assetdb[name]
        assetlist = assetcol.find({}, {
            "UserName": 1,
            "Operation": 1,
            "Time": 1
        })
        #rowcount = len(assetlist)      #assetlist并不是列表类型
        i = 0
        # for x in assetlist:
        #     i += 1  #求得行数减一

        for xdir in assetlist:

            if "UserName" in xdir:
                str1 = xdir["UserName"]
                newItem1 = QTableWidgetItem(str1)
                self.tableWidget_operationNote.setItem(i, 0, newItem1)

            if "Time" in xdir:
                str3 = xdir["Time"]
                newItem3 = QTableWidgetItem(str3)
                self.tableWidget_operationNote.setItem(i, 2, newItem3)

            if "Operation" in xdir:
                str2 = xdir["Operation"]
                newItem2 = QTableWidgetItem(str2)
                self.tableWidget_operationNote.setItem(i, 1, newItem2)
                i += 1

        self.saveBrowseNode(self.username, name, type)  #保存浏览信息到库

        # 链接信号与槽函数
        self.btn_export.clicked.connect(
            lambda: self.exportModelToHoudini(name, type, path))
        self.btn_exportToMaya.clicked.connect(
            lambda: self.exportModelToMaya(name, type, path))
        # self.saveBrowseNode(self.username, name, type)

    # 进度条
    def slot_run(self):
        self.timer.start()
        self.auto_color_progress.setValue(0)

    def slot_timeout(self):
        if self.auto_color_progress.value() > 99:
            self.timer.stop()
        else:
            self.auto_color_progress.setValue(
                self.auto_color_progress.value() + 1)

    def setPic(self, path):
        pixmap = QPixmap(path)
        self.label_filePic.setPixmap(pixmap)
        self.label_filePic.setScaledContents(True)

    def setObjPic(self):
        """加载的是obj模型,设置obj的图片"""
        pixmap = QPixmap(file_path + r"\res\image\objimg.jpg")
        self.label_filePic.setPixmap(pixmap)
        self.label_filePic.setScaledContents(True)

    def saveBrowseNode(self, username, filename, type):

        RTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        #将浏览信息存入用户数据库
        col = userdb[username]
        dict = {"Operation": "Browse", "Time": RTime, "FileName": filename}
        col.insert_one(dict)

        #将浏览信息存入资产数据库
        assetdb = client[type]
        assetcol = assetdb[filename]
        adict = {"UserName": username, "Time": RTime, "Operation": "Browse"}
        assetcol.insert_one(adict)

    def exportModelToHoudini(self, filename, type, path):
        try:

            import hrpyc
            connection, hou = hrpyc.import_remote_module()
            name = filename.split(".")[0]
            if (type == "obj" or type == "fbx"):
                print("exportModelHoudiniOBJ")

                geo = hou.node('/obj').createNode('geo', name)
                fileNode = geo.createNode('file', name)
                fileNode.parm('file').set(path)

                prinShaderNode = hou.node('/mat').createNode(
                    'principledshader', name)
                prinShaderNode.parm('basecolor_useTexture').set(1)

                materialNode = geo.createNode('material', name + "_material")
                materialNode.parm('shop_materialpath1').set("/mat/" + name)
                materialNode.setInput(0, fileNode)
                materialNode.moveToGoodPosition()
                materialNode.setDisplayFlag(1)

            if (type == "jpg" or type == "jpeg"):
                try:
                    print("exportModelHoudiniJPG")
                    # 路径不能有中文
                    imgNode = hou.node('/img').createNode('img', "comp1")
                    imgNode = hou.node('/img/comp1').createNode('file', name)
                    # fileNode = imgNode.createNode('file', name)
                    imgNode.parm('filename1').set(path)
                except:
                    print("ExportPictureFail")

            #保存导出记录到资产数据库
            RTime = time.strftime('%Y-%m-%d %H:%M:%S',
                                  time.localtime(time.time()))
            assetdb = client[type]
            assetcol = assetdb[filename]
            adict = {
                "UserName": self.username,
                "Time": RTime,
                "Operation": "Export"
            }
            assetcol.insert_one(adict)
            # 保存导出记录到用户数据库
            usercol = userdb[self.username]
            adict = {
                "FileName": filename,
                "Time": RTime,
                "Operation": "Export"
            }
            usercol.insert_one(adict)
        except:
            self.slot_show_message(MMessage.info,
                                   (u'导出失败!请确认Houdini是否配置成功或启动。'))
            print(path)
            print(type)

    def exportModelToMaya(self, filename, type, path):

        if type == "obj" or type == "fbx":
            print("ExportModelToMaya")

            import socket

            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect(('127.0.0.1', 7001))
                #s.send('print("HelloWord!!!!!!!!!!!!");')
                name = filename.split(".")[0]

                command0 = "import maya.cmds as mc;"
                command1 = "imported_objects = mc.file(r'" + path + "\', ns='ns', i=True, rnn=True);"
                command2 = "transforms = mc.ls(imported_objects, type='transform');"
                command = command0 + command1 + command2
                s.send(command)
            except:
                self.slot_show_message(MMessage.info,
                                       (u'导出失败!请确认Maya是否配置成功或启动。'))
                print(path)
                print(type)
        else:
            print("This can't export to Maya")

    def saveExportModelNode(self, username, filename, type):
        RTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        # 将浏览信息存入用户数据库
        col = userdb[username]
        dict = {"Operation": "Export", "Time": RTime, "FileName": filename}
        col.insert_one(dict)

        # 将浏览信息存入资产数据库
        assetdb = client[type]
        assetcol = assetdb[filename]
        adict = {"UserName": username, "Time": RTime, "Operation": "Export"}
        assetcol.insert_one(adict)

    def reviseTag(self):

        if self.username != None:
            usercol = userdb[self.username]
            idlist = usercol.find({"_id": "UserID"}, {"UserID": 1})
            for iddir in idlist:
                self.id = iddir["UserID"]

            if self.id != "管理员":
                self.send_message_signal.emit("warnning", u"只有管理员才可以修改标签")
                return 0

            self.let_tag.setReadOnly(False)  #可写入
            self.btn_reviseTag.setText(u"确认修改")

            self.btn_reviseTag.clicked.disconnect()
            self.btn_reviseTag.clicked.connect(lambda: self.confirmReviseTag())

    def confirmReviseTag(self):
        self.let_tag.setReadOnly(True)  # 只读

        #连接数据库
        assetdb = client[self.type]
        assetcol = assetdb[self.filename]
        assetdb = client[self.type]
        assetcol = assetdb[self.filename]

        newTags = self.let_tag.text().split(",")
        self.oldTags = []
        taglist = assetcol.find({}, {"Tag": 1})
        for tag in taglist:
            if "Tag" in tag:
                self.oldTags.append(tag["Tag"])

        #是否有删除标签
        for oldTag in self.oldTags:
            delTag = True
            for newTag in newTags:
                if newTag == oldTag:
                    delTag = False
            if delTag:  #存在
                # 删除资产库里的标签
                deldir = {"Tag": oldTag}
                assetcol.delete_one(deldir)
                #删除标签文件库里对应的文件
                tagfilecol = tagfiledb[oldTag]
                deldir = {"FileName": self.filename}
                tagfilecol.delete_one(deldir)

        #是否有新标签
        for newTag in newTags:
            if newTag == "":
                continue
            # 是否为从未有过的标签
            new = True
            for x in tagcol.find({}, {"Tag": 1}):  # 把数据库里的标签取出
                if newTag == x["Tag"]:
                    new = False
            if new:
                newTagdir = {"Tag": newTag}
                tagcol.insert_one(newTagdir)  # 添加到标签数据库

            addTag = True
            for oldTag in self.oldTags:
                if newTag == oldTag:
                    addTag = False
            if addTag:
                #资产库里添加新标签
                adict = {"Tag": newTag}
                assetcol.insert_one(adict)
                # 标签文件库里添加对应的文件
                tagfilecol = tagfiledb[newTag]
                deldir = {"FileName": self.filename}
                tagfilecol.insert_one(deldir)

        self.btn_reviseTag.setText(u"修改")
        self.send_message_signal.emit("info", u"已成功修改标签")

        #保存操作记录到用户数据库
        RTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        usercol = userdb[self.username]
        adict = {
            "FileName": self.filename,
            "Time": RTime,
            "Operation": "EditTag"
        }
        usercol.insert_one(adict)
        #保存操作记录到资产数据库
        RTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

        adict = {
            "UserName": self.username,
            "Time": RTime,
            "Operation": "EditTag"
        }
        assetcol.insert_one(adict)

        self.btn_reviseTag.clicked.disconnect()
        self.btn_reviseTag.clicked.connect(lambda: self.reviseTag())

    # Todo: 传入预览图路径,加载3d视口资源到3d视口
    def setModelWidget(self, path):

        file = os.path.dirname(path)
        tex_type = [
            'albedo', 'bump', 'roughness', 'specular', 'opacity', 'normal',
            'displacement'
        ]
        data = {}  #存储贴图数据

        for name in os.listdir(file):
            if name.split(".")[-1] == "obj" or name.split(".")[-1] == "fbx":
                modelpath = os.path.join(file, name).replace("\\", "/")
                data["model"] = modelpath

            elif name.split(".")[-1] == "jpg":
                for typ in tex_type:
                    _typ = "_%s." % typ
                    if _typ in name.lower():
                        data[typ] = os.path.join(file, name).replace("\\", "/")
                        break
        import json
        # self.model_widget.layout().addWidget(MLabel(modelpath))
        data = json.dumps(data)
        print data
        self.model_widget.loadAsset(data)

    # 弹出信息提示窗口
    def slot_show_message(self, func, config):
        func(config, parent=self.parent())
Exemplo n.º 2
0
class SearchableMenuBase(ScrollableMenuBase):
    def __init__(self, *args, **kwargs):
        super(SearchableMenuBase, self).__init__(*args, **kwargs)
        self.search_popup = MPopup(self)
        self.search_popup.setVisible(False)
        self.search_bar = MLineEdit(self)
        self.search_label = QtWidgets.QLabel()

        self.search_bar.textChanged.connect(self.slot_search_change)
        self.search_bar.keyPressEvent = partial(
            self.search_key_event, self.search_bar.keyPressEvent
        )
        self.aboutToHide.connect(lambda: self.search_bar.setText(""))

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.search_label)
        layout.addWidget(self.search_bar)
        self.search_popup.setLayout(layout)

        self.setProperty("search_placeholder", self.tr("Search Action..."))
        self.setProperty("search_label", self.tr("Search Action..."))

        self.setProperty("searchable", True)
        self.setProperty("search_re", "I")

    def search_key_event(self, call, event):
        key = event.key()
        # NOTES: support menu original key event on search bar
        if key in (
            QtCore.Qt.Key_Up,
            QtCore.Qt.Key_Down,
            QtCore.Qt.Key_Return,
            QtCore.Qt.Key_Enter,
        ):
            super(SearchableMenuBase, self).keyPressEvent(event)
        elif key == QtCore.Qt.Key_Tab:
            self.search_bar.setFocus()
        return call(event)

    def _set_search_label(self, value):
        self.search_label.setText(value)

    def _set_search_placeholder(self, value):
        self.search_bar.setPlaceholderText(value)

    def _set_search_re(self, value):
        if not isinstance(value, six.text_type):
            raise TypeError("`search_re` property should be a string type")

    def slot_search_change(self, text):
        flags = 0
        for m in self.property("search_re") or "":
            flags |= getattr(re, m.upper(), 0)
        search_reg = re.compile(r".*%s.*" % text, flags)
        self._update_search(search_reg)

    def _update_search(self, search_reg, parent_menu=None):
        actions = parent_menu.actions() if parent_menu else self.actions()
        vis_list = []
        for action in actions:
            menu = action.menu()
            if not menu:
                is_match = bool(re.match(search_reg, action.text()))
                action.setVisible(is_match)
                is_match and vis_list.append(action)
            else:
                is_match = bool(re.match(search_reg, menu.title()))
                self._update_search("" if is_match else search_reg, menu)

        if parent_menu:
            parent_menu.menuAction().setVisible(bool(vis_list) or not search_reg)

    def keyPressEvent(self, event):
        key = event.key()
        if self.property("searchable"):
            # NOTES(timmyliang): 26 character trigger search bar
            if 65 <= key <= 90:
                char = chr(key)
                self.search_bar.setText(char)
                self.search_bar.setFocus()
                self.search_bar.selectAll()
                width = self.sizeHint().width()
                width = width if width >= 50 else 50
                offset = QtCore.QPoint(width, 0)
                self.search_popup.move(self.pos() + offset)
                self.search_popup.show()
            elif key == QtCore.Qt.Key_Escape:
                self.search_bar.setText("")
                self.search_popup.hide()
        return super(SearchableMenuBase, self).keyPressEvent(event)
Exemplo n.º 3
0
class editUserWinodw(QWidget):
    """
    编辑用户信息窗口类
    """
    editUser_signal = QtCore.Signal()  #确认头像信号

    def __init__(self, username):
        super(editUserWinodw, self).__init__()

        self.setWindowModality(Qt.ApplicationModal)

        self.setMinimumSize(Data.getWindowHeight() / 1.5,
                            Data.getWindowHeight() / 3)

        # self.setMinimumSize(Data.getWindowWidth() / 3, Data.getWindowHeight() / 3)
        # self.setMaximumSize(Data.getWindowWidth() / 3, Data.getWindowHeight() / 3)
        self.username = username
        self.key = None
        self.wchp = False
        self.wcun = False
        self.wcpw = False
        self.wcid = False

        # 设置窗口名称
        self.setWindowTitle(u"用户窗口")

        self.tab = MLineTabWidget()
        widget = QWidget()
        widget_child = QWidget()
        widget_child_2 = QWidget()
        widget.setLayout(QHBoxLayout())
        widget_child.setLayout(QVBoxLayout())
        widget_child_2.setLayout(QVBoxLayout())

        self.label_headProfile = MLabel()
        self.label_headProfile.setAlignment(Qt.AlignHCenter)
        self.btn_changeHead = MPushButton(u'选择新头像')

        widget_child.layout().addWidget(self.label_headProfile)
        widget_child.layout().addWidget(self.btn_changeHead)
        # widget_child.layout().addStretch()

        self.let_username = MLineEdit(text='username')
        tool_button = MLabel(text=u'用户名').mark().secondary()
        tool_button.setAlignment(Qt.AlignCenter)
        tool_button.setFixedWidth(80)
        self.let_username.set_prefix_widget(tool_button)

        widget_child_2.layout().addWidget(self.let_username)

        self.let_ID = MLineEdit(text='identity')
        self.btn_changeID = MPushButton(text=u'修改身份').primary()
        self.btn_changeID.setFixedWidth(80)
        self.let_ID.set_suffix_widget(self.btn_changeID)
        widget_child_2.layout().addWidget(self.let_ID)

        self.let_key = MLineEdit(text='')
        tool_button = MLabel(text=u'密钥').mark().secondary()
        tool_button.setAlignment(Qt.AlignCenter)
        tool_button.setFixedWidth(80)
        self.let_key.set_prefix_widget(tool_button)
        widget_child_2.layout().addWidget(self.let_key)

        self.let_password = MLineEdit(text='***********')
        self.btn_changePassword = MPushButton(text=u'修改密码').primary()
        self.btn_changePassword.setFixedWidth(80)
        self.let_password.set_suffix_widget(self.btn_changePassword)
        widget_child_2.layout().addWidget(self.let_password)

        self.btn_ok = MPushButton(u'确定').large().primary()
        self.btn_cancel = MPushButton(u'取消').large().primary()
        layout = QHBoxLayout()
        layout.addWidget(self.btn_ok)
        layout.addWidget(self.btn_cancel)

        widget_child_2.layout().addLayout(layout)

        widget.layout().addWidget(widget_child)
        widget.layout().addWidget(widget_child_2)

        self.tab.add_tab(widget, u'用户信息')

        widget2 = QWidget()
        self.ui = loadUi(file_path + r"\res\UI\EditUserWindow.ui")

        self.ui.setParent(widget2)
        widget2.setLayout(QVBoxLayout())

        widget2.layout().addWidget(self.ui)
        self.tableWidget_operationNode = self.ui.findChild(
            QTableWidget, "tableWidget_operationNode")

        self.tableWidget_operationNode.setStyleSheet(Data.getQSS())

        setSectionResizeMode(self.tableWidget_operationNode.horizontalHeader(),
                             QHeaderView.Stretch)  # 自适应
        # widget2.layout().addSpacing(100)
        self.tab.add_tab(widget2, u'操作记录')

        btn_layout = QHBoxLayout()

        main_lay = QVBoxLayout()
        main_lay.addSpacing(20)

        main_lay.addWidget(self.tab)

        main_lay.addWidget(MDivider(u''))
        main_lay.addLayout(btn_layout)
        main_lay.addSpacing(20)

        self.setLayout(main_lay)
        dayu_theme.background_color = "#262626"
        dayu_theme.apply(self)

        # 设置默认值
        self.tableWidget_operationNode.setHorizontalHeaderLabels(
            [u'操作', u'文件名', u'时间'])
        # 设置资产操作记录表:

        colUser = userdb[self.username]
        userlist = colUser.find({}, {"FileName": 1, "Operation": 1, "Time": 1})

        i = 0
        for xdir in userlist:

            if "Operation" in xdir:
                str1 = xdir["Operation"]

                newItem1 = QTableWidgetItem(str1)
                self.tableWidget_operationNode.setItem(i, 0, newItem1)

            if "FileName" in xdir:
                str2 = xdir["FileName"]
                newItem2 = QTableWidgetItem(str2)
                self.tableWidget_operationNode.setItem(i, 1, newItem2)

            if "Time" in xdir:
                str3 = xdir["Time"]
                newItem3 = QTableWidgetItem(str3)
                self.tableWidget_operationNode.setItem(i, 2, newItem3)
                i += 1

        #设置默认值
        pixmap = QtGui.QPixmap(hpPath + "\\" + self.username + ".jpg")
        self.label_headProfile.setPixmap(pixmap)
        self.let_username.setText(self.username)
        self.let_username.setReadOnly(True)  #只读
        self.let_ID.setReadOnly(True)  # 只读
        self.let_password.setReadOnly(True)  # 只读
        self.let_password.setEchoMode(QLineEdit.Password)  #输入密码形式

        # 从数据库提取ID
        for x in colUser.find({"_id": "UserID"}, {"UserID": 1}):
            ID = x["UserID"]
            self.let_ID.setText(ID)  # 显示身份

        self.let_password.setText("**********")

        #链接信号与槽
        self.btn_changeHead.clicked.connect(lambda: self.editHeadProfile())
        self.btn_ok.clicked.connect(lambda: self.ok())
        self.btn_cancel.clicked.connect(lambda: self.cancel())
        self.btn_changePassword.clicked.connect(lambda: self.changePassword())
        self.btn_changeID.clicked.connect(lambda: self.setID())

    #修改头像
    def editHeadProfile(self):
        dialog = QFileDialog()
        dialog.setStyleSheet(Data.getQSS())
        #根据当前所在文件目录,设置默认打开文件格式
        dialog.setNameFilter(u"图片文件(*.jpg *.png *.jpeg);;")
        #加载对应的文件
        dialog.setFileMode(QFileDialog.ExistingFiles)
        dialog.setViewMode(QFileDialog.Detail)

        if dialog.exec_():
            imgPaths = dialog.selectedFiles()
            imgPath = imgPaths[0]

            self.editHeadProfileWin = headProfieWindow(imgPath)
            self.editHeadProfileWin.show()
            self.editHeadProfileWin.hPOK_signal.connect(
                lambda: self.setPicture())  #选中图片,更新头像
            self.editHeadProfileWin.hPOK_signal.connect(lambda: self.setWCHP())

    #设置头像图片
    def setPicture(self):
        pixmap = QtGui.QPixmap(file_path + r"\res\headPortrial\buffer.jpg")
        self.label_headProfile.setPixmap(pixmap)

    def ok(self):
        # 保存头像
        if self.wchp:
            saveHeadPorfile(self.username,
                            file_path + r"\res\headPortrial\buffer.jpg")
        if self.wcpw:
            self.setPassword()
            self.saveChangePasswordNode(self.username)
        if self.wcid:
            colUser = userdb[self.username]
            # 从数据库提取ID
            for x in colUser.find({"_id": "UserID"}, {"UserID": 1}):
                ID = x["UserID"]
            oldD = {"UserID": ID}
            newD = {"$set": {"UserID": self.let_ID.text()}}
            x = colUser.update_many(oldD, newD)
        self.editUser_signal.emit()  #发射确认修改信号
        self.slot_show_message(MMessage.success, (u'成功修改用户信息'))
        self.close()

    def cancel(self):
        self.close()

    def setWCHP(self):
        self.wchp = True

    def changePassword(self):
        self.let_password.setReadOnly(False)
        self.wcpw = True

    def setPassword(self):
        newPassword = self.let_password.text()
        if not newPassword:
            msgBox = QMessageBox()
            msgBox.setText(u'请输入密码!')
            msgBox.exec_()
            return 0
        colUser = userdb[self.username]
        # 从数据库提取密码
        for x in colUser.find({"_id": "Password"}, {"Password": 1}):
            if "Password" in x:
                DBpassword = x["Password"]
        oldD = {"Password": DBpassword}
        newD = {"$set": {"Password": newPassword}}
        x = colUser.update_many(oldD, newD)

    def setID(self):
        self.key = self.let_key.text()
        if self.key == "IDO":
            if self.let_ID.text() == u"普通用户":
                self.let_ID.setText(u"管理员")
            elif self.let_ID.text() == u"管理员":
                self.let_ID.setText(u"普通用户")
            self.wcid = True

    def saveChangePasswordNode(self, username):
        RTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        # 将浏览信息存入用户数据库
        col = userdb[username]
        dict = {"Operation": "ChangePassword", "Time": RTime}
        col.insert_one(dict)

    # def changeUsername(self):
    #     self.let_username.setReadOnly(False)
    #     self.wcun = True

    # def setUsername(self):
    #     newname = self.let_username.text()
    #     collist = userdb.list_collection_names()
    #     if newname in collist:
    #         print("The username already exists")
    #         return 0

    # 弹出信息提示窗口
    def slot_show_message(self, func, config):
        func(config, parent=self)
Exemplo n.º 4
0
class EditWidget(QWidget):
    send_message_signal = Signal(str, str)

    def __init__(self, paths, parent=None):
        super(EditWidget, self).__init__(parent)
        self.setWindowTitle(u'资产编辑器')
        self.paths = paths
        self.isLoadPic = True  #导出的是图片
        self._init_ui()
        self.setConnect()

    def _init_ui(self):
        self.setWindowModality(Qt.ApplicationModal)
        self.setMinimumSize(Data.getWindowWidth() / 4.5,
                            Data.getWindowHeight() / 1.6)
        self.setMaximumSize(Data.getWindowWidth() / 4.5,
                            Data.getWindowHeight() / 1.6)

        browser_4 = MClickBrowserFolderToolButton().huge()
        self.lineEdit = MLineEdit(text='filepath')
        self.lineEdit.setReadOnly(True)

        browser_4.sig_folder_changed.connect(self.lineEdit.setText)
        lay_1 = QHBoxLayout()
        lay_1.addWidget(self.lineEdit)
        lay_1.addWidget(browser_4)

        self.tab = MLineTabWidget()
        widget = QWidget()
        widget.setLayout(QVBoxLayout())

        self.lineEdit_width = MLineEdit()
        tool_button = MLabel(text=u'宽度').mark().secondary()
        tool_button.setAlignment(Qt.AlignCenter)
        tool_button.setFixedWidth(80)
        self.lineEdit_width.set_prefix_widget(tool_button)
        self.lineEdit_width.setText("1080")
        self.lineEdit_width.setValidator(QIntValidator())

        self.lineEdit_height = MLineEdit()
        tool_button = MLabel(text=u'高度').mark().secondary()
        tool_button.setAlignment(Qt.AlignCenter)
        tool_button.setFixedWidth(80)
        self.lineEdit_height.set_prefix_widget(tool_button)
        self.lineEdit_height.setText("720")
        self.lineEdit_height.setValidator(QIntValidator())

        self.lineEdit_level = MLineEdit()
        tool_button = MLabel(text=u'精度').mark().secondary()
        tool_button.setAlignment(Qt.AlignCenter)
        tool_button.setFixedWidth(80)
        self.lineEdit_level.set_prefix_widget(tool_button)
        self.lineEdit_level.setText("50")
        self.lineEdit_level.setValidator(QIntValidator())

        widget.layout().addWidget(MLabel(u'贴图大小'))
        widget.layout().addWidget(self.lineEdit_width)
        widget.layout().addWidget(self.lineEdit_height)
        widget.layout().addSpacing(10)
        widget.layout().addWidget(MLabel(u'贴图精度'))
        widget.layout().addWidget(self.lineEdit_level)

        self.tab.add_tab(widget, u'低精度图片')

        widget2 = QWidget()
        widget2.setLayout(QVBoxLayout())
        self.MlineEdit_level = MLineEdit()
        tool_button = MLabel(text=u'精度').mark().secondary()
        tool_button.setAlignment(Qt.AlignCenter)
        tool_button.setFixedWidth(80)
        self.MlineEdit_level.set_prefix_widget(tool_button)
        self.MlineEdit_level.setText("50")
        self.MlineEdit_level.setValidator(QIntValidator())
        widget2.layout().addWidget(MLabel(u'模型精度'))
        widget2.layout().addWidget(self.MlineEdit_level)

        widget2.layout().addSpacing(100)
        self.tab.add_tab(widget2, u'低精度模型')

        btn_layout = QHBoxLayout()
        self.btn_ok = MPushButton(text=u'导出').primary()
        self.btn_ok.setFixedWidth(80)

        self.btn_cancel = MPushButton(text=u'取消').primary()
        self.btn_cancel.setFixedWidth(80)

        btn_layout.addWidget(self.btn_ok)
        btn_layout.addWidget(self.btn_cancel)

        main_lay = QVBoxLayout()
        main_lay.addSpacing(20)
        main_lay.addWidget(MDivider(u'路径选择'))
        main_lay.addLayout(lay_1)
        main_lay.addWidget(MDivider(u'操作选择'))
        main_lay.addWidget(self.tab)

        main_lay.addWidget(MDivider(u''))
        main_lay.addLayout(btn_layout)
        main_lay.addSpacing(20)

        self.setLayout(main_lay)
        dayu_theme.background_color = "#262626"
        dayu_theme.apply(self)

    def setConnect(self):
        self.btn_ok.clicked.connect(self.on_btn_ok_click)
        self.btn_cancel.clicked.connect(self.on_btn_cancel_click)
        self.tab.tool_button_group.sig_checked_changed.connect(
            self.on_tab_change)

    def on_btn_ok_click(self):
        if (self.paths == []):
            self.send_message_signal.emit("warnning", u"请选择操作资产")
            self.close
            return

        if (self.lineEdit.text()) == "filepath":
            self.send_message_signal.emit("warnning", u"请选择导出的位置")
            return

        output = self.lineEdit.text()
        if self.isLoadPic == True:
            width = int(self.lineEdit_width.text())
            height = int(self.lineEdit_height.text())
            level = int(self.lineEdit_level.text())
            for path in self.paths:
                for name in os.listdir(path):
                    if name.split(".")[-1] == "jpg":

                        picpath = path + "/" + name
                        self.make_thumb(picpath, output, width, height, level)

            self.send_message_signal.emit("success", u"图片生成成功")

        else:

            level = int(self.MlineEdit_level.text())
            for path in self.paths:
                for name in os.listdir(path):
                    if name.split(".")[-1] == "obj" or name.split(
                            ".")[-1] == "fbx":

                        modelpath = path + "/" + name
                        self.genteralLOD(modelpath, output, level)

        self.close()

    def on_btn_cancel_click(self):

        self.close()

    def on_tab_change(self):
        if self.isLoadPic == True:
            self.isLoadPic = False
        else:
            self.isLoadPic = True

    def make_thumb(self, path, output, size1=1080, size2=720, level=50):
        """
        缩略图生成程序
        size 参数传递要生成的尺寸
        返回缩略图地址
        """

        try:  # 尝试打开文件

            im = Image.open(path)

        except IOError:
            return

        mode = im.mode
        if mode not in ('L', 'RGB'):
            if mode == 'RGBA':
                # 透明图片需要加白色底
                alpha = im.split()[3]
                bgmask = alpha.point(lambda x: 255 - x)
                im = im.convert('RGB')

                im.paste((255, 255, 255), None, bgmask)
            else:
                im = im.convert('RGB')

        width, height = im.size
        if width == height:
            region = im
        else:
            if width > height:
                delta = (width - height) / 2
                box = (delta, 0, delta + height, height)
            else:
                delta = (height - width) / 2
                box = (0, delta, width, delta + width)
            region = im.crop(box)

        filename = (path.split("/"))[-1]

        savePath = output + "//" + os.path.splitext(filename)[0] + "_thumb.jpg"
        # savePath = file_path + r"\res\images\thumbnail"  + "_" + "%sx%s" % (str(size), str(size)) + ".jpg"
        thumb = region.resize((size1, size2), Image.ANTIALIAS)
        if (level < 0):
            level = 0
        elif (level > 100):
            level = 100
        thumb.save(savePath, quality=level)  # 默认 JPEG 保存质量是 75, 可选值(0~100)

    # 生成低精度模型
    def genteralLOD(self, input, output, level=50):
        try:
            import hou
            name = (input.split("/"))[-1]

            name = (name.split("."))[0]

            output = output + "//" + name + "_" + str(level) + ".obj"

            obj = hou.node("obj")
            geo = obj.createNode("geo")
            fileImport = geo.createNode("file")
            fileImport.parm("file").set(input)

            polyreduce = geo.createNode("polyreduce")
            polyreduce.setFirstInput(fileImport)
            polyreduce.parm("percentage").set(level)

            fileExport = geo.createNode("file")
            fileExport.setFirstInput(polyreduce)
            fileExport.parm("filemode").set(2)
            fileExport.parm("file").set(output)
            fileExport.setDisplayFlag(1)
            fileExport.parm("reload").pressButton()
            self.send_message_signal.emit("success", u"模型生成成功")

        except:
            self.send_message_signal.emit("warnning", u"该功能仅在houdini内部可以调用")
Exemplo n.º 5
0
class UserPanel(QWidget):
    """用户面板"""

    login_signal = QtCore.Signal(str)  #用户面板的登陆信号
    CorrectUserName = None

    def __init__(self):
        super(UserPanel, self).__init__()

        self.username = None  # 初始化用户名
        self.imgPath = hpPath + "\\" + "default.jpg"  #保存用户头像
        self.password = None
        self.rePassword = None
        self.key = None
        self.WM = False

        self.login_userName = None
        self.login_password = None

        self.setObjectName("UserPanel")

        self.setupUI()
        self.setTabOrder(self.btn_sign_up, self.line_edit_name)
        self.setTabOrder(self.line_edit_name, self.line_edit_password)
        self.setTabOrder(self.line_edit_password, self.btn_sign_in)
        self.setTabOrder(self.btn_sign_in, self.btn_sign_up)

    # 设置用户界面
    def setupUI(self):

        self.setMinimumSize(Data.getWindowWidth() / 4.7,
                            Data.getWindowHeight() / 2)
        self.setMaximumSize(Data.getWindowWidth() / 4.7,
                            Data.getWindowHeight() / 2)
        self.setWindowModality(Qt.ApplicationModal)
        Data.setWindowCenter(self)
        self.setLayout(QVBoxLayout())

        btn = MPushButton("SIGNAL IN")
        btn.setIcon(QIcon(file_path + r"\res\ZeusDesign\a.png"))

        self.layout().addWidget(btn)
        self.layout().addWidget(MDivider())

        self.line_edit_name = MLineEdit()
        self.line_edit_name.setPlaceholderText('username')
        self.line_edit_name.set_prefix_widget(
            MToolButton().svg('user_line.svg').icon_only())
        self.line_edit_password = MLineEdit()
        self.line_edit_password.setPlaceholderText('password')
        self.line_edit_password.setEchoMode(QLineEdit.Password)
        self.line_edit_password.set_prefix_widget(
            MToolButton().svg('confirm_line.svg').icon_only())

        self.layout().addWidget(self.line_edit_name)
        self.layout().addWidget(self.line_edit_password)

        self.layout().addWidget(MDivider())
        self.btn_sign_in = MPushButton(u'登录').large().primary()
        self.layout().addWidget(self.btn_sign_in)

        self.btn_sign_up = MPushButton(u'注册').large().primary()
        self.layout().addWidget(self.btn_sign_up)

        dayu_theme.background_color = "#262626"
        dayu_theme.apply(self)

        self.layout().setContentsMargins(20, 40, 20, 40)

        self.btn_sign_up.clicked.connect(self.on_sigin_up_click)
        self.btn_sign_in.clicked.connect(self.on_sigin_in_click)

        self.setWindowTitle(u"登录界面")

    # 弹出信息提示窗口
    def slot_show_message(self, func, config):
        func(config, parent=self)

    # 登录按钮按下,加载登录界面
    def on_sigin_in_click(self):
        self.login_userName = self.line_edit_name.text()
        self.login_password = self.line_edit_password.text()
        if not self.login_userName:
            self.slot_show_message(MMessage.error, (u'请输入用户名'))
            return 0
        if not self.login_password:
            self.slot_show_message(MMessage.error, (u'请输入密码'))
            return 0

        collist = userdb.list_collection_names()
        if self.login_userName in collist:  # 判断该用户是否存在
            colUser = userdb[self.login_userName]

            # Todo: 从数据库读取数据,判断是否名字存在,密码是否正确,成功则执行login函数,失败提示
            # 从数据库提取密码
            for x in colUser.find({"_id": "Password"}, {"Password": 1}):
                if "Password" in x:
                    DBpassword = x["Password"]
            if not DBpassword:

                return 0
            if self.login_password == DBpassword:
                saveLoginTime(self.login_userName)  # 保存登陆时间
                self.login_signal.emit(self.login_userName)  # 发射登陆信号
                UserPanel.CorrectUserName = self.login_userName
                msg = MToast.loading(u'正在登录中', parent=self)
                msg.sig_closed.connect(
                    functools.partial(MToast.success, u'登录成功', self))
                self.close()
            else:
                self.slot_show_message(MMessage.error, (u'密码错误'))
        else:
            self.slot_show_message(MMessage.error, (u'该用户名不存在'))
            return 0

    # 设置注册界面
    def setRegeditWindow(self):
        self.custom_widget = QWidget()
        custom_lay = QFormLayout()
        self.custom_widget.setLayout(custom_lay)
        self.btn_regedit_image = MPushButton(u'选择文件')
        self.line_edit_regedit_name = MLineEdit()
        self.line_edit_regedit_password = MLineEdit()
        self.line_edit_regedit_password2 = MLineEdit()
        self.switch_identity = MSwitch().large()

        custom_lay.addRow(u' 选择头像:  ', self.btn_regedit_image)
        custom_lay.addRow(u' 账号名称:  ', self.line_edit_regedit_name)

        custom_lay.addRow(u' 账号密码:  ', self.line_edit_regedit_password)
        custom_lay.addRow(u' 确认密码:  ', self.line_edit_regedit_password2)
        custom_lay.addRow(u' 管理权限: ', self.switch_identity)
        # custom_lay.addRow(u'管理钥匙: ',self.line_edit_key)
        # self.custom_widget.layout().addRow(MLabel)
        self.drawer = MDrawer('Regedit', parent=self)
        submit_button = MPushButton(u'注册').primary()
        cancel_button = MPushButton(u'取消')
        self.drawer.add_button(cancel_button)
        self.drawer.add_button(submit_button)

        self.drawer.setFixedWidth(Data.getWindowWidth() / 5)
        self.drawer.set_widget(self.custom_widget)

        self.line_edit_regedit_name.setText(self.username)
        self.line_edit_regedit_password.setText(self.password)
        self.line_edit_regedit_password2.setText(self.rePassword)

        self.switch_identity.clicked.connect(self.signUpManager)
        self.btn_regedit_image.clicked.connect(self.setHeadPorfie)

        submit_button.clicked.connect(self.regedit)
        cancel_button.clicked.connect(self.drawer.close)

    # 注册按钮按下
    def on_sigin_up_click(self):
        self.slot_new_account()

    # 注册
    def slot_new_account(self):
        self.setRegeditWindow()
        self.drawer.show()

    # 设置头像
    def setHeadPorfie(self):

        dialog = QFileDialog()
        dialog.setStyleSheet(Data.getQSS())
        #根据当前所在文件目录,设置默认打开文件格式
        dialog.setNameFilter(u"图片文件(*.jpg *.png *.jpeg);;")
        #加载对应的文件
        dialog.setFileMode(QFileDialog.ExistingFiles)
        dialog.setViewMode(QFileDialog.Detail)

        if dialog.exec_():
            imgPaths = dialog.selectedFiles()
            self.imgPath = imgPaths[0]

            img = cv2.imread(self.imgPath)
            flag = min(img.shape[0], img.shape[1])
            newimg = img[((img.shape[0] - flag) // 2):((img.shape[0] + flag) //
                                                       2),
                         ((img.shape[1] - flag) // 2):((img.shape[1] + flag) //
                                                       2)]
            newimg = cv2.resize(newimg, (150, 150),
                                interpolation=cv2.INTER_AREA)
            cv2.imwrite(hpPath + "\\" + "buffer.jpg", newimg)  #将图片作为缓存存入指定文件内
            # pixmap = QtGui.QPixmap(hpPath + "\\" + "buffer.jpg")
            # self.lab_headProfile.setPixmap(pixmap)

            # 打开头像编辑器
            self.hpw = headProfieWindow(self.imgPath)
            self.hpw.show()
            # self.hpw.hPOK_signal.connect(lambda: self.setPicture())

    # #保存用户头像路径
    # def setPicture(self):
    #     self.imgPath = file_path + r"\res\headPortrial\buffer.jpg"

    # 设置管理员权限
    def signUpManager(self):
        if (self.WM):
            self.WM = False

            # self.custom_widget.layout().deleteLater(self.custom_widget.layout().itemAt(1))
            # self.custom_widget.layout().removeWidget(self.line_edit_key)
            # self.custom_widget.layout().removeWidget(self.key_label)
            # .deleteLater()

            self.key_label.deleteLater()
            self.line_edit_key.deleteLater()
            # self.key_widget.close()
        else:
            self.WM = True
            self.key_label = MLabel(u"管理密钥:")
            self.line_edit_key = MLineEdit()
            # self.key_widget = QWidget()
            # self.key_widget.setLayout(QHBoxLayout())
            # self.key_widget.layout().addWidget(self.key_label)
            # self.key_widget.layout().addWidget(self.line_edit_key)
            self.custom_widget.layout().addRow(self.key_label,
                                               self.line_edit_key)
            # self.custom_widget.layout().addWidget(self.key_widget)

    #点击完成注册
    def regedit(self):
        self.username = self.line_edit_regedit_name.text()
        self.password = self.line_edit_regedit_password.text()
        self.rePassword = self.line_edit_regedit_password2.text()

        self.key = None

        #判断是否输入信息
        if not self.username:
            self.slot_show_message(MMessage.error, (u'请输入用户名!'))
            return 0

        if not self.password:
            self.slot_show_message(MMessage.error, (u'请输入密码!'))
            return 0

        if not self.rePassword:
            self.slot_show_message(MMessage.error, (u'请再次输入密码!'))
            return 0
        if self.rePassword == self.password:

            collist = userdb.list_collection_names()
            if self.username in collist:  # 判断该用户是否存在
                self.slot_show_message(MMessage.error, (u'该用户已经存在'))

                return 0
            else:
                if self.WM:  #注册管理员
                    self.key = self.line_edit_key.text()
                    if self.key == "IDO":  #管理员密钥
                        saveUsername(self.username)
                        savePassword(self.username, self.password)
                        saveUserID(self.username, "管理员")
                        saveRegisterTime(self.username)
                        if self.imgPath:  #如果设置了截图
                            saveHeadPorfile(self.username,
                                            hpPath + "\\" + "buffer.jpg")
                        else:
                            saveHeadPorfile(self.username,
                                            hpPath + "\\" + "default.jpg")
                        self.drawer.close()  #注册成功,关闭窗口
                    else:
                        self.slot_show_message(MMessage.error, (u'密钥错误'))
                        return 0
                else:  #注册普通用户
                    saveUsername(self.username)
                    savePassword(self.username, self.password)
                    saveUserID(self.username, "普通用户")

                    saveRegisterTime(self.username)
                    if self.imgPath:  # 如果设置了头像截图
                        saveHeadPorfile(self.username, self.imgPath)
                    msg = MToast.loading(u'正在注册中', parent=self)
                    msg.sig_closed.connect(
                        functools.partial(MToast.success, u'注册成功', self))

                    self.drawer.close()  # 注册成功,关闭窗口
        else:
            self.slot_show_message(MMessage.error, (u'两次输入密码不一致!'))
            return 0

    # 登录,显示登录界面
    def login(self, name):
        self.widget = QWidget()
        self.widget.setMinimumSize(Data.getWindowWidth() / 6,
                                   Data.getWindowHeight() / 4)

        # 加载ui,并设置ui界面
        #self.ui = loadUi(file_path + "\\res\\UI\\LoginIn.ui")

        self.ui = loadUi(file_path + "\\res\\UI\\LoginIn.ui")

        self.ui.setParent(self.widget)

        self.widget.setLayout(QVBoxLayout())
        # 设置布局
        self.widget.layout().addWidget(self.ui)
        self.setWidget(self.widget)

        # 获取控件
        self.label_name = self.ui.findChild(QLabel, "label_name")
        self.label_identity = self.ui.findChild(QLabel, "label_identity")
        self.label_headLogin = self.ui.findChild(QLabel, "label_headLogin")
        self.btn_editUser = self.ui.findChild(QPushButton, "btn_editUser")

        # 链接信号与槽函数
        self.btn_editUser.clicked.connect(lambda: self.editUser(name))

        #saveLoginTime(name)  # 储存登陆时间
        # Todo 根据名字访问数据库里的信息,加载到界面

        self.label_name.setText(name)  # 显示用户名

        colUser = userdb[name]
        for x in colUser.find({"_id": "UserID"}, {"UserID": 1}):
            ID = x["UserID"]
            self.label_identity.setText(ID)  # 显示身份

        # 设置头像
        self.setHeadPortrait(name, self.label_headLogin)

        #设置操作记录

        self.Userlogin_signal.emit()

        # Todo 点击头像,可以更换头像界面,然后把头像写入数据库

    # 设置头像
    def setHeadPortrait(self, username, QWidget):
        path = file_path + r"\res\headPortrial\default.jpg"
        nameList = os.listdir(file_path + r"\res\headPortrial")
        for name in nameList:
            if (username + ".jpg") == name:
                path = file_path + r"\res\headPortrial" + "\\" + username + ".jpg"

        pixmap = QtGui.QPixmap(path)
        QWidget.setPixmap(pixmap)

    # #获得用户名并加载登录后用户界面
    # def getUsername(self):
    #     self.username = self.loginWin.username
    #     self.login(self.username)

    #编辑用户信息
    def editUser(self, username):
        self.editUserWin = editUserWinodw(username)
        self.editUserWin.show()
        self.editUserWin.editUser_signal.connect(
            lambda: self.reSetUserInformation(username))  #链接确认编辑信号与槽函

    #重新设置用户信息
    def reSetUserInformation(self, username):
        self.setHeadPortrait(username, self.label_headLogin)
        colUser = userdb[username]
        for x in colUser.find({"_id": "UserID"}, {"UserID": 1}):
            ID = x["UserID"]
            self.label_identity.setText(ID)  # 显示身份