一、用Qt Creator创建test工程
① ui文件
② .h文件
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> class QListWidgetItem; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); public slots: void slotTest(QListWidgetItem *item); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
③ cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QListWidgetItem> #include <QTableWidgetItem> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(slotTest(QListWidgetItem*))); ui->tableWidget->setRowCount(4); ui->tableWidget->setColumnCount(4); ui->tableWidget->setItem(0,0, new QTableWidgetItem("a")); ui->tableWidget->setItem(1,0, new QTableWidgetItem("b")); ui->tableWidget->setItem(2,0, new QTableWidgetItem("c")); ui->tableWidget->setItem(3,0, new QTableWidgetItem("d")); } MainWindow::~MainWindow() { delete ui; } void MainWindow::slotTest(QListWidgetItem *item) { for(int row = 0; row < ui->tableWidget->rowCount();row++) { QTableWidgetItem *itemData = ui->tableWidget->item(row,0); if(item->text() == itemData->text()) { QTableWidgetItem *header = ui->tableWidget->verticalHeaderItem(row); if(header == NULL) { qDebug() << "111111"; } header->setTextColor(QColor(255,0,0)); } } }
④运行程序
问题: 点击ListWidget的Item匹配右边TableWidget数据导致程序崩溃
原因:ui->tableWidget->verticalHeaderItem(row)返回值为NULL
解决办法:重新设置表头,如下图代码:
点击ListWidget 的 item 匹配TableWidget相同数据 将表头标记为红色
原文:https://www.cnblogs.com/jiangson/p/9043251.html