简体   繁体   中英

How to put a QLineEdit into QTableView cell PyQt4?

So here is my model,view and proxy model:

class example(QDialog):
    def __init__(self):
        super(druglist, self).__init__()
        self.setMinimumWidth(745)
        self.UI()
    def UI(self):
        self.table_view=QTableView()
        self.table_model=QStandardItemModel()
        self.table_proxy=QSortFilterProxyModel()
        self.table_proxy.setSourceModel(self.table_model)
        self.table_view.setModel(self.table_proxy)

I'm going to put QLineEdits for each column of my table for filtering purpose. How should i do this?

A delegate can do that. Here's a basic example.

The table view's delegate decides which widget should be used when editing a cell. In this example the delegate is only applied to the first column. The QLineEdit widget has a character limit of 3 so that you can tell the difference between it and the other columns (which otherwise look the same).

class ExampleDelegate(QtGui.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        line_edit = QtGui.QLineEdit(parent)
        line_edit.setMaxLength(3)
        return line_edit


class Example(QtGui.QDialog):
    def __init__(self,):
        super(Example, self).__init__()
        self.build_ui()

    def build_ui(self):       
        self.table_model = QtGui.QStandardItemModel(4, 2)
        self.delegate = ExampleDelegate()
        self.table_view = QtGui.QTableView()
        self.table_view.setItemDelegateForColumn(0, self.delegate)
        self.table_view.setModel(self.table_model)

        self.layout.addWidget(self.table_view)
        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

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