QTableWidget单击选中取消

您所在的位置:网站首页 怎么取消点击 QTableWidget单击选中取消

QTableWidget单击选中取消

2024-07-12 16:50| 来源: 网络整理| 查看: 265

QTableWidget单击选中取消事件 前言

很多情况下有这样的需求,当鼠标点击QTableWidget时,每次只能选中一行或者不选中,不允许选中多行。例如:当点击表格中时选中一行,同时打开所选中的这行的详细信息(另一个GUI控件),当点击表格之外,选中行取消高亮(取消选择),同时详细信息也消失。

说明

1、QTableWidget时,选择行时,可以使用

 setSelectionBehavior(QAbstractItemView::SelectRows);

2、QTableWidget选择多个节点时,单击节点之外是可以自动取消高亮行的,现在的问题是每次只能选择一行,QT文档说明如下:

Constant

Value

Description

QAbstractItemView::SingleSelection

1

When the user selects an item, any already-selected item becomes unselected, andthe user cannot unselect the selected item by clicking on it.

QAbstractItemView::ContiguousSelection

4

When the user selects an item in the usual way, the selection is cleared and the new item selected. However, if the user presses the Shift key while clicking on an item, all items between the current item and the clicked item are selected or unselected, depending on the state of the clicked item.

QAbstractItemView::ExtendedSelection

3

When the user selects an item in the usual way, the selection is cleared and the new item selected. However, if the user presses the Ctrl key when clicking on an item, the clicked item gets toggled and all other items are left untouched. If the user presses the Shift key while clicking on an item, all items between the current item and the clicked item are selected or unselected, depending on the state of the clicked item. Multiple items can be selected by dragging the mouse over them.

QAbstractItemView::MultiSelection

2

When the user selects an item in the usual way, the selection status of that item is toggled and the other items are left alone. Multiple items can be toggled by dragging the mouse over them.

QAbstractItemView::NoSelection

0

Items cannot be selected.

红色字体可以看出,SingleSelection模式时,再次单击选中的行,是不会取消选择的,其实,还有一个没有说明:就是单击表格之外,其实也不会取消当前的选择。

         当表格中有多行数据时,其实可以点击其他行,是可以切换的,最大的问题是,当表格只有一行数据时,如果你选中了该行后,那么无论点击哪里,该选择都取消不了,这会带来一系列的问题……

         那么如何能实现每次只选择一行,却可以在点击表格之外,可以取消当前的选择行?

 

解决方法

         通过继承,重写鼠标按下事件,在按下的时候,判断该坐标点是否在表格中,进行取消/选择高亮是可以实现的,但是,不太喜欢这样做……

         现在的方法如下,无需继承,只需要一个槽行数即可。

1、  首先我们选择使用

setSelectionBehavior(QAbstractItemView::SelectRows)设置行选择。

setSelectionMode(QAbstractItemView::ContiguousSelection);设置多行选择。

2、  使该表的信号itemSelectionChanged与某个槽关联。

3、  在槽中进行处理,使其看起来像单行选择的效果。具体说明看代码

.h文件

 

#ifndef CTESTGUI_H

#define CTESTGUI_H

 

#include

 

class QTableWidget;

 

class CTestGui : public QWidget

{

    Q_OBJECT

 

public:

    CTestGui(QWidget *parent =NULL);

    ~



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3