+-
python – 在运行时替换QWidget对象
在我的应用程序中,我必须用自定义的QLineEdit替换所有QLineEdit元素.要做到这一点,有不同的解决方案:

>从pyuic4修改生成的py文件,并用我的一个LineEdit替换所有QLineEdit对象.这个解决方案并不是最好的,因为每次运行pyuic4时,我都会失去对生成的输出文件所做的修改.
>编写一个新的类,在我的窗口或对话框中递归搜索QLineEdit小部件类型,并用我的一个LineEdit替换它们.这个解决方案要好得多.它允许我也可以对其他对象执行相同的操作,或者根据需要对其进行扩展,而无需关心对话框或窗口.

到目前为止,我可以编写一个模块(WidgetReplacer),它以递归方式搜索QGridLayout项,并搜索是否有QLineEdit子项.如果是,请将其替换为我的.

问题是,当我尝试访问我的一个LineEdit对象时,我收到以下错误:

RuntimeError: wrapped C/C++ object of type QLineEdit has been deleted

如果我查看我的输出,我会注意到修改后的QLineEdit对象具有旧的id:

old qt_obj <PyQt4.QtGui.QLineEdit object at 0x0543C930>
Replaced txt_line_1 with LineEdit
new qt_obj <LineEdit.LineEdit object at 0x0545B4B0>
----------------------------------
...
----------------------------------
<PyQt4.QtGui.QLineEdit object at 0x0543C930>

为什么会这样?如何在运行时替换QWidgets?

更新

这里有一些关于ojects包装的其他细节:
在WidgetReplace模块中,如果我转储QEditLine和LineEdit对象,我得到:

<PyQt4.QtGui.QLineEdit object at 0x05378618>
    Reference count: 7
    Address of wrapped object: 051FAC40
    Created by: Python
    To be destroyed by: C/C++
    Parent wrapper: <PyQt4.QtGui.QGridLayout object at 0x05378588>
    Next sibling wrapper: NULL
    Previous sibling wrapper: <PyQt4.QtGui.QLabel object at 0x05378930>
    First child wrapper: NULL

<LineEdit.LineEdit object at 0x05378978>
    Reference count: 3
    Address of wrapped object: 051FAC40
    Created by: Python
    To be destroyed by: C/C++
    Parent wrapper: <__main__.Dialog object at 0x0535FBB8>
    Next sibling wrapper: <PyQt4.QtGui.QGridLayout object at 0x05378780>
    Previous sibling wrapper: NULL
    First child wrapper: NULL

相反,如果我从main转储我的行编辑,我得到follow,它代表已删除的QLineEdit对象:

<PyQt4.QtGui.QLineEdit object at 0x05378618>
    Reference count: 2
    Address of wrapped object: 00000000
    Created by: Python
    To be destroyed by: C/C++
    Parent wrapper: NULL
    Next sibling wrapper: NULL
    Previous sibling wrapper: NULL
    First child wrapper: NULL

在这里我的代码

对话
ui和generate文件可以从DropBox dialog.ui and dialog.py下载

主要

import sys
from PyQt4.QtGui import QDialog, QApplication
from dialog import Ui_Form
from WidgetReplacer import WidgetReplacer

class Dialog(QDialog, Ui_Form):

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

        # Set up the user interface from Designer.
        self.setupUi(self)
        WidgetReplacer().replace_all_qlineedit(self)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Dialog()

    window.show()

    print window.txt_line_1
    window.txt_line_1.setText("Hello Text 1")

    sys.exit(app.exec_())

LineEdit

from PyQt4.QtGui import QLineEdit, QValidator, QPalette
from PyQt4 import QtCore

class LineEdit(QLineEdit):

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

        self.color_red = QPalette()
        self.color_red.setColor(QPalette.Text, QtCore.Qt.red)

        self.color_black = QPalette()
        self.color_black.setColor(QPalette.Text, QtCore.Qt.red)

        # Make connections
        self.textChanged.connect(self.verify_text)

    def verify_text(self, text):
        validator = self.validator()
        is_valid = QValidator.Acceptable

        if validator is not None:
            is_valid = validator.validate(text, 0)

        if is_valid == QValidator.Acceptable:
            self.setPalette(self.color_black)
        elif is_valid in [QValidator.Invalid, QValidator.Intermediate]:
            self.setPalette(self.color_red)

WidgetReplacer

import sip
from LineEdit import LineEdit
from PyQt4.QtCore import QRegExp
from PyQt4 import QtGui

class WidgetReplacer():

    def __init__(self):
        pass

    def replace_all_qlineedit(self, qt_dlg):
        children = self._get_all_gridlayout(qt_dlg)

        items = []
        for child in children:
            new_items = self._find_all_obj_in_layout(child, QtGui.QLineEdit)
            items.extend(new_items)

        for item in items:
            layout = item[0]
            row = item[1]
            column = item[2]
            qt_obj = item[3]
            self._replace_qlineedit_from_gridlayout(qt_dlg, qt_obj,
                                                    layout, row, column)

    def _get_all_gridlayout(self, qt_dlg):
        return qt_dlg.findChildren(QtGui.QGridLayout, QRegExp("gridLayout_[0-9]"))

    def _find_all_obj_in_layout(self, layout, qt_type):
        # Output list format:
        # layout, row, col, qt_obj,
        objects = []
        if type(layout) == QtGui.QGridLayout:
            layout_cols = layout.columnCount()
            layout_rows = layout.rowCount()
            for i in range(layout_rows):
                for j in range(layout_cols):
                    item = layout.itemAtPosition(i, j)
#                    print "item(",i, j, "):", item

                    if type(item) == QtGui.QWidgetItem:
                        if type(item.widget()) == qt_type:
                            new_obj = [layout, i, j, item.widget()]
                            objects.append(new_obj)

        elif type(layout) in [QtGui.QHBoxLayout, QtGui.QVBoxLayout]:
            raise SyntaxError("ERROR: Find of Qt objects in QHBoxLayout or QVBoxLayout still not supported")
#            for i in range(layout.count()):
#                item = layout.itemAt(i)

        return objects

    def _replace_qlineedit_from_gridlayout(self, parent, qt_obj, layout, row, column):
        print "old qt_obj", qt_obj
        obj_name = qt_obj.objectName()
        layout.removeWidget(qt_obj)
        sip.delete(qt_obj)
        qt_obj = LineEdit(parent)
        qt_obj.setObjectName(obj_name)

        layout.addWidget(qt_obj, row, column)
        print "Replaced", obj_name, "with LineEdit"

        print "new qt_obj", qt_obj
        print "----------------------------------"
最佳答案
不要在运行时替换小部件:在Qt Designer中提升小部件,以便在生成GUI模块时,自定义类会自动替换行编辑.

以下是如何推广窗口小部件以使用自定义类:

在Qt Designer中,选择要替换的所有行编辑,然后右键单击它们并选择“Promote to …”.在对话框中,将“Promoted class name”设置为“LineEdit”,并将“Header file”设置为包含此类的模块的python导入路径(例如myapp.LineEdit).然后单击“添加”和“提升”,您将在“对象检查器”窗格中看到类从“QLineEdit”更改为“LineEdit”.

现在,当您使用pyuic重新生成ui模块时,您应该看到它使用您的自定义LineEdit类,并且文件底部会有一个额外的行,如下所示:

    from myapp.LineEdit import LineEdit
点击查看更多相关文章

转载注明原文:python – 在运行时替换QWidget对象 - 乐贴网