QTableWidget 和 QLineEdit - 位置和文本内容

QTableWidget and QLineEdit - position and text content

本文关键字:文本 QLineEdit QTableWidget 位置      更新时间:2023-10-16

我很难弄清楚如何在QLineEdit中获取位置(列和行(和内容。我正在使用事件过滤器来获取信号,但从那里我卡住了。有什么建议吗?谢谢

 ui->tableWidget->setRowCount(5);
 ui->tableWidget->setColumnCount(5);
 QStringList wordList;
 wordList << "alpha" << "omega" << "omega2" << "omega3" <<"omicron" << "zeta";
 for(int i = 0; i<5;i++)
 {
 QLineEdit *lineEdit = new QLineEdit;
 QCompleter *completer = new QCompleter(wordList);
 completer->setCaseSensitivity(Qt::CaseInsensitive);
 lineEdit->installEventFilter(this);
 lineEdit->setCompleter(completer);
 ui->tableWidget->setCellWidget(i,i,lineEdit);
 }
 ....
 bool MainWindow::eventFilter(QObject * object, QEvent *event)
 {
  }

我想在完成编辑后获得该职位。我想通过向上和向下键或鼠标左键从列表中选择一个单词。一旦选择一个单词,该单词将填充QLineEdit。然后我想知道这个职位。现在,如果用户编写的文本与列表内容不同,则不应返回任何位置。我只对"单词列表"中的内容感兴趣。谢谢

正如您在注释中指出的那样,您只想在选择QCompleter中设置的元素时获取文本,为此我们必须使用 void QCompleter::activated(const QString & text) 信号。

为此,将创建一个插槽并建立连接:

*.h

private slots:
    void onActivated(const QString &text);

*。.cpp

    QCompleter *completer = new QCompleter(wordList);
    ...
    connect(completer, qOverload<const QString &>(&QCompleter::activated), this, &MainWindow::onActivated);

有两种可能的解决方案:

  • 首先使用我们通过QCompleterwidget()方法获得的QLineEdit的位置,以及我们通过sender()获得它QCompleter,这是发出信号和pos()的对象。 然后我们得到带有indexAt()QModelIndex,这有行和列的信息:

void MainWindow::onActivated(const QString &text)
{
    QCompleter *completer = static_cast<QCompleter *>(sender());
    QModelIndex ix = ui->tableWidget->indexAt(completer->widget()->pos());
    if(ix.isValid()){
        qDebug()<<ix.row()<<ix.column()<<text;
    }
}
  • 或者将行和列另存为属性:

    QCompleter *completer = new QCompleter(wordList);
    ...
    completer->setProperty("row", i);
    completer->setProperty("column", i);
void MainWindow::onActivated(const QString &text)
{
    QCompleter *completer = static_cast<QCompleter *>(sender());
    qDebug()<< completer->property("row").toInt()<<completer->property("column").toInt()<<text;    
}

在以下链接中,您可以找到两个完整的示例