1.首先在ui中画出两个新建项,分别命名为OpenAction和DeleteAction,并拖到头部。
2. 选择转到槽。
3.选择table weight
4.选择转到槽里的double
5.mainwindow.cpp代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QFileDialog"
#include "QDebug"
#include "QTableWidget"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow),player(new QMediaPlayer)
{ui->setupUi(this);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_OpenAction_triggered()
{QTableWidget* tableWidget = findChild<QTableWidget*>("tableWidget",Qt::FindChildOption::FindChildrenRecursively);QStringList filePaths = QFileDialog::getOpenFileNames();for(QString filePath : filePaths){QFileInfo info(filePath);if(info.suffix() != "mp3"){continue;}qDebug() << info.fileName();int count = tableWidget->rowCount();tableWidget->insertRow(count);QTableWidgetItem* item0 = new QTableWidgetItem(info.fileName());item0->setFlags((Qt::ItemFlag)32);tableWidget->setItem(count,0,item0);QTableWidgetItem* item1 = new QTableWidgetItem(filePath);item0->setFlags((Qt::ItemFlag)32);tableWidget->setItem(count,1,item1);}
}void MainWindow::on_tableWidget_itemDoubleClicked(QTableWidgetItem *item)
{item->setBackgroundColor(Qt::green);player->setMedia(QMediaContent(QUrl::fromLocalFile(item->text())));player->play();
}
6.mainwindow.h代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTableWidgetItem>
#include <QMediaPlayer>namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_OpenAction_triggered();void on_tableWidget_itemDoubleClicked(QTableWidgetItem *item);private:Ui::MainWindow *ui;QMediaPlayer * player; // QMediaPlaylist * playList;
};#endif // MAINWINDOW_H
7.“.pro”部分代码
#-------------------------------------------------
#
# Project created by QtCreator 2022-03-24T18:15:57
#
#-------------------------------------------------QT += core gui
QT += multimediagreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = 324night
TEMPLATE = app# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0CONFIG += c++11SOURCES += \main.cpp \mainwindow.cppHEADERS += \mainwindow.hFORMS += \mainwindow.ui# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
8.结果