当前位置:网站首页>Reprint: detailed explanation of qtablewidget (style, right-click menu, header collapse, multiple selection, etc.)

Reprint: detailed explanation of qtablewidget (style, right-click menu, header collapse, multiple selection, etc.)

2022-06-25 23:35:00 The struggle history of polar bear

Article reprinted from :http://blog.sina.com.cn/s/blog_a6fb6cc90101dd5u.html

stay Qt In the development process , Forms are often used (QTableWidget) This control , There is a lot of information on the Internet , But it's all basic , Some of the problems we often encounter are not clear . therefore , Let's sum it up here today !

  Here's a personal simulation Windows A form for Explorer

   One 、 Set the form style

  table_widget->setColumnCount(4); // Set number of columns

  table_widget->horizontalHeader()->setDefaultSectionSize(150); 
  table_widget->horizontalHeader()->setClickable(false); // Setting the header is not clickable ( By default, click to sort )

  // Set the contents of the header
  QStringList header;
  header<<tr("name")<<tr("last modify time")<<tr("type")<<tr("size");
  table_widget->setHorizontalHeaderLabels(header);

  // Set the header font bold

  QFont font = this->horizontalHeader()->font();
  font.setBold(true);
  table_widget->horizontalHeader()->setFont(font);

  table_widget->horizontalHeader()->setStretchLastSection(true); // Set the width of the fill table
  table_widget->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
  table_widget->verticalHeader()->setDefaultSectionSize(10); // Set row height
  table_widget->setFrameShape(QFrame::NoFrame); // Set borderless
  table_widget->setShowGrid(false); // Set the grid line not to be displayed
  table_widget->verticalHeader()->setVisible(false); // Set the vertical head invisible
  table_widget->setSelectionMode(QAbstractItemView::ExtendedSelection);  // You can choose more (Ctrl、Shift、  Ctrl+A Fine )
  table_widget->setSelectionBehavior(QAbstractItemView::SelectRows);  // When setting the selection behavior, select one line at a time
  table_widget->setEditTriggers(QAbstractItemView::NoEditTriggers); // Settings are not editable
  table_widget->horizontalHeader()->resizeSection(0,150); // Set the width of the first column of the header to 150
  table_widget->horizontalHeader()->setFixedHeight(25); // Set the height of the meter

  table_widget->setStyleSheet("selection-background-color:lightblue;"); // Set the selected background color

  table_widget->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); // Set the header background color

  table_widget->horizontalHeader()->setStyleSheet("QHeaderView{background:blue}");    // Set the background color of the empty part of the header

  // Set level 、 Vertical scroll bar style

  table_widget->horizontalScrollBar()->setStyleSheet("QScrollBar{background:transparent; height:10px;}"
  "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"
  "QScrollBar::handle:hover{background:gray;}"
  "QScrollBar::sub-line{background:transparent;}"
  "QScrollBar::add-line{background:transparent;}");

  table_widget->verticalScrollBar()->setStyleSheet("QScrollBar{background:transparent; width: 10px;}"
  "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"
  "QScrollBar::handle:hover{background:gray;}"
  "QScrollBar::sub-line{background:transparent;}"

  "QScrollBar::add-line{background:transparent;}");

// The width of the header cannot be changed by dragging the mouse 、 Height

    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);

    tableWidget->horizontalHeader()->setDisabled(true);    // Setting columns cannot be dragged

    tableWidget->verticalHeader()->setDisabled(true);        // The setting line cannot be dragged


  Okay , Style setup complete , The effect is as follows :

QTableWidget Detailed explanation ( style 、 Right-click menu 、 Header collapse 、 Multiple selection, etc. )

  Question 1 : The options clicked by the mouse will show a blank box , stay Qt The official website found a blog devoted to , Go straight to the code !

  (1) Implement the following class

  #include "no_focus_delegate.h"

  void NoFocusDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const
  {
     QStyleOptionViewItem itemOption(option);
     if (itemOption.state & QStyle::State_HasFocus)
     {
        itemOption.state = itemOption.state ^ QStyle::State_HasFocus;
     }

     QStyledItemDelegate::paint(painter, itemOption, index);
  }

  (2) Add the following code to the table structure

   table_widget->setItemDelegate(new NoFocusDelegate());

   OK, Dashed border removal

   Question two : When a table has only one row , The header will collapse

  

QTableWidget Detailed explanation ( style 、 Right-click menu 、 Header collapse 、 Multiple selection, etc. )

   Groping for a long time , To solve :

   // When clicking the table, the header row will not be highlighted ( Get focus ) 
   table_widget->horizontalHeader()->setHighlightSections(false); 

  Two 、 Select more than one row and get the selected row

this->setSelectionMode(QAbstractItemView::ExtendedSelection);  // Set multiple selection ( Sure Ctral+A Future generations Ctral+Shift multi-select ) Get the selected line number :

bool TableWidget::getSelectedRow(QSet&set_row)

