简体   繁体   English

如何从QTableWidgetItem中提取显示的文本?

[英]How can I extract the displayed text from a QTableWidgetItem?

I have a subclass of QTableWidget with the following code: 我有以下代码的QTableWidget的子类:

connect(this, SIGNAL(cellChanged(int, int)), this, SLOT(pushCellChange(int, int)), Qt::QueuedConnection);

...

void MyTableView::pushCellChange(int row, int column)
{
    QString text(item(row, column)->text());
    QByteArray data = text.toAscii();
    cout << data.length() << endl;
    const char* cellData = text.toAscii().constData();
    cout << "Cell ("<<row<<", "<<column<<") changed to: " << cellData << endl;
}

When I change the upper-right cell to anything this outputs: 当我将右上角的单元格更改为任何内容时,将输出:

2
Cell (0, 0) changed to: ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌░▬∟C▌▌

However, while this corrupt data is spewed out on the console, the table widget itself seems to behave normally and shows the correct string. 但是,虽然在控制台上喷出了这些损坏的数据,但表小部件本身似乎表现正常,并显示正确的字符串。 Does anyone know what is going on here? 有人知道这是怎么回事吗?

std::string cellData = text.ToStdString();
cout << "Cell ("<<row<<", "<<column<<") changed to: " << cellData << endl;

That should work fine. 那应该工作正常。 As for why toAscii doesn't work, I have no clue. 至于为什么toAscii 不起作用 ,我不知道。

The call toAscii() is storing the QString 's data to a QByteArray . toAscii()的调用将QString的数据存储到QByteArray In your code, you do this twice: 在您的代码中,您需要执行两次:

QByteArray data = text.toAscii();

const char* cellData = text.toAscii().constData();
                       _____________^ <-- temporary QByteArray   

The const char* is actually pointing to the data within a temporary variable, which goes out of scope at the semicolon, at which point the pointer becomes invalid. const char*实际上指向临时变量中的数据,该临时变量超出了分号的范围,此时指针变为无效。 If instead you were to make use of the local variable data , you'd be OK: 相反,如果要使用局部变量data ,则可以:

const char* cellData = data.constData();
                       ___^ <-- still-in-scope QByteArray

Alternatively, you can do this all in-line with the cout and the data will still be valid when it is copied to the output stream: 另外,您也可以使用cout进行所有这些操作,并且将数据复制到输出流后,数据仍然有效:

cout << "Cell ("<<row<<","<<column<<") changed to: " << text.toAscii().constData() << endl;

If it's just about the console output, you could also use qDebug() (available after #include <QDebug> ) and pass the QString directly: 如果仅是控制台输出,则还可以使用qDebug()(在#include <QDebug>之后提供)并直接传递QString

void MyTableView::pushCellChange(int row, int column)
{
    qDebug() << item(row, column)->text().length();
    qDebug() << "Cell (" << row << ", " << column << ") changed to: "
             << item(row, column)->text();
}

This way, you don't have to mess with data conversion … 这样,您就不必搞乱数据转换了……

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM