自上周以来,我一直在与 QPlainTextEdit 更新引起的问题作斗争。我正在尝试使用 QPlainTextEdit 创建与 QMainWindow Dialog 窗口分开的窗口。当我尝试使用 appendHtml 信号(也尝试使用 appendText)时,问题就开始了,除非用鼠标标记,否则放置的文本是不可见的。重绘或更新导致程序崩溃或没有可见操作。
带有 QPlainTextEdit 标头的 QDialog 的简化代码:
namespace Ui {
class LogWindow;
}
class LogWriter: public QDialog
{
Q_OBJECT
QMutex print_lock;
public:
class Log{
Q_OBJECT
const static int MAX_SIZE = 100;
bool to_terminal;
QString color;
QMutex *print_lock;
QPlainTextEdit *text_place;
QVector< QPair<QString,time_t> > history;
LogWriter * obj;
public:
bool print;
Log(bool _print,QString _color,LogWriter *obj_ = NULL)
{print = _print; color = _color; obj = obj_;}
void setLock(QMutex *print_lock_){print_lock = print_lock_;}
void setTextField(QPlainTextEdit *_text) {text_place = _text;}
Log& operator<<(QString &a);
Log& operator<<(const char* a);
};
static LogWriter* getInstance()
{
static LogWriter instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return &instance;
}
~LogWriter();
Log LOW,MEDIUM,HIGH;
Ui::LogWindow *ui;
signals:
void signalLogAppend(QString);
};
方法定义的简化代码:
LogWriter::LogWriter(QWidget * parent): QDialog(parent) {
ui = new Ui::LogWindow;
ui->setupUi(this);
LOW.setLock(&print_lock);
MEDIUM.setLock(&print_lock);
HIGH.setLock(&print_lock);
connect(this,SIGNAL(signalLogAppend(QString)),ui->plainTextEdit,
SLOT(appendHtml(QString)),Qt::DirectConnection);
}
LogWriter::Log& LogWriter::Log::operator<< (QString &s){
history.push_front(qMakePair(s,time(NULL)));
if(history.size() > MAX_SIZE) history.pop_back();
if(print){
//print_lock->lock();
QString text = "<font color=\"";
text += color + "\">";
text += s + "</font>";
//cout << text.toStdString() << endl;
//text_place->appendHtml(text);
//text_place->repaint();
emit (obj)->signalLogAppend(text);
//print_lock->unlock();
}
return *this;
}
我有两个单独的 ui 文件(第一个用于主窗口,第二个用于日志窗口)。我必须在整个程序中使用日志窗口(大约 10 个线程),我坚持这个问题。我的问题是 - 是否可以在不使用主线程的情况下强制 GUI 更新,如果没有 - 我还有什么可能性。如果可能的话,我宁愿避免重构我的所有代码——这需要我一些时间来完成。现在记录非常容易 - 我只需要:
LogWindow *log = LogWindow::getInstance();
log->MEDIUM << "something";
作为附加信息,我添加了 QTCreator 警告:
QObject::connect: Cannot queue arguments of type 'QTextBlock'
(Make sure 'QTextBlock' is registered using qRegisterMetaType().)
QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)