{

    QList items = this->selectedItems();

    int item_count = items.count();

    if(item_count <= 0)

    {

        return false;

    }

    for(int i=0; i

    {

        // Get the selected row

        int item_row = this->row(items.at(i));

        set_row.insert(item_row);

    }

    return  true;

}

   3、 ... and 、 Operation form ( add to 、 Delete lines, etc )

  (1) Insert rows dynamically

  int row_count = table_widget->rowCount(); // Get the number of rows in the form
  table_widget->insertRow(row_count); // Insert a new line

  QTableWidgetItem *item = new QTableWidgetItem();
  QTableWidgetItem *item1 = new QTableWidgetItem();
  QTableWidgetItem *item2 = new QTableWidgetItem();
  QTableWidgetItem *item3 = new QTableWidgetItem();

  // Set corresponding icon 、 File name 、 Last update time 、 The corresponding type 、 file size
  item->setIcon(icon); //icon Icon for calling the system , Later affix to distinguish    
  item->setText(name);
  item1->setText(last_modify_time);
  item2->setText(type); //type Is the type of the calling system , Later affix to distinguish

  item3->setText(size);

  table_widget->setItem(row_count, 0, item);
  table_widget->setItem(row_count, 1, item1);    
  table_widget->setItem(row_count, 2, item2);
  table_widget->setItem(row_count, 3, item3);

  // Set the style to gray
  QColor color("gray");
  item1->setTextColor(color);
  item2->setTextColor(color);
  item3->setTextColor(color);

  (2) Insert a row at the specified position

  In fact, with (1) be similar ,(1) The precondition is to get the number of table rows

  table_widget->insertRow(row); // Insert a new line row Is the insertion position

   Four 、 Click the event triggered by the header

  (1) Connect the signal and slot of the meter

  connect(horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(onHeaderClicked(int)));

 (2) Implement slot function

  void TableWidget::onHeaderClicked(int column)
  {
      //column For a column of the clicked header
  }

   5、 ... and 、 Open a row for editing

  Since simulation Window Then imitate it a little ,Windows You can change the name , that Qt It must be possible to

QTableWidget Detailed explanation ( style 、 Right-click menu 、 Header collapse 、 Multiple selection, etc. )

   // Get the current node and get the edit name
   QTableWidgetItem *item = table_widget->item(edit_row, 0); //edit_row For the line number you want to edit
   table_widget->setCurrentCell(edit_row, 0);
   table_widget->openPersistentEditor(item); // Open edit item
   table_widget->editItem(item);

   // Close edit item

   table_widget->closePersistentEditor(item);

   OK, Rename complete ,!

    6、 ... and 、 Right-click menu

  (1) Create a menu 、 A menu item

   void TableWidget::createActions()
  {
    // Create menu items
    pop_menu = new QMenu();
    action_name = new QAction(this);
    action_size = new QAction(this);
    action_type = new QAction(this);
    action_date = new QAction(this);

    action_open = new QAction(this);   
    action_download = new QAction(this);
    action_flush = new QAction(this);

    action_delete = new QAction(this);
    action_rename = new QAction(this);
    action_create_folder = new QAction(this);

    action_open->setText(QString(" open "));

    action_download->setText(QString(" download "));

    action_flush->setText(QString(" Refresh "));

    action_delete->setText(QString(" Delete "));

    action_rename->setText(QString(" rename "));

    action_create_folder->setText(QString(" New folder "));

    action_name->setText(QString(" name "));
    action_size->setText(QString(" size "));
    action_type->setText(QString(" Project type "));
    action_date->setText(QString(" modification date "));

    // Set shortcut key

    action_flush->setShortcut(QKeySequence::Refresh);

    // Set the folder icon
    action_create_folder->setIcon(icon);

    QObject::connect(action_create_folder, SIGNAL(triggered()), this, SLOT(createFolder()));
}  

  (2) Re actualize contextMenuEvent

  void TableWidget::contextMenuEvent(QContextMenuEvent *event)
  {
    pop_menu->clear(); // Clear the original menu
    QPoint point = event->pos(); // Get the window coordinates

    QTableWidgetItem *item = this->itemAt(point);

    if(item != NULL)

    {

       pop_menu->addAction(action_download);
       pop_menu->addAction(action_flush);
       pop_menu->addSeparator();
       pop_menu->addAction(action_delete);
       pop_menu->addAction(action_rename);
       pop_menu->addSeparator();
       pop_menu->addAction(action_create_folder);

       sort_style = pop_menu->addMenu(" Sort ");
       sort_style->addAction(action_name);
       sort_style->addAction(action_size);
       sort_style->addAction(action_type);
       sort_style->addAction(action_date);

       // The position where the menu appears is the position of the current mouse
       pop_menu->exec(QCursor::pos());
       event->accept();

    } 

 }

  OK, Be accomplished !

   7、 ... and 、 The signal  

  void cellActivated(int row, int column)
  void cellChanged(int row, int column)
  void cellClicked(int row, int column)
  void cellDoubleClicked(int row, int column)
  void cellEntered(int row, int column)
  void cellPressed(int row, int column)
  void itemActivated(QTableWidgetItem *item)
  void itemChanged(QTableWidgetItem *item)
  void itemClicked(QTableWidgetItem *item)
  void itemDoubleClicked(QTableWidgetItem *item)
  void itemEntered(QTableWidgetItem *item)
  void itemPressed(QTableWidgetItem *item)
  void itemSelectionChanged()

  void currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous)

  void currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)

    Files about the interface ( clip ) How to get icons and types ? For documents , Files with different extensions have at least 100 More than species , If the icon and type are fixed, it is not feasible , therefore , There are two ways to get .

More about QTableView Please refer to :

    All of the above are in contact with Qt Some small experiences summarized since , I hope you found that useful ! Every step is worth a thousand miles , No small stream can make a river ...

notes :
     Technology is communication 、 communicate , Reprint please indicate the source and keep the integrity of the work .

原网站

版权声明
本文为[The struggle history of polar bear]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206252013020343.html