2

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

Qt - 何时编辑 QListWidget 行的信号?

对我来说,它只在按“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) 期间,如何让它在每次更改/按键时发出信号,以便我可以实现自动完成类型功能?

4

1 回答 1

2

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

#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();
}
于 2018-12-02T19:14:40.283 回答