Exclusive checkbox in QListView

Exclusive checkbox in QListView

By : Michael Hansen
Date : November 22 2020, 09:00 AM
I hope this helps . You can always make it in the way described below. Firstly connect the clicked signal of ListView to the slot which will handle your items click. Secondly inside of the slot you can get the item from QModelIndex and check the state of the item. Below is pseudo code:
For example, in constructor of ListView:
code :
  connect(this, SIGNAL(clicked(QModelIndex)), this, SLOT(_handleItemClicked(QModelIndex)));
void ListView::_handleItemClicked(QModelIndex index)
        QStandardItem* item = _model->itemFromIndex(index);

        if( item->checkState() == Qt::Checked) qDebug() << "Checked!";

Share : facebook icon twitter icon
How to style the checkbox in a QListView so that the label is under the checkbox?

How to style the checkbox in a QListView so that the label is under the checkbox?

By : Uzma Hamid
Date : March 29 2020, 07:55 AM
hop of those help? So the only solution is to create a styled item delegate with your custom checkbox and label, just adapt this code : http://discussion.forum.nokia.com/forum/showthread.php?217027-Display-widget-as-items-in-a-QListView&p=813138&viewfull=1#post813138
How to add a Checkbox in the repeater and the checkbox should be mutually exclusive check box

How to add a Checkbox in the repeater and the checkbox should be mutually exclusive check box

