qt - QTextEdit 在 setText()/insertPlainText() 之后刷新
问题描述
我在私人插槽中有一个 QTextEdit 小部件,我会定期使用 setText() 和 insertPlainText() 对其进行更新。
我发现 setText()/insertPlainText() 不会立即更新 QTextEdit 小部件。相反,当 slot 函数返回时,QTextWidget 会更新。为了测试这一点,我在 setText()/insertPlainText() 之后放置了一个 sleep()。
class MyWindow : public Widget
{
MyWindow()
{
my_button = new QPushButton(this);
my_edit = new QTextEdit(this);
connect(my_button,
&QPushButton::clicked,
this,
&MyWindow::my_callback);
}
private slots:
void my_callback()
{
my_edit->setText("sample text");
// nothing happens; the QTextEdit
// widget does not show "sample text"
sleep(10);
// the QTextEdit widget will show
// "sample text" AFTER the sleep,
// when my_callback returns.
}
private:
QPushButton* my_button;
QTextEdit* my_edit;
}
这对我来说是个问题,因为我需要在启动一个耗时的过程(使用 QProcess)之前在我的 QTextEdit 小部件中打印一条消息。目前,直到 QProcess 进程返回后才会打印此消息。
有谁知道如何让 QTextEdit 小部件在 setText()/insertPlainText() 之后立即显示其内容?
在 Fedora 29 上使用 Qt5。
解决方案
永远不要在 GUI 线程中执行耗费大量时间的任务。通常,解决方案是在另一个线程中执行该任务,但在您的情况下,它表明您使用 QProcess,所以我假设您使用的是方法 waitForFinished()、waitForStarted() 或 waitForReadyRead() 之一,而不是您应该使用信号:
#include <QtWidgets>
class Widget: public QWidget{
Q_OBJECT
public:
Widget(QWidget *parent=nullptr):
QWidget(parent)
{
button.setText("Press me");
QVBoxLayout *lay = new QVBoxLayout{this};
lay->addWidget(&button);
lay->addWidget(&textedit);
connect(&button, &QPushButton::clicked, this, &Widget::onClicked);
connect(&process, &QProcess::readyReadStandardError, this, &Widget::onReadyReadStandardError);
connect(&process, &QProcess::readyReadStandardOutput, this, &Widget::onReadAllStandardOutput);
}
private Q_SLOTS:
void onClicked(){
textedit.setText("sample text");
process.start("ping 8.8.8.8");
}
void onReadyReadStandardError(){
textedit.append(process.readAllStandardError());
}
void onReadAllStandardOutput(){
textedit.append(process.readAllStandardOutput());
}
private:
QPushButton button;
QTextEdit textedit;
QProcess process;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
#include "main.moc"
推荐阅读
- django - 如何在 django 中发送电子邮件并附加动态上下文传递的邀请.ics 文件?
- ajax - 级联下拉列表中的第二个下拉列表未加载(ASP.NET CORE)
- swift - CocoaPod : [!] 找不到 `PODEMO` 的规范
- javascript - 如何在 Typescript 中添加多个断言
- amazon-web-services - 如果我在读取过时的数据后写入 DynamoDb 数据会发生什么?
- java - ArrayList 添加不正确的值
- java - 从 Activity 退出后,片段上的 OnItemClickListener 不起作用
- php - 使用 AJAX xmlhttprequest 上传图片文件失败
- python - 我应该如何假设三个贵重物品并在此代码块中打印它们
- python - 我试图每天在某个时间执行我的代码,但它不起作用