MainWindow.h
#include <QMainWindow>
#include <QTreeWidget>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void contextMenuRequest(const QPoint& pos);
void openLink();
private:
QTreeWidget* treeWidget;
};
MainWindow.cpp
#include "mainwindow.h"
#include <QTreeWidgetItem>
#include <QStringList>
#include <QBrush>
#include <QAction>
#include <QMenu>
#include <QTime>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
treeWidget = new QTreeWidget(this);
treeWidget->setGeometry(0, 0, 500, 500);
treeWidget->setColumnCount(2);
treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuRequest(QPoint)));
QStringList headers;
headers << "Date" << "Message";
treeWidget->setHeaderLabels(headers);
QTreeWidgetItem* errorItem = new QTreeWidgetItem();
errorItem->setForeground(1, QBrush(QColor(255, 0, 0)));
errorItem->setText(0, QTime::currentTime().toString());
errorItem->setText(1, "error message");
QTreeWidgetItem* warningItem = new QTreeWidgetItem();
warningItem->setForeground(1, QBrush(QColor(255, 165, 0)));
warningItem->setText(0, QTime::currentTime().toString());
warningItem->setText(1, "warning message");
treeWidget->addTopLevelItem(errorItem);
treeWidget->addTopLevelItem(warningItem);
for (int i = 0; i < 500; ++i)
{
QTreeWidgetItem* item;
if (i % 2)
{
item = errorItem->clone();
treeWidget->addTopLevelItem(item);
}
else
{
item = warningItem->clone();
treeWidget->addTopLevelItem(item);
}
treeWidget->scrollToItem(item); //call after adding new item
}
resize(500, 500);
}
MainWindow::~MainWindow()
{
}
void MainWindow::contextMenuRequest(const QPoint& pos)
{
QAction* openAction = new QAction("Open link", this);
connect(openAction, SIGNAL(triggered()), this, SLOT(openLink()));
QMenu menu;
menu.addAction(openAction);
menu.exec(mapToGlobal(pos));
}
void MainWindow::openLink()
{
}
我用一個表格部件爲我登錄我的Qt應用程序。 – drescherjm
「QTreeWidget」將項目顯示爲樹(如Windows資源管理器的左列)。你應該使用'QTableWidget',但我不認爲你將能夠顯示沒有一些代碼的鏈接。看看Qt文檔。這是最好的開始。 –