文本更改后的QListWidget Editable Item信号

时间:2018-12-02 14:09:02

标签: c++ qt qt5 qlistwidget qcompleter

在Qt 4.6.1上,当我连接来自QListWidget的itemChanged信号时,我看不到每次编辑中的持续发射行为,

Qt - signal for when QListWidget row is edited?

对我来说,它仅在按“ Enter”键时才发出itemChanged,其方式与commitData解决方案相同。

QListWidget* Groups = new QListWidget();  
Groups->setEditTriggers(QAbstractItemView::AllEditTriggers);    
connect(Groups,SIGNAL(itemChanged(QListWidgetItem*)),this,SLOT(slot_itemchanged(QListWidgetItem*)));
connect(Groups->itemDelegate(), SIGNAL(commitData(QWidget*)), this, SLOT(slot_dataCommited(QWidget*)));
Groups->insertItem(0,"search");
Groups->item(0)->setFlags(Groups->item(0)->flags() | Qt::ItemIsEditable);

如何在item(0)的编辑过程中每次更改/按键时发出信号,以便实现自动完成类型功能?

1 个答案:

答案 0 :(得分:1)

自动完成任务必须在编辑器中通过委托完成:

#include <QtWidgets>

class CompleteDelegate: public QStyledItemDelegate
{
public:
    using QStyledItemDelegate::QStyledItemDelegate;
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        QWidget *editor = QStyledItemDelegate::createEditor(parent, option, index);
        if(QLineEdit *le = qobject_cast<QLineEdit *>(editor)){
            QStringList wordList{"alpha", "omega", "omicron", "zeta"};
            QCompleter *completer = new QCompleter(wordList, le);
            //completer->setCompletionMode(QCompleter::InlineCompletion);
            le->setCompleter(completer);
        }
        return editor;
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QListWidget w;
    CompleteDelegate *delegate = new CompleteDelegate(&w);
    w.setItemDelegate(delegate);
    w.setEditTriggers(QAbstractItemView::AllEditTriggers);
    for(const QString & text: {"search", "find"}){
        QListWidgetItem *it = new QListWidgetItem(text);
        it->setFlags(it->flags()| Qt::ItemIsEditable);
        w.addItem(it);
    }
    w.show();
    return a.exec();
}