By : Eddie Kok
Date : March 29 2020, 07:55 AM
will help you I am using a Repeater control with some attributes like name, age, address and filling these details from the database. I want to use a check box on the Repeater. so when a user click on a checkbox, I want to show the selected details on other panel. My issues is How to add a Checkbox in the repeater and the checkbox should be mutually exclusive check box , well then do, assuming you have jquery
code :
$('checkboxSelector').on('click', function () {
    var me = $(this);
    if(me.is(':checked')) //uncheck all other options
        $(':checkbox').not(me).filter(':checked').prop('checked', false);
Hide the checkbox from a QListView item

Hide the checkbox from a QListView item

By : B Green
Date : March 29 2020, 07:55 AM
wish help you to fix your issue When you call setCheckState or setCheckable, the qt will update the data of list item by adding or setting a Qt::CheckStateRole data. If the Qt::CheckStateRole data is existed, the check icon will be shown. So you need remove it from the data map of the list item.
Finally, the code of hideCheckBox should be:
code :
void MyModel::hideCheckBox(int row)
    // check the item pointer
    QStandardItem* pitem = item(row);
    if (pitem == NULL) return;

    // find and delete the Qt::CheckStateRole data
    QMap<int, QVariant> mdata = itemData(pitem->index());
    if (mdata.remove(Qt::CheckStateRole))
        setItemData(pitem->index(), mdata);
CheckBox in QListView using QSqlTableModel

CheckBox in QListView using QSqlTableModel

By : Deepak Shaw
Date : March 29 2020, 07:55 AM
wish help you to fix your issue A possible option is to enable the flag Qt::ItemIsUserCheckable, and overwrite the data() and setData() methods when the role is Qt::CheckStateRole, to store the data we create a dictionary.
code :
class TableModel(QSqlTableModel):
    def __init__(self, *args, **kwargs):
        QSqlTableModel.__init__(self, *args, **kwargs)
        self.checkeable_data = {}

    def flags(self, index):
        fl = QSqlTableModel.flags(self, index)
        if index.column() == 1:
            fl |= Qt.ItemIsUserCheckable
        return fl

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.CheckStateRole and (self.flags(index)&Qt.ItemIsUserCheckable != Qt.NoItemFlags):
            if index.row() not in self.checkeable_data.keys():
                self.setData(index, Qt.Unchecked, Qt.CheckStateRole)
            return self.checkeable_data[index.row()]
            return QSqlTableModel.data(self, index, role)

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.CheckStateRole and (self.flags(index)&Qt.ItemIsUserCheckable != Qt.NoItemFlags):
            self.checkeable_data[index.row()] = value
            self.dataChanged.emit(index, index, (role,))
            return True
        return QSqlTableModel.setData(self, index, value, role)
def createConnection():
    db = QSqlDatabase.addDatabase("QSQLITE");
    if not db.open():
        print("Cannot open database"),
        print("Unable to establish a database connection.\n"
                        "This example needs SQLite support. Please read "
                        "the Qt SQL driver documentation for information how "
                        "to build it.\n\n"
                        "Click Cancel to exit.")
        return False

    query = QSqlQuery()
    query.exec_("create table person (id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "firstname VARCHAR(20), lastname VARCHAR(20))");
    query.exec_("insert into person(firstname, lastname) values('Danny', 'Young')");
    query.exec_("insert into person(firstname, lastname) values('Christine', 'Holand')");
    query.exec_("insert into person(firstname, lastname) values('Lars', 'Gordon')");
    query.exec_("insert into person(firstname, lastname) values('Roberto', 'Robitaille')");
    query.exec_("insert into person(firstname, lastname) values('Maria', 'Papadopoulos')");

    return True

class Widget(QMainWindow):
    def __init__(self):
        lv = QListView(self)
        model = TableModel(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    if not createConnection():
    ex = Widget()
python - checkbox selection in QListView

python - checkbox selection in QListView

By : Christopher Mueller
Date : March 29 2020, 07:55 AM
hop of those help? The problem is caused because the states of a QCheckBox are 3:
code :
import sys
from PyQt4 import Qt, QtCore, QtGui

class ChecklistDialog(QtGui.QDialog):

    def __init__(
        super(ChecklistDialog, self).__init__(parent)

        self.name = name
        self.icon = icon
        self.model = QtGui.QStandardItemModel()
        self.listView = QtGui.QListView()

        for string in stringlist:
            item = QtGui.QStandardItem(string)
            check = \
                (QtCore.Qt.Checked if checked else QtCore.Qt.Unchecked)


        self.okButton = QtGui.QPushButton('OK')
        self.cancelButton = QtGui.QPushButton('Cancel')
        self.selectButton = QtGui.QPushButton('Select All')
        self.unselectButton = QtGui.QPushButton('Unselect All')

        hbox = QtGui.QHBoxLayout()

        vbox = QtGui.QVBoxLayout(self)

        if self.icon:


    def onAccepted(self):
        self.choices = [self.model.item(i).text() for i in
                        if self.model.item(i).checkState()
                        == QtCore.Qt.Checked]

    def select(self):
        for i in range(self.model.rowCount()):
            item = self.model.item(i)

    def unselect(self):
        for i in range(self.model.rowCount()):
            item = self.model.item(i)

if __name__ == '__main__':
    fruits = [
        'Honeydew Melon',
        'Ugli Fruit',
    app = QtGui.QApplication(sys.argv)
    form = ChecklistDialog('Fruit', fruits, checked=True)
    if form.exec_() == QtGui.QDialog.Accepted:
        print '\n'.join([str(s) for s in form.choices])
Related Posts Related Posts :
  • How to avoid littering header files with std::
  • Why is this program not working? (Program to copy contents of file to another)
  • Difference between DBus and other Interprocess Communications method
  • How to fill a part of a multidimensional array in C++?
  • C++ SFML Game programming linkage error
  • How do GTK and Qt integrate with Linux in comparison to how they integrate with Windows and OS X?
  • Complexity analysis of loop with limited looping time
  • Boost test fails with enum classes inside namespaces
  • is this a function declaration?
  • Socket recv() one byte at a time
  • C++ Glibc Detected error. Double Free or corruption
  • OpenCV - How to write IplImage array in Mat form?
  • Qt event when anything changed on the window/screen + Screenshot
  • OpenGL Linker error, linking with uncompiled shader
  • Find 4 specific corner pixels and use them with warp perspective
  • Cin Execution Not Working (program.exe < filewithdata.txt)
  • cudaMallocManaged causes Access Violation
  • How to correctly read a value from stdin into a variable
  • Binary Search Tree Forgetting Every Node I Add
  • C++ Return Value from function not same as that value in function
  • Microsoft Visual Studio C++, OpenCV animation
  • C++ function pointer syntax. Why does (*) work but * not?
  • C++: Template class binary operator overloading - seg fault?
  • Passing buffer between two terminals (Named Pipe)
  • C++ parse sub-string to integer
  • Create stereo context for modern opengl
  • Memory leak, when using GLM
  • Get Control under cursor
  • Is this proper behavior? std::map iterator invalidation
  • 2D isometric engine - Math problems - Cube selection - diamond shape map
  • Open second window in Qt
  • Stack Overflow error with Vectors
  • Pure Virtual Friend Class
  • Object initialization syntax in C++
  • Variable undefined error
  • C++ tolower/toupper char pointer
  • Overhead with std::function
  • Is there a way to make a loop that get user input but doesn't stop if the user doesn't input anything?
  • OpenCV in cmake-based project: checking for contrib modules
  • shared_ptr vs unique_ptr uses in classes and children
  • MFC dialog Border padding changed after switching from VS2010 to 2012 or later
  • String rotator in C++ (bitwise rotation)
  • Custom sort vector of pair based on their values
  • Pointer to const overloaded member function
  • how to avoid this for-loop mess in c++?
  • Can the state of a standard C++ iostream manipulator be polled?
  • How to make sure a data type is as large as it needs to be in C++
  • Why is my first ofstream output in my else block missing the fill character?
  • Returning static/ normal arrays in recursion/another function
  • c++, why use const std::string & parameterName?
  • expression did not evaluate to a constant in C++ VS
  • Owner object that takes pre-created values ? Wrong design?
  • Cannot use Macro in a C++ constructor?
  • vector is loosing mat4 information
  • Invalid declarator before with map of struct?
  • std::initializer_list to return member variables returns incorrect values
  • Unable to use Boost + Qt in Mac
  • Passing template function and overload as function argument
  • non standard extension warning when searching in a vector of unique_ptrs
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co