Evgenii Legotckoi
Sept. 4, 2015, 9:54 p.m.

Qt/C++ - Lesson 016. How to set QCheckBox in the cell center in QTableWidget?

One of the first problems in working with The QTableWidget , which are trying to solve, start to work with this widget - setting QCheckBox in the middle of the cell. The fact that the standard check box in QTableWidget checkbox attached to the left edge of the cell, while the right side is given for explanatory text. But the text may not be, but the area still remains. But at the same time it allows you to set QTableWidget in his cell widgets, which we use to solve this problem.

This article is an extension of a previous article on working with QTableWidget , therefore, to see the full code of the project I encourage you also to the article. This article provides only the code necessary to solve the problem.

Project Structure for QCheckBox center

Project structure remains the same as in the previous article .

mainwindow.ui

The form for the application window QCheckBox In the main application will be placed:

  • QTableWidget
  • QLable

mainwindow.cpp

Instead of the standard checkbox will be used to set the widget layer in it, which will contain QCheckBox , which will be located in the center of the widget. It will also be shown a way to get the state of the checkbox of this widget. In the previous lesson, create a table with the devices and odd devices were marked marked checkboxes.

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. MainWindow::MainWindow(QWidget *parent) :
  5. QMainWindow(parent),
  6. ui(new Ui::MainWindow)
  7. {
  8. /* The code from the previous lesson QTableWidget */
  9. }
  10.  
  11. MainWindow::~MainWindow()
  12. {
  13. delete ui;
  14. }
  15.  
  16. /* The method to configure the interface,
  17.  * the method will be carried out to fill QTableWidget records from the table
  18. * */
  19. void MainWindow::createUI(const QStringList &headers)
  20. {
  21. /* The code from the previous lesson QTableWidget */
  22.  
  23. QSqlQuery query("SELECT "
  24. DEVICE ".id, "
  25. DEVICE "." DEVICE_CHECK_STATE ", "
  26. DEVICE "." DEVICE_HOSTNAME ", "
  27. DEVICE "." DEVICE_IP ", "
  28. DEVICE "." DEVICE_MAC
  29. " FROM " DEVICE);
  30.  
  31. /* Perform filling QTableWidget records using a loop
  32. * */
  33. for(int i = 0; query.next(); i++){
  34. // Insert row
  35. ui->tableWidget->insertRow(i);
  36. /* Set the id column in the first taking it from the result of the SQL-query.
  37.   * This column will be hidden
  38. * */
  39. ui->tableWidget->setItem(i,0, new QTableWidgetItem(query.value(0).toString()));
  40.  
  41. // Create a widget that will contain a checkbox
  42. QWidget *checkBoxWidget = new QWidget();
  43. QCheckBox *checkBox = new QCheckBox(); // We declare and initialize the checkbox
  44. QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); // create a layer with reference to the widget
  45. layoutCheckBox->addWidget(checkBox); // Set the checkbox in the layer
  46. layoutCheckBox->setAlignment(Qt::AlignCenter); // Center the checkbox
  47. layoutCheckBox->setContentsMargins(0,0,0,0); // Set the zero padding
  48. /* Check on the status of odd if an odd device,
  49.   * exhibiting state of the checkbox in the Checked, Unchecked otherwise
  50. * */
  51.  
  52. if(query.value(1).toInt() == 1){
  53. checkBox->setChecked(true);
  54. } else {
  55. checkBox->setChecked(false);
  56. }
  57. // Set the checkbox in the second column
  58. ui->tableWidget->setCellWidget(i,1, checkBoxWidget);
  59. // Next, pick up all the data from a result set in other fields
  60. ui->tableWidget->setItem(i,2, new QTableWidgetItem(query.value(2).toString()));
  61. ui->tableWidget->setItem(i,3, new QTableWidgetItem(query.value(3).toString()));
  62. ui->tableWidget->setItem(i,4, new QTableWidgetItem(query.value(4).toString()));
  63. }
  64.  
  65. ui->tableWidget->resizeColumnsToContents();
  66.  
  67. /* In this section we take a code state checkboxes, and in order to derive their QLabel
  68. * */
  69. QString str = QString("Состояния чекбоксов:");
  70.  
  71. for(int i = 0; i < 4; i++){
  72. // Taking the widget from the cell
  73. QWidget *item = ( ui->tableWidget->cellWidget(i,1));
  74. // Taking the widget from the layout and cast it to QCheckBox
  75. QCheckBox *checkB = qobject_cast <QCheckBox*> (item->layout()->itemAt(0)->widget());
  76.  
  77. if(checkB->isChecked()){
  78. str += " 1 "; // adding to a string " 1 " , if true
  79. } else {
  80. str += " 0 "; // otherwise " 0 "
  81. }
  82. }
  83. // Set text in QLabel
  84. ui->label->setText(str);
  85. }

Result

The result is an application that looks like this.

Application with QCheckBox in the center of the cell QTableWidget

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html