Making only one column of a QTreeWidgetItem editable

后端 未结 10 1033
无人共我
无人共我 2020-12-06 04:18

I have a QTreeWidgetItem with two columns of data, is there any way to make only the second column editable? When I do the following:

QTreeWidge         


        
相关标签:
10条回答
  • 2020-12-06 04:52

    I'm new to PySide and Python in general, but I was able to get this to work by registering with the QTreeWidget for itemClicked callbacks. Within the callback, check the column and only call 'editItem' if it's for a column you want to allow editing.

    class Foo(QtGui.QMainWindow):
    ...
    def itemClicked(self, item, column):
       if column > 0:
          self.qtree.editItem(item, column)
    

    By not invoking editItem for column 0, the event is basically discarded.

    0 讨论(0)
  • 2020-12-06 04:58

    I found out that the code below works well for my needs and does "kinda" stop the user from editing certain parts of columns:

    I basically check for role and then column. I only allow for editing in column 0. So if user edit it in any other column, then I stop the setData edit and no change is being made.

    void treeItemSubclassed::setData(int column, int role, const QVariant &value) {
        if (role == Qt::ItemIsEditable && column != 0){
            return;
        }
        QTreeWidgetItem::setData(column, role, value);
    }
    
    0 讨论(0)
  • 2020-12-06 05:01

    You can make only certain columns in a QTreeWidget editable using a workaround:

    1) Set the editTriggers property of the QTreeWidget to NoEditTriggers

    2) On inserting items, set the Qt:ItemIsEditable flag of the QTreeWidgetItem object

    3) Connect the following slot to the "itemDoubleClicked" signal of the QTreeWidget object:

    void MainWindow::onTreeWidgetItemDoubleClicked(QTreeWidgetItem * item, int column)
    {
        if (isEditable(column)) {
            ui.treeWidget->editItem(item, column);
        }
    }
    

    where "isEditable" is a function you wrote that returns true for editable columns and false for non-editable columns.

    0 讨论(0)
  • 2020-12-06 05:05

    The simplest way that I found was to use Qt::ItemFlags

    void myClass::treeDoubleClickSlot(QTreeWidgetItem *item, int column)
    {
        Qt::ItemFlags tmp = item->flags();
        if (isEditable(item, column)) {
            item->setFlags(tmp | Qt::ItemIsEditable);
        } else if (tmp & Qt::ItemIsEditable) {
            item->setFlags(tmp ^ Qt::ItemIsEditable);
        }
    }
    

    The top of the if adds the editing functionality through an OR, and the bottom checks if it is there with AND, then removes it with a XOR.

    This way the editing functionality is added when you want it, and removed when you don't.

    Then connect this function to the tree widget's itemDoubleClicked() signal, and write your 'to edit or not to edit' decision inside of isEditable()

    0 讨论(0)
提交回复
热议问题