用C++将QTreeWidget和QPlainTextEdit结合起来
时间: 2024-05-08 12:16:32 浏览: 98
案例:QTabWidget与QLineEdit
以下是将QTreeWidget和QPlainTextEdit结合起来的示例代码:
```
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建窗口
QWidget window;
window.setWindowTitle("QTreeWidget and QPlainTextEdit Example");
// 创建QTreeWidget和QPlainTextEdit
QTreeWidget treeWidget;
QPlainTextEdit plainTextEdit;
// 将QTreeWidget和QPlainTextEdit添加到窗口中
QVBoxLayout *layout = new QVBoxLayout(&window);
layout->addWidget(&treeWidget);
layout->addWidget(&plainTextEdit);
// 设置QTreeWidget
QStringList headers;
headers << "Name" << "Size" << "Type";
treeWidget.setHeaderLabels(headers);
QTreeWidgetItem *root = new QTreeWidgetItem(&treeWidget);
root->setText(0, "Root");
QTreeWidgetItem *file1 = new QTreeWidgetItem(root);
file1->setText(0, "File 1");
file1->setText(1, "10 KB");
file1->setText(2, "Text");
QTreeWidgetItem *file2 = new QTreeWidgetItem(root);
file2->setText(0, "File 2");
file2->setText(1, "20 KB");
file2->setText(2, "Image");
// 连接QTreeWidget的itemClicked信号和槽函数
QObject::connect(&treeWidget, &QTreeWidget::itemClicked, [&](QTreeWidgetItem *item, int column)
{
QString text = item->text(0) + " " + item->text(1) + " " + item->text(2);
plainTextEdit.setPlainText(text);
});
// 显示窗口
window.show();
return app.exec();
}
```
这段代码创建了一个窗口,将QTreeWidget和QPlainTextEdit添加进去,并设置了一个简单的QTreeWidget。当QTreeWidget中的一个项目被单击时,将在QPlainTextEdit中显示该项目的文本。
阅读全文