简体   繁体   中英

PyQt5 / PySide2 code only executes works with ascii characters

I have made a script extension for a programm called Nuke which opens a dialog with lineedit and allows the user to enter a label. However the script only executes setLabel() by pressing enter when there are only ascii characters in the lineedit.

text() returns unicode and Nuke has no problem with special characters like äöü in labels if you do it through the normal ui

Here is my code:

# -*- coding: utf-8 -*-
from PySide2 import QtCore, QtGui, QtWidgets
import nuke
import sys
import os

class setLabelTool(QtWidgets.QDialog):
    def __init__(self, node):
        self.n = node
        super(setLabelTool, self).__init__()
        self.setObjectName("Dialog")
        self.setWindowTitle("Test")
        self.setFixedSize(199, 43)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)

        self.lineEdit = QtWidgets.QLineEdit(self)
        self.lineEdit.setGeometry(QtCore.QRect(10, 10, 181, 25))
        self.lineEdit.setObjectName("lineEdit")

        self.lineEdit.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.lineEdit.setAlignment(QtCore.Qt.AlignHCenter)

        currentlabel = self.n['label'].value()
        if len(currentlabel) == 0:
            self.lineEdit.setPlaceholderText("Set node label")
        else:
            self.lineEdit.setText(currentlabel)
            self.lineEdit.selectAll()

        self.lineEdit.returnPressed.connect(self.setLabel)

    def setLabel(self):
        label = self.lineEdit.text()
        self.n['label'].setValue(label)
        print ("Node: " + self.n['name'].value() + " labeled " + label)
        self.close()

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            print "Exit setLabelTool"
            self.close()

def showLabelTool():
    n = nuke.selectedNodes()[-1]
    if n != None:
        Tool = setLabelTool(n)
        Tool.exec_()
    else:
        print "Error in showLabelTool()"

I had the same problem yesterday. text() returns of type unicode and your method needs a string object, to convert just use encode('utf-8')

This might be a bit out of context, but there's easier ways to change the label for a node in Nuke using getInput if that's what you're trying to accomplish:

new_label = nuke.getInput("enter label")
nuke.selectedNode()['label'].setValue(new_label)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM