1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QtWidgets>
#include "mainwindow.h"
MainWindow::MainWindow()
{
QMenu *fileMenu = new QMenu(tr("&File"));
QAction *quitAction = fileMenu->addAction(tr("E&xit"));
quitAction->setShortcut(tr("Ctrl+Q"));
QMenu *tableMenu = new QMenu(tr("&Table"));
QAction *tableWidthAction = tableMenu->addAction(tr("Change Table &Width"));
QAction *tableHeightAction = tableMenu->addAction(tr("Change Table &Height"));
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(tableMenu);
//! [0]
tableWidget = new QTableWidget(this);
//! [0]
tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
connect(quitAction, &QAction::triggered, this, &QWidget::close);
connect(tableWidthAction, &QAction::triggered, this, &MainWindow::changeWidth);
connect(tableHeightAction, &QAction::triggered, this, &MainWindow::changeHeight);
setupTableItems();
setCentralWidget(tableWidget);
setWindowTitle(tr("Table Widget Resizing"));
}
void MainWindow::setupTableItems()
{
//! [1]
tableWidget->setRowCount(10);
tableWidget->setColumnCount(5);
//! [1]
for (int row = 0; row < tableWidget->rowCount(); ++row) {
for (int column = 0; column < tableWidget->columnCount(); ++column) {
//! [2]
QTableWidgetItem *newItem = new QTableWidgetItem(tr("%1").arg(
(row+1)*(column+1)));
tableWidget->setItem(row, column, newItem);
//! [2]
}
}
}
void MainWindow::changeWidth()
{
bool ok;
int newWidth = QInputDialog::getInteger(this, tr("Change table width"),
tr("Input the number of columns required (1-20):"),
tableWidget->columnCount(), 1, 20, 1, &ok);
if (ok)
tableWidget->setColumnCount(newWidth);
}
void MainWindow::changeHeight()
{
bool ok;
int newHeight = QInputDialog::getInteger(this, tr("Change table height"),
tr("Input the number of rows required (1-20):"),
tableWidget->rowCount(), 1, 20, 1, &ok);
if (ok)
tableWidget->setRowCount(newHeight);
}